Thursday, 30 May 2019

Java program to find second largest number in an array

       This is familiar interview question for the middle level developers. Interviewer will check the coding logic of the candidate and best solution(performance level).

       In this question, there are two solutions to find the second largest number in the given array.

1) Using Sort - This is simple one, you have to sort the array in descending order and return the second element from the sorted array. Time complexity of this approach is O(nlogn)

2) Single Loop using Traversal :- Use single for loop,Inside for loop find the largest number and second condition to find the second largest number using first largest number.
Time complexity of this approach is O(n). This is the better solution compared to first one.

Let's see the below example to find the second largest number in an array,

SecondLargestNumber.java,

package com.test;

public class SecondLargestNumber {
 
         public static void main(String[] args) {
  
                  int[] arr = {2, 3, 4, 10, 28, 38, 88, 10};
  
                  int firstLargeNum = 0;

                  int secondLargeNum = 0;

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

                         if (arr[i] > firstLargeNum) {

                                  secondLargeNum = firstLargeNum;

                                  firstLargeNum = arr[i];

                         } else if(arr[i] > secondLargeNum && arr[i] != firstLargeNum) {

                                  secondLargeNum = arr[i];

                         }
                  }

                  System.out.println("Second Largest Number is - "+secondLargeNum);
          }

}

Output:-
Second Largest Number is - 38.


Related Posts:--
1) Java Code to Print the Numbers as Pyramid - Examples
2) Java Program to find the Missing Number in an Array
3) Java program to print the first n prime numbers
4)  Java Program to check the given number is a palindrome or not
5) Write a Java program to print the Floyd's triangle

Saturday, 25 May 2019

What is call by value and call by reference in Java ?

     This also one of the important question for experienced Java developers. In this post, we need understand what is call by value(pass by value) and call by reference .  

     Call by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments of the method are always passed by value. 

     With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.

Read Top Java Blogs - Feedspot Top 40 Java Blogs

Is Java call by value or call by reference ?

    Java doesn't pass method arguments by reference; it passes them by value. So Java uses or supports call by value.

     In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in the call by reference, the modification done to the parameter passed are persistent and changes are reflected in the caller's scope. The below example explains the call by value and call by reference with output.


Call by value example:-

   The following code shows an example of call by value. The values of the arguments will remain the same even after the method invocation.

PassByValueExample.java,

package com.test;

public class PassByValueExample {
 
       public static void main(String[] args) {
             int x = 10;
             System.out.println("Value of x before calling method changeValue() - " +x);
             changeValue(x);
             System.out.println("Value of x after calling method changeValue() - " +x);
       }

       public static void changeValue(int x) {
              x = 12;
              System.out.println("Value of x inside method - "+x);
       }
}

Output:-
Value of x before calling method changeValue() - 10
Value of x inside method - 12
Value of x after calling method changeValue() - 10

In the above output, the value of x after invoking the method, will remain same, it doesn't impact on original value.


Call by reference example:-

    The following code is the example of call by reference where List reference passed as an argument of  method. The elements of list will get change when we modify the element in the calling method.

PassByReferenceExample.java

package com.test;

import java.util.ArrayList;
import java.util.List;

public class PassByReferenceExample {

       public static void main(String[] args) {
               List<String> list = new ArrayList<String>();
               list.add("A");
               System.out.println("List before calling method - "+list);
               addElement(list);
               System.out.println("List after calling method - "+list);
       }

       public static void addElement(List<String> list) {
               list.add("B");
               System.out.println("List elements inside method - "+list);
       }
}

Output:-
List before calling method - [A]
List elements inside method - [A, B]
List after calling method - [A, B]


Related Posts:-
1) String Interview Questions and Answers
2) Exception Handling Interview questions and answers
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Interface and Abstract Class Interview Questions and Answers

Friday, 24 May 2019

Builder Design Pattern in Java

        The  Design Pattern is an important question for the experienced(4+ exp) candidates.  For freshers interviewer will check the Singleton or Factory design pattern knowledge but when comes to experience we need to know other design patterns also. In the current post, we will discuss one of the important design pattern i.e Builder Design Pattern. 

Read Top Java blogs, Feedspot Top 40 Java Blogs

What is Builder Design Pattern? 

According to wikipedia definition:-

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

It is used to construct a complex object step by step and the final step will return the object.

When to use ?

 Following are the conditions where we can use builder design pattern,

  • When multiple representation of objects are required.
  • Number of parameter required in constructor is more than manageable(more than 4 or 5)
  • Object creation contains optional parameter.

Guidelines to create the Builder Design Pattern:-

1) Create a static builder class inside the class whose object is to be build by the builder. EmployeeBuilder class is a static class created as in the example.

2) Builder class should have public constructor  with required parameters and outside class should have private constructor. All fields of class should be private.

3) Needs to write methods to get the values of optional parameters.
e.g withFieldPhone(), withFieldAddress and withFieldDateOfBirth().
In example, phone,address and dob are optional parameters.

