The below series of concepts, questions and answers with explanations will help SDETs to prepare for programming questions in interviews.
Why is Java called platform independent programming language? Explain with example.
Java is platform independent because we write Java code once and then we can execute it in any platform which provides an environment to execute it.
Using the above picture, let’s say we write a java program called HelloWorldApp.java in a Windows platform. When the program is compiled using the compiler, it creates a file called HelloWorldApp.class.
HelloWorldApp.class can be executed by any JVM; be it provided by Windows or Unix or MacOs.
Since we are able to use HelloWorldApp.class in any platform which has a JVM, JAVA is called platform independent programming language; which is one of the strong features of JAVA.
Explain public static void main (String [] args) which is commonly used in a JAVA program?
public - This keyword is an access modifier, which means it specifies who can access the method. ‘public’ signifies it is a public method and can be accessed by all classes.
static – It is keyword in JAVA which defines if it is a part of any specific class or not. main() is made static in JAVA so that it can be accessed without creating the instance of a Class; otherwise JVM will throw exception saying that main() is called even before the object of the class is created.
void – This keyword says that main() method returns nothing.
main – Name of the method.
String args[]: It is the parameter passed to the main method.
main() method is usually the starting point of JAVA programs; but there are exception.
Can we execute some code before main () method starts execution?
Yes, we can. Here is an example.
public class Test {
static{
System.out.println(10+5);
}
public static void main(String[] args) {
System.out.println(20+20);
}
}
Output
15
40
Here, before we get output from main () method, we got the output from static block. This is very important aspect in automation because sometimes we might need to initialize and have properties file elements accessible even before the browser is open.
What is Autoboxing and Unboxing in JAVA?
Autoboxing: When the Java compiler automatically transforms the primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float and Double); then it is called autoboxing.
Unboxing: The automatic transformation of wrapper types (Integer, Float & Double) into their primitive equivalent (int, float, double) is known as Unboxing.
Example of Autoboxing
class AutoboxingExample
{
public static void myMethod(Integer num){
System.out.println(num);
}
public static void main(String[] args) {
/* passed int (primitive type), it would be
* converted to Integer object at Runtime
*/
myMethod(2);
}
}
Output
2
Example of Unboxing
class Unboxing
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
}
}
Output
Value of i: 10
Value of i1: 10
What is postfix and prefix operator in JAVA?
When we say a=x++; it is called a postfix operation is happening. But if we declare b=++y; it is a prefix operation.
a=x++ -- Assignment then increment
b=++y -- Increment then assignment
Let’s have a look at the below program.
public class OperatorTest {
public static void main(String[] args) {
int x= 10;
int y=10;
int a= x++;
int b=++y;
System.out.println(a+" "+b);
}
}
Output
10 11
When we declared integer a, we first assigned the value of x (which is 10) and then increased the value of x. However, when we declared b, we incremented x first (making the value to 11) and then assigned the same to b. That is why the output is different when a & b are printed.
Find if a given number is prime or not
A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are: 2 3 5 7 11 13 17 19 23 etc.
public class PrimeExample {
public void checkPrime(int input) {
boolean flag = false;
int mid = input / 2;
if (input == 0 || input == 1) {
System.out.println(input + " is not prime number");
} else {
for (int i = 2; i <= mid; i++) {
if (input % i == 0) {
flag = true;
System.out.println(input + " is not prime number");
break;
}
}
if (flag == false) {
System.out.println(input + " is prime number");
}
}
}
public static void main(String args[]) {
PrimeExample ex1 = new PrimeExample();
ex1.checkPrime(1);
}
}
Explanation
We are taking input from the user of the checkPrime() method and then verifying if that number can be divided by any other number apart from 1 & the number. Based on the division result, we are printing if the given number is prime or not.
Find the sum of digits of a given number
public class SumOfDigits {
public static void main(String[] a)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int s = in.nextInt();
int sum=0;
while (s!=0)
{
sum=sum+(s%10);
s=s/10;
}
System.out.println(sum);
}
}
}
Explanation
First of all, we are taking an integer input from the user. Then using while loop, we continue to add the remainders of the number after dividing by 10. Finally, we print the sum in console.
Find the smallest & highest number of an integer array
public class FindArrayNumbers {
public static void main(String[] a)
{
int[] arr = { 5, 6, 87, -19, 0 };
int smallest = arr[0];
int highest = arr[0];
for (int j = 1; j < arr.length; j++) {
if (arr[j] < smallest)
smallest = arr[j];
}
for (int k = 1; k < arr.length; k++) {
if (arr[k] > highest)
highest = arr[k];
System.out.println("The smallest number is: "+smallest);
System.out.println("The highest number is: "+highest);
}
}
Explanation
We have declared an array of integers, 2 integers to hold smallest and highest values. Then we are introducing for loop on the array and comparing with the smallest and highest values to check if they are smaller or bigger respectively. Based on the outcome, we are reassigning the values to the variables. Finally, we are printing them in console.
Find the duplicates in an integer array
public class DuplicateNumbers {
public static void main(String[] a)
{
// Initialize array
int[] arr = new int[] { 1, 2, 3, 4, 2, 7, 8, 8, 3, 2 };
System.out.println("Duplicate elements in given array: ");
// Searches for duplicate element
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
System.out.println(arr[j]);
break;
}
}
}
}
}
Explanation
First, we initialize an integer array. Then using a for loop, starting from the first index of the array, we keep on checking until the last element and compare it with the index. If both are same, we print the number and break the inner loop as we do not want to continue when a duplicate of a number is found. However, we keep on iterating the outer loop as we need to find all the duplicates in the array.
How to remove duplicates from an array?
We can use Set (from JAVA collection framework) data structure to remove duplicates in an array.
class DuplicateRemoval {
// Function to remove duplicate from array
public static void removeDuplicates(int[] arr)
{
LinkedHashSet<Integer> set
= new LinkedHashSet<Integer>();
// adding elements to LinkedHashSet
for (int i = 0; i < a.length; i++)
set.add(a[i]);
// Print the elements of LinkedHashSet
System.out.print(set);
}
public static void main(String[] args)
{
int a[] = {5,2,6,8,6,7,5,2,8};
// Function call
removeDuplicates(a);
}
}
Explanation
In the above program we define a method called removeDuplicates() which takes an array of integers with duplicates as input. Thereafter, a set is defined and we keep on pushing array elements to that set. If there is a duplicate found in the array, that is not inserted in the set as set does not allow duplicates. Finally, the set is printed.
Output
[5, 2, 6, 8, 7]
Find if a given number is palindrome.
A palindrome is a number/string which is same if read from the end. For example - 323 is a palindrome because it is same if read from either front/rear.
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println(" The number is a palindrome number ");
else
System.out.println("The number is not a palindrome");
}
}
Output
The number is a palindrome number
Find if a given year is leap year or not.
A leap year is a year which has 366 days. To determine a year is a leap year or not, follow the below steps:
If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
The year is a leap year (it has 366 days).
The year is not a leap year (it has 365 days).
public class LeapYear {
public static void isLeapYear(int year) {
if(year%400==0 || (year%100!=0 && year%4==0))
{
System.out.println("The given year "+year+" is a leap year");
}
else System.out.println("The given year "+year+" is not a leap year");
}
public static void main(String args[]) {
isLeapYear(1624);
}
}
Output
The given year 1624 is a leap year
Develop a program to print Fibonacci series.
public class FibonacciNumbers {
public static void printFibonacciSeries(int count) {
int a = 0;
int b = 1;
int c = 1;
for (int i = 1; i <= count; i++) {
System.out.print(a + ", ");
a = b;
b = c;
c = a + b;
}
}
public static void main(String args[]) {
printFibonacciSeries(10);
}
}
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Find the common elements between 2 arrays
public class Intersection {
public static void getIntersection(int a[], int b[]) {
int []x=new int[a.length+b.length];
int c= 0;
for(int i = 0; i<a.length; i++ )
{
for (int j = 0; j<b.length; j++)
{
if(a[i]==b[j])
{
x[c]=a[i];
c++;
break;
}
else continue;
}
}
for(int m=0;m< c; m++)
{
System.out.println(x[m]);
}
}
public static void main(String args[]) {
int[] x= {2,5,3,7,1};
int[] y={5,2,9,0,1};
getIntersection(x,y);
}
}
Explanation
getIntersection() method takes 2 integer arrays as input. We define a new empty array of the combined length of those 2 integer array. Afterwards, we traverse the arrays and whenever there is a match; we insert the element into the new array. Finally, we print the final array, which contains the common elements of 2 input arrays.
Find the closest/smallest difference between 2 array elements
public class ClosestDiff {
public static void findClosestDiff(int[] a) {
Arrays.sort(a);
int distance = a[1]-a[0];
int firstNum=a[0];
int secondNum=a[1];
for (int i=0;i<a.length;i++)
{
if(i==a.length-1) continue;
if((a[i+1]-a[i])<distance)
{
distance = a[i+1]-a[i];
firstNum=a[i+1];
secondNum=a[i];
}
}
System.out.println("The shortest distance is: "+distance);
System.out.println("The numbers are: "+firstNum+" "+secondNum);
}
public static void main(String args[]) {
int[] testArray = {3, 9, 50, 15, 99, 7, 98, 65};
findClosestDiff(testArray);
}
}
Output
The shortest distance is: 1
The numbers are: 99 98
Explanation
The simplest solution to this question is to sort the array and compare each pair of numbers and store the result in integer variables. Once the comparison (for loop) is completed, we print the result in the console.