# Java Interview question-7

**Question 61: Find the output of below code snippet. What will print and why?**

```java
package learning;
public class FindOutput3 {
    public static void main(String[] args) {
        String x = "ab";
        change(x);
        System.out.println(x);
    }
    public static void change(String x) {
        x = "cd";
    }
}
/**
* Output: ab
/
```

**Question 62: Write a program to find the occurrence of each word in a given string.**

```java
package learning;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class FindOccurence {
    public static void main(String[] args) {
        String str = "Fear leads to anger; anger leads to hatred; ";
        System.out.println(findCountOfEachWord(str));
    }
    private static Map findCountOfEachWord(String str) {
        return Arrays.stream(str.split(" "))
                .collect(
              Collectors.groupingBy(x -> x, Collectors.counting())
                        );
    }
}
/**
 * Output:
 * {anger;=1, Fear=1, hatred;=1, leads=2, to=2, anger=1}
 */
```

**Question 63: Write a program to find the sum of the entire array result using java 8 streams.**

Criteria are -&gt; Sum of numbers, if odd, multiply by 2, if even keep same, if negative don’t consider.

```java
public class Test2 {
    public static void main(String[] args) {
        int[] arr = {1, 2, -3, 4, 5, 6, -7, 8, 9, 10};
        List<Integer> ls = Arrays.asList(1, 2, -3, 4, 5, 6, -7, 8, 9, 10);
        System.out.println(ls.stream().map(x-> {
            if(x % 2 == 0){
                return x;
            }else if(x %2==1){
                return x*2;
            }else if(x < 0){
                return 0;
            }    
            return null;
        }).collect(Collectors.summingInt(Integer::intValue)));
    }
}
```

**Question 64: Write a program to find even numbers from a list of integers and multiply with 2 using stream java 8.**

```java
public class FindEvenNumerMultiplyBy2 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        List<Integer> ans = list.stream()
                  .filter(x -> x % 2 == 0)
                  .map(x -> x*2).collect(Collectors.toList());
        System.out.println(and);
    }
}
```

**Question 65: Mockito cannot mock this class exception from the Mockito unit testing framework, how to resolve that?**

Mockito can only mock non-private & non-final classes

**Question 66: Write a program for valid parenthesis in java.**

input is — “{()}” so this is a valid parenthesis

String str — “{)(}” this is an invalid parenthesis

```java
package learning;
import java.util.HashMap;
import java.util.Stack;
public class PerenthesisTest {
    // Hash table that takes care of the mappings.
    private final HashMap<Character, Character> mappings;
    // Initialize hash map with mappings. 
    // This simply makes the code easier to read.
    public PerenthesisTest() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
    }
    public static void main(String[] args) {
        PerenthesisTest pt = new PerenthesisTest();
        System.out.println(pt.isValid("[{}]"));
    }
    public boolean isValid(String s) {
        // Initialize a stack to be used in the algorithm.
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // If the current character is a closing bracket.
            if (this.mappings.containsKey(c)) {
                // Get the top element of the stack. 
                // If the stack is empty, set a dummy value of '#'
                char topElement = stack.empty() ? '#' : stack.pop();
                // If the mapping for this bracket doesn't match 
                // the stack's top element, return false.
                if (topElement != this.mappings.get(c)) {
                    return false;
                }
            } else {
                // If it was an opening bracket, push to the stack.
                stack.push(c);
            }
        }
        // If the stack still contains elements, 
        // then it is an invalid expression.
        return stack.isEmpty();
    }
}
/**
 * Output: true
 */
```

**Question 67: Write a program for the below String.**

String str = “wwwwaaadexxxxxxwww”;

output — *“w4a3d1e1x6w3”*

```java
package com.vivek;
public class Compressor {
    public static void main(String[] args) {
        System.out.println(compress("aaaabbacccdddc"));//a4b2a1c3d3c1
        System.out.println(compress("ac"));//a1c1
        System.out.println(compress("acc"));//a1c2
        System.out.println(compress("a"));//a1
        System.out.println(compress("aabcca"));//a2b1c2a1
        System.out.println(compress(""));//""
        System.out.println(compress(null));//null
    }
    public static String compress(String input) {
        if (null == input || input.isEmpty()) {
            return input;
        }
        StringBuilder stringBuilder = new StringBuilder();
        char[] charArray = input.toCharArray();
        char prev = charArray[0];
        int count = 1;
        for (int i = 1; i < charArray.length; i++) {
            if (prev == charArray[i]) {
                count++;
            } else {
                stringBuilder.append(prev).append(count);
                prev = charArray[i];
                count = 1;
            }
        }
        return stringBuilder.append(prev).append(count).toString();
    }
}
/**
 * Output:
 * a4b2a1c3d3c1
 * a1c1
 * a1c2
 * a1
 * a2b1c2a1
 * ""
 * null
 */
```

**Question 68: Find the missing number from array.**

```java
class Solution {
    public int missingNumber(int[] nums) {
        Set<Integer> numSet = new HashSet<Integer>();
        for (int num : nums) numSet.add(num);
        int expectedNumCount = nums.length + 1;
        for (int number = 0; number < expectedNumCount; number++) {
            if (!numSet.contains(number)) {
                return number;
            }
        }
        return -1;
    }
}
```

**Question 69: Why microservices are stateless?**

Statefullness and statelessness are not generally about DB persistence. Also, there are different levels of state(full)(less)ness, I will try to list some examples:

We could say a microservice is stateless if it does not hold information in its internal storage that is critical to serving clients, instead it holds data in external stores (which can be stateful). A good thought experiment is to imagine that your service restarts on a different node between each and every request. If the service can fulfil its purpose this way, it can be usually considered stateless. Another example is that load-balancers can randomly balance requests without using sticky sessions for stateless services. That’s said if your service persists data in a local store (filesystem, etc…), then restarts in another node, and this data was critical for well-functioning, then it is not stateless. So statelessness is not strictly constrained to not holding data in memory.

Stateful service can be anything that holds a state between client accesses, and given this state is destroyed, some requests will fail.

Things get complicated with applications that are stateful internally but externally have a stateless API. For example, an actor-based system can be termed stateful (services know about each other), but automatic failover (actors from dead nodes are migrated to live nodes) can guarantee reliability if paired with persistent actor state storage. As you see, the overall service is stateful, but interactions are stateless through the API.

What is more important than these buzzwords, is how your application behaves in some edge conditions:

* Handling existing processes/sessions/requests during scaling (adding nodes)
    
* Handling the unexpected restart or termination of a service or node
    
* Handling requests during network partitions
    
* and more like these…
    

If your service can remain consistent and performant during these conditions, you are all good.

**Question 70: Recursion vs for loop? which one is best and why?**

Recursion works at the method or the function level, whereas looping is applied at the instruction level. We use iteration by repeatedly executing a set of instructions until the terminating condition is hit

[  
](https://medium.com/tag/java-interview-questions?source=post_page-----517a9b215d6e---------------java_interview_questions-----------------)