4) Create builder method in the builder class to get the desired object.

Example:--

Employee.java,

package com.test;

public class Employee {
 
     private int id;
     private String name;
     private int age;
     private String phone;
     private String address;
     private String dob;
 
     private Employee(EmployeeBuilder builder) {
         this.id = builder.id;
         this.name = builder.name;
         this.age = builder.age;
         this.phone = builder.phone;
         this.address = builder.address;
         this.dob = builder.dob;
     }
 
     public int getId() {
         return id;
     }

     public String getName() {
         return name;
     }

     public int getAge() {
         return age;
     }

     public String getPhone() {
         return phone;
     }

     public String getAddress() {
         return address;
     }

     public String getDob() {
         return dob;
     }

     public static class EmployeeBuilder {
  
         private int id;
         private String name;
         private int age;
         private String phone;
         private String address;
         private String dob;
  
         //id, name and age are manadatory fields 
         public EmployeeBuilder(int id, String name, int age) {
             this.id = id;
             this.name = name;
             this.age = age;
         }
  
         public EmployeeBuilder withFieldPhone(String phone) {
             this.phone = phone;
             return this;
         }
  
         public EmployeeBuilder withFieldAddress(String address) {
             this.address = address;
             return this;
         }
  
         public EmployeeBuilder withFieldDateOfBirth(String dob) {
             this.dob = dob;
             return this;
         }
  
         public Employee build() {
             return new Employee(this);
         }
    }    
 
     @Override 
     public String toString() { 
         return "Id - "+id+", Name - "+name+", age - "+age+ ",address - "+ address+
          ", Phone - "+phone; 
     }
  
}

The above code is an example of Builder Design pattern, Now this we can access in below code.

BuilderDesignPatternEx.java,

package com.test;

public class BuilderDesignPatternEx {
 
     public static void main(String[] args) {
         Employee pattern = new Employee.EmployeeBuilder(10, "Kiran",10).withFieldAddress("Sonyal").build();
         System.out.println(pattern);
         //System.out.println(pattern.getName());
     }

}

Output:--

Id - 10, Name - Kiran, age - 10,address - Sonyal, Phone - null


Java built in builder design pattern examples:

StringBuilder and StringBuffer classes are internally used builder design pattern concept.

Thank you for visiting blog..

Monday, 13 May 2019

Java 8 - BiConsumer, BiFunction and BiPredicate Interface Example

        We discussed in earlier posts, Java 8 Consumer Interface, method reference and forEach() method with examples. In this page or post, we will discuss about BiConsumer, BiFunction and BiPredicate Interface with examples.

       All these Interfaces accept two input parameters and returns a result. We will discuss more details of each interface as below.

  • BiConsumer (java.util.function package)

        BiConsumer is a functional interface, has one abstract method i.e accept(), similar to a Consumer Interface. The difference between consumer and BiConsumer is Consumer interface accepts single parameter where as BiConsumer accepts two input parameters, and both doesn’t return anything.

Example:-

package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class BiConsumerExample {
 
         public static void main(String[] args) {
      
                   //Consumer example
                  Consumer<String> strConsumer = str -> System.out.println(str);
                  strConsumer.accept("Java Wolrd");
  
                  //BiConsumer example
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("Hello", "World");
                  BiConsumer<String, String> consumer = (key, value) -> System.out.println("Key - "+ key+", Value - "+value);
    
                  map.forEach(consumer);
         }

}

Output:-
Java World
Key - Hello, Value - World


  • BiFunction (java.util.function package)
         BiFunction interface is also similar to Function interface(It is also functional interface), difference is Function interface will accept one parameter but BiFunction interface accepts two parameters as a input and returns results.

Declaration:-

Interface BiFunction<T,U,R>

Here, 

T - the type of the first argument as input
U - the type of the second argument as input
R - the type of the result of the function

Example:-

package com.test;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {
 
         public static void main(String[] args) {
  
                 //Function example
                Function<Integer, Integer> printNumber = a -> a*10;
                System.out.println("Number is "+printNumber.apply(10));
  
                 //BiFunction example
                BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
                System.out.println("Summation of two number is "+add.apply(3,2));
        }

}

Output:-
Number is 100
Summation of two number is 5


  • BiPredicate (java.util.function package)

        This interface also similar to Predicate interface and it's also functional interface. Predicate interface takes one agrument as input and return boolean value. But BiPredicate interface takes two arguments as input and returns boolean data type same as Predicate interface.

Example:-

package com.test;

import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class BiPredicateExample {
 
         public static void main(String[] args) {
                
                 //Predicate example
                Predicate<String> pr = a -> a.contains("A");
                System.out.println(pr.test("Anil"));
  
                 //BiPredicate example
                BiPredicate<Integer, Integer> biPrdt = (a,b) -> a>10 && b<5;
                System.out.println(biPrdt.test(11, 2));
         }
}

Output:-
true
true


Related Posts:-
1) Java 8 forEach method with examples
2) Method References in Java 8
3) Java 8 features with examples
4) Java 8 - Consumer Interface with examples

Wednesday, 8 May 2019

Method References in Java 8

       In previous post, we learned Consumer Interface in Java 8 with examples. In this post, we will discuss another new feature of java 8, i.e method references.

      A method reference is the shorthand notation for a lambda expression to call a method. In previous versions of Java, we will use object dot method name to call method of the given object. In java 8, using :: operator after the object, to call the method.

Below is the general syntax of a method reference:

Object :: methodName

The example of Method Reference uses,

Using lambda expression,

s -> System.out.println(s)

It replaces using method reference as below,

System.out::println

Examples:-

1)  Instance method of object example(Object::instanceMethod)

MethodRefExample.java,

package com.test;

interface MethodRefInterface {  
       void abstractMethod();  
} 
 
public class MethodRefExample {
  
           public void method(){  
                   System.out.println("This is a method reference example");  
           }  

           public static void main(String[] args) {
                    MethodRefExample methodRef = new MethodRefExample();  
                    MethodRefInterface ref= methodRef::method;
                    ref.abstractMethod();
           }  
}  

Output:- 

This is a method reference example


2) Static method of a Class(ClassName::methodName)

MethodRefStatic.java,

package com.test;

import java.util.Arrays;
import java.util.List;

public class MethodRefStatic {
 
         public static void main(String[] args) {
                   List<Integer> list = Arrays.asList(1, 2, 3, 4);
                   System.out.println("Using lambda expression");
                   list.forEach(num -> printNumbers(num));  //using lambda expression
                   System.out.println("Using method references");
                   list.forEach(MethodRefStatic::printNumbers); //using method references
         }
 
         public static void printNumbers(int number) {
                   System.out.println("Number - " + number);
         }
}

Output:-
Using lambda expression
Number - 1
Number - 2
Number - 3
Number - 4
Using method references
Number - 1
Number - 2
Number - 3
Number - 4


3) Example of method reference to a Constructor(Class::new)

MethodRefConstruct.java,

package com.test;

interface MessageInterface{  
         MethodRefEx getMessage(String msg);  
} 

class MethodRefEx {
 
         MethodRefEx(String msg){  
                  System.out.print(msg);  
         }  
}  
class MethodRefConstruct {  
     
         public static void main(String[] args) {  
                   MessageInterface msg = MethodRefEx::new;  
                   msg.getMessage("Hello World");  
         }  
}  

Output:-
Hello World


Related Posts:--
1) Java 8 - Consumer Interface with examples
2) Java 8 forEach method with examples
3) Java 8 features with examples

Monday, 6 May 2019

Java 8 - Consumer Interface with examples

        In the current post, I will explain you the in-built functional interface Consumer introduced in Java 8 with examples. It contains two methods accept() & andThen(), comes under java.util.function package.

What is java.util.function.Consumer ?

       Consumer<T> is an in-built functional interface introduced in Java 8 and it is in the java.util.function package.  Here T is any type of input arguments. Consumer can be used in all contexts where an object needs to be consumed, i.e it will take argument as an input and some operation needs to be performed on the object without returning any result.  

       This is a functional interface because it contains only one abstract method i.e accept().

Methods in Consumer Interface

  • accept()
  • andThen()

       The accept() method is abstract method, need to implement in the code, it will take one parameter as argument and doesn't return anything.

syntax:-

    void accept(T t);

The following example shows how to use the accept() method of the Consumer interface.

package com.test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerInterface {
 
       public static void main(String[] args) {
  
               List<Integer> values = Arrays.asList(2,3,5,8);
               Consumer<Integer> printInt = new Consumer<Integer>() {
                        @Override
                        public void accept(Integer var) {
                                  System.out.println("Number - "+var);
                        }  
               };
  
               //print the single integer number using consumer interface.
               printInt.accept(10);
  
               //print the integers using consumer interface
               values.forEach(printInt);
       }

}

Output:--
Number - 10
Number - 2
Number - 3
Number - 5
Number - 8


andThen() -   is a default method in Consumer interface. Method andThen(), when applied on a Consumer interface, takes as input another instance of Consumer interface and returns as a result a new consumer interface which represents aggregation of both of the operations defined in the two Consumer interfaces.

syntax:-

default Consumer <T> 
        andThen(Consumer<? super T> after)

The return type of the above method is Consumer and this accepts a parameter after which is the Consumer to be applied after the current one.

The below code is to illustrate the andThen() method,

package com.test;

import java.util.function.Consumer;

public class ConsumerInterface {
 
      public static void main(String[] args) {
  
              Consumer<String> cons1 = str -> {
                        System.out.println(str + " World");
              };
      
              Consumer<String> cons2 = str -> {
                        System.out.println(str + " Java");
              };
  
              cons1.andThen(cons2).accept("Hello");
      }

}

Output:-

Hello World
Hello Java



Related Posts:-
1) Java 8 forEach method with examples
2) Java 8 features with examples