Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Wednesday, May 1, 2024

Interview preparation series Java: Are you not getting interview and/or coding test invites?

Are you not getting interview and/or coding test invites? 

These days it is pretty common. So, first of all, I would advice, consider reviewing your CV/Resume. Kindly do not exaggerate listing your skills, by copying from others. The technical panels are smart to judge how much truth is in it. Focus on elaborating on your role, job duties and some of the key challenges that you may have faced in the projects that you have been a part of, your professional achievements and certifications. My advice to freshers is they should put focus on their academic projects, and challenges faced in executing them and the certifications.

Now, if you get an invite for interview/coding test with a very short notice, how much prepared do you think you are? 

If you are among a small set of lucky candidates who received the interview/coding test invites, you still are in a competition.Thus, you need smart preparation to compete fairly, which includes a lot of coding practice on a regular basis. Below are my recommendations for preparing well:

Java:

1. Thoroughly study and memorize the functions under java.lang.Math package. You may ask why? Because over past 10 years, most of the coding tests ask require you to solve either a mathematical or a numerical problem. So without having a solid command over Math package, you can't solve most of the problems.

2. Focus on Java 8 onward features and coding styles. These days Java 6 style coding is old-fashioned and the industry trends follow Functional programming, including asynchronous functions (lamda), bi-functions and its use in stream() operations. In some of the online coding tests, you will be asked to only write the missing part of the code in a method. If you are not familiar with the aforementioned concepts, then you may miss an opportunity to score, because sometimes the asks will be very simple, but by the time you realize it, the opportunity will turn into a lost opportunity.

3. Thoroughly study and memorize the functions under java.util.Stream package. You may ask why? Again, most coding tests moved to Java 8 and above syntax. So, the expectation is to solve problems using stream() operations. Practice using Array, Strings, charArray, collections, (i.e. List, Set) and map. The idea is to determine whether you are familiar with the java data-structure and collections framework or not, and if you can apply it whenever appropriate in a programming context. 

4. Bitwise operations, sometimes most neglected by the students and professionals, however Bitwise operations are very important to master if you are a Java developer or going to become one. Brush up the bitwise operations and practice the number conversions including Octal, Hexadecimal and Binary numbers, bitwise shift operations, XOR operations. This topic always finds its place either in the online coding test or in the interview process.

5. You might have learned about Data-Structures: Stack, Queue, Dequeue, LinkedList, Tree etc. Do you know when to use it to solve a programming problem? Have you tried using the built-in data-structures in Java in any of your academic or professional code? Being honest with yourself, if you feel you are not comfortable with applying Data-structures, then revisit the concepts, look out for programming practice problems and set out sometime everyday to do practice for at least an hour.

6. None of the programming is complete without its File operations, and Java is not an exception. So please read through java.io.File package, memorize the functions and its parameters, and understand when to use which technique to read and write to files. The interviewers are sometimes more interested in understanding how much you know about the file operation efficiencies.

7. Without DB connection, a standalone program does not deliver value. So, you need to master JDBC connection and Spring Boot alternatives. In the interviews, you may expect questions on DB operations with respect to microservices development. So, getting yourself familiar with MySQL, Postgre, MongoDB will help a lot.

8. Exception handling and debugging is an integral part of any programming language. So, you should be able to tackle questions around efficient ways of handling errors and exceptions, including raising custom exceptions.

Thursday, August 24, 2023

Interview preparation series: Java 8 Streams and BiFunction - scratch work reference

 Hello readers, in this blog, I am going to show some scratch work, based on the recent interview trends in Test Automation. These days most organizations are expecting people to code using Java 8 style, than Java 6 style, and there is nothing wrong in it, Java has been evolving and helping us optimizing our coding effort. In case, you are a test automation professional and yet to upgrade your coding style to Java 8, then this article will surely help you to break the ice.

No more boring texts to read :) , the complete program is self-explanatory. Major highlight is the use of generic type filter functions, Bi-functions, Optional's and generator functions.

