Sunday, March 13, 2022

Shallow and deep cloning

Shallow Copy:

When we do a copy of some entity to create two or more than two entities such that changes in one entity are reflected in the other entities as well, then we can say we have done a shallow copy. In shallow copy, new memory allocation never happens for the other entities, and the only reference is copied to the other entities

Deep Copy:

When we do a copy of some entity to create two or more than two entities such that changes in one entity are not reflected in the other entities, then we can say we have done a deep copy. In the deep copy, a new memory allocation happens for the other entities, and reference is not copied to the other entities. Each entity has its own independent reference. 

How will you print numbers from 1 to 100 without using loop?

Solution: Use recursive to print numbers without loop.

public class PrintNumbers {

public static void main(String args[]) {

printnumbers(5);

}

public static void printnumbers(int n) {

if(n>0) {

System.out.println(n);

printnumbers(n-1);

}

}

}

Saturday, March 12, 2022

Check if string is a palindrome after removing one character.

public class Program2 {

    public static boolean makePalindrome(String mjono) {

        StringBuilder sb = new StringBuilder(mjono);

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

            sb.deleteCharAt(i);

            if(isPalindrome(sb.toString())){

                return true;

            } else {

                sb.insert(i, mjono.charAt(i));

            }

        }

        return false;

    }

    private static boolean isPalindrome(String str) {

        return str.equals(new StringBuilder(str).reverse().toString());

    }

    public static void main(String[] args) {

        System.out.println(makePalindrome("ABCBXA"));

        System.out.println(makePalindrome("ABCBAX"));

        System.out.println(makePalindrome("ABCXBA"));

        System.out.println(makePalindrome("ABCDE"));

        System.out.println(makePalindrome("BAAAAC"));

    }

}

Friday, March 11, 2022

If we try to insert duplicate values in a Set, What will happen?

 Just it wont add, It wont give compile time error and run time error.

Two arrays common numbers with minimum complexity

public void findCommon(in[] a, int[] b){

    Set<Integer> s = new HashSet(Arrays.stream(a).boxed().collect(Collectors.toList()));

    s.retainAll(Arrays.stream(b).boxed().collect(Collectors.toList()))

   System.out.println("Find common number:"+s)

}