How to attach JDK java source code to Eclipse?

If you try to see the code for JDK classes you might get this error:
Source not found. The JAR file …\rt.jar has no source attachment.

To fix this you need to attach the JDK to your IDE.

In Eclipse, select Windows -> Preferences -> Java -> Installed JREs , select the installed JDK, expands

rt.jar

, select “Source attachment” and find the

src.zip

from your disk drive, which is under the folder your JDK is installed.

 

 

Java code to find index of longest repeated letters in a string

Here’s the Java code to find index of the longest consecutive sequence of repeated letters in a string. If there is more than one run with the same length, the index of the first one is returned.
For example, if the string is(“bbbccffffiiiffff”), the program should return 5 as the longest sequence is ffff and it first appears on index 5.

Continue reading

Java code to determine the validity of a binary search tree

Write a code to determine the validity of a binary search tree (BST). A binary search tree is rooted binary tree, whose internal nodes each store a key and each have two distinguished sub-trees, commonly denoted left and right. The key in each node must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-tree. Below is an example of a BST:

Binary_search_tree

Continue reading

Mockito: How to mock a methods to get a parameter and return a specific value every time it’s called?

        PortBuildNumberGenerator mockBuildNumberGenerator = mock(PortBuildNumberGenerator.class);
        when(mockBuildNumberGenerator.generateNextPortBuildNumberInSequence(anyString())).thenAnswer(new Answer<string>() {

            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                return Integer.toString(Integer.parseInt((String)args[0]) + 1);
            }
        });