package springboot.webdriver.cucumber;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;

public class Miscellaneous {

public static void main(String[] args) {
//Creating a linked list. Remember this data-structure does not
// allocate contiguous space like array-list. This linked
// list will be used throughout most part of the below code.
LinkedList<Integer> objSearchableLinkedList = new LinkedList<Integer>();
objSearchableLinkedList.add(5);
objSearchableLinkedList.add(1);
objSearchableLinkedList.add(4);
objSearchableLinkedList.add(3);
objSearchableLinkedList.add(2);
//Creating an object of this class, will be used to call
// non-static methods
Miscellaneous practiceLinkedList = new Miscellaneous();
//This map will be used to showcase some Java8 steam() and
// filter() concepts
Map<String,String> objMap = new HashMap<>();
objMap.put("Tamil Nadu","Chennai");
objMap.put("Karnataka","Bengaluru");
objMap.put("West Bengal","Kolkata");
//To diversify the examples creating this List<Integer>.
// Remember we are
//using List<T> interface object, rather than Array-List /
// Linked-List
//reason behind it is, later we can store array-list or
// linked-list vales in it
int[] pval= {11,20,21,22};
List<Integer> objAlist = Arrays.stream(pval).boxed().toList();

//The element() method always returns the HEAD or the first element
//of the LinkedList. The peek() method also returns the same
System.out.println("element() method returns the first element" +
" of the linked-list, peek() method also does the same "
+ objSearchableLinkedList.element());

//Find if a given number is present in the Linked List and return
// its index, in Java 6 style
System.out.println("The Linked-list is hardcoded with values" +
" between 1 to 5. Now enter a number to be searched" +
" in the linked-list: ");
//You need to enter the value in the execution prompt
//for the program to resume.
int input = new Scanner(System.in).nextInt();
System.out.println("Output returned by Java 6 style:");
practiceLinkedList.findInputInLinkedList(objSearchableLinkedList,
input);
System.out.println("Output returned by Java 8 style:");
//Below example will do the same in Java 8 style
practiceLinkedList.findInputInLinkedListJava8(
objSearchableLinkedList,
input);

//Sort and display the integer Linked-List values in Ascending order
System.out.println("Sorted values of Linked-List in ascending" +
" order: "
+ objSearchableLinkedList.element());
objSearchableLinkedList.sort(Comparator.
comparingInt(Integer::intValue));
objSearchableLinkedList.forEach(System.out::println);

//sort and display elements from a List of integer in reverse order
System.out.println("Sorted values of List in descending " +
"order/reverse: "
+ objSearchableLinkedList.element());
List<Integer> objList = objAlist.stream().sorted(Comparator.
reverseOrder())
.toList();
objList.forEach(System.out::println);

//Using BiFunction and generic filter method to find integers in
// a LinkedList whose values are greater than 2
List<Integer> result1 = practiceLinkedList
.filterList(objSearchableLinkedList,2,
practiceLinkedList::filterByValue);

System.out.println("BiFunction on Integer Linked-List output: "
+result1.toString());

//Using BiFunction and generic filter method to find a string in
// a Map values, where the string length is less than or equal
// to 7
List<String> result2 = practiceLinkedList.filterMap(
objMap,7,practiceLinkedList::filterByStringLength
);
result2.forEach(a->System.out.println("BiFunction on map" +
" output: "+a));

//Below is a use case for using Optional and using it with streams
String testString = new Random().nextInt(1,5)%2==0
?"hello":null; //Generating random string value
Optional<String> optString = Optional.ofNullable(testString);
assert(optString.isPresent());
optString.ifPresent(val -> System.out.println("Length of String: "
+val.length()));
Optional<String> optString2 = optString.stream().findFirst();
optString2.ifPresent(System.out::println);

//Below is use case for Generator function
List<Integer> objIntegerList = Arrays.asList(1,2,2); //input
//Below are generator functions, which we are going to chain together
Function<List<Integer>, Integer> function = (val)->val
.stream().map(X-> X*2)
.mapToInt(B->B).distinct().sum();
Function<Integer,Integer> function2 = (val1) -> val1 *10;
Function<Integer,Integer> function3 = (val2) -> val2*100;
//Chaining generator functions call
Integer result = function3.andThen(function2).apply
(function.apply(objIntegerList));
System.out.println("Result: " + result);

}

/**
* This method will be supplied as parameter in place of the
* BiFunction. The BiFunction will be responsible to apply
* this method to the inputs to the generic filterList method
* and will return the output
* @param val
* @param size
* @return
*/
private Integer filterByValue(Integer val, Integer size) {
if (val > size) {
return val;
} else {
return null;
}
}
//Another support method to be used as BiFunction parameter
private String filterByStringLength(String val, Integer size) {
if (val.length()<=size) {
return val;
} else {
return null;
}
}

/**
* This is a generic type implementation of a custom filter method.
* Why do we need one? Well, the stream().filter() methods can take
* only one variable as argument. If we need two variables as
* argument, then we need to use BiFunction<T, U, R> function().
* If you study the below method, the first argument takes List<T>,
* Second argument will determine the type by the passed value,
* and the third argument is a BiFunction.
* @param list1
* @param condition
* @param func
* @param <T>
* @param <U>
* @param <R>
* @return
*/
protected <T, U, R> List<R> filterList(List<T> list1,
U condition, BiFunction<T, U, R> func) {
//If you want to return different type of value,
//you can modify the return type of result here
List<R> result = new ArrayList<>();
for (T t : list1) {
//The apply(t,condition) method is a special method
// introduced by Java 8 Functional programming
R apply = func.apply(t, condition);
if (apply != null) {
result.add(apply);
}
}
return result;
}
//Another generic type function, which will be applied to a Map
protected <T, U, R> List<R> filterMap(Map<T,T> map1,
U condition, BiFunction<T, U, R> func) {
//If you want to return different type of value,
//you can modify the return type of result here
List<R> result = new ArrayList<>();
for (T t : map1.values()) {
//The apply(t,condition) method is a special method
// introduced by Java 8 Functional programming
R apply = func.apply(t, condition);
if (apply != null) {
result.add(apply);
}
}
return result;
}

//This method uses Java 6 style syntax to find and return an element
// from the linked list
public void findInputInLinkedList(LinkedList<Integer> objLinkedList,
Integer input)
{
ListIterator<Integer> objIterator= objLinkedList
.listIterator(0);
AtomicBoolean notFoundFlag = new AtomicBoolean();
notFoundFlag.set(true);
System.out.println("Remember Peek value in Linked List " +
" never changes, until a pollFirst() method is executed" +
" so, current peek always returns the Head:" +
objLinkedList.peek());
while(objIterator.hasNext()) {
var value = objIterator.next();
if(Objects.equals(value, input)) {
notFoundFlag.set(false);
System.out.println("input value present in the linked list: "
+ input + ", its index is: "+objLinkedList.
indexOf(value));
break;
}else{
notFoundFlag.set(true);
}
}
if(notFoundFlag.get()) {
System.out.println("input value is NOT present in the linked list");
}
}
//This method uses Java 8 style syntax to find and return element
//from the linked list
public void findInputInLinkedListJava8(LinkedList<Integer> objLinkedList,
Integer input)
{
//Atomic values are mutable, and accessible from Lamda functions/methods
AtomicInteger i = new AtomicInteger();
int indexOfElement = objLinkedList.stream()
.peek(val -> i.incrementAndGet())
.anyMatch(target -> Objects.equals(target, input)) ?
i.get() - 1 : -1;
if(indexOfElement >= 0)
System.out.println("input value present in the linked list: "
+ input + ", its index is: " + indexOfElement);
else {
System.out.println("input value is NOT present in the linked list");
}
}
}

Here are the outputs:

element() method returns the first element of the linked-list, peek() method also does the same 5
The Linked-list is hardcoded with values between 1 to 5. Now enter a number to be searched in the linked-list: 
4
Output returned by Java 6 style:
Remember Peek value in Linked List  never changes, until a pollFirst() method is executed so, current peek always returns the Head:5
input value present in the linked list: 4, its index is: 2
Output returned by Java 8 style:
input value present in the linked list: 4, its index is: 2
Sorted values of Linked-List in ascending order: 5
1
2
3
4
5
Sorted values of List in descending order/reverse: 1
22
21
20
11
BiFunction on Integer Linked-List output: [3, 4, 5]
BiFunction on map output: Chennai
BiFunction on map output: Kolkata
Length of String: 5
hello
Result: 6000

Process finished with exit code 0

Saturday, July 8, 2023

Interview preparation series: Write a Java Program to calculate the angle formed between the hour and the minute arms in an analog clock

In this post, I am going to solve this programming puzzle following a simple approach. If you have any better approach in mind, please mention in comment. If you are liking my posts, then please share it with your friends.

Steps to solve the problem during interview or online test:

1. Patiently analyse the problem statement for 2-3 minutes, conceptualize the expected calculations. In our case, we know that analog clocks have overall 360 degree angle. The hour hand moves 30 degrees between each hour. The minute arm moves 6 degrees between each minutes. The hour hand also moves 0.5 degrees each minute. On 60th minute, the hour arm moves to a new hour, and the meeting arm gets reset to zero. When hour ==12, then there is no angle formed between hour and minute arms. 

2. Use, any of your favorite Java IDE. (Prerequisites: Java 6 or above installed, Set JAVA_HOME)

3. Create a Java class file, name it following the best practices

4. Create the main method

5. It's always a good practice to take inputs from the user, rather than using hard-coded input values. This creates a positive impact in the interviewers mind.

6. Write the logic in simplistic way possible

7. Ensure you are displaying the expected output

8. Do a proof read, before executing for the first time, if the program fails at first run, it may create a negative impact in the interviewers mind

9. Run the program against different inputs to proof the logic is correct. For online tests, upon the code submission it will auto trigger unit tests, and highlight any failures. You can fix the issues before the test gets timeout.

public class CalculateHourAndMinuteArmAnglesInAnAnalogClock {
public static void main(String[] args) {
/**
* Taking two inputs from the user at runtime
* hour: Represents the hour arm value of an analog clock
* minute: Represents the minute arm value of an analog clock
*/
int hour = new Scanner(System.in).nextInt();
int minute = new Scanner(System.in).nextInt();
//Declaring a local variable which will hold the final value of the
// computed angle
double angle;
//We need to ensure that the user has entered correct data, otherwise
// we will
// throw a RuntimeException
if (hour > 0 && hour <=12 && minute >= 0 && minute<=60) {
//if user enters minutes=60, then we will add 1 to the hour value,
// and reset minute to 0
if(minute==60 && hour<12) {
hour += 1;
minute=0;
}
//if hour=12, then we need to set hour = 0, and compute the
// angle between 12 and the minute value
if(hour==12) {
hour = 0;
angle = Math.abs(hour - (minute * 6));
}//Otherwise, we will calculate the angle as follows
else {
angle = Math.abs((60 * hour) * 0.5 - (minute * 6));
}
System.out.println("hour = " + hour);
System.out.println("minute = "+minute);
System.out.println("Angle between the hour and the " +
"minute arms of an analog clock is: " + (int) angle
+ " degrees");
}else{
throw new RuntimeException("Invalid inputs, hour should be" +
" >=1 and <=12, and minute should be >=0 and <=60");
}
}
}

Test Automation Strategy for Oracle Forms application running in Citrix servers

  Context : There are many product based applications developed using Oracle Forms and Java thick-client architecture, and most of them are ...