Core Java interview – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 28 Nov 2023 09:40:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Core Java interview – Java2Blog https://java2blog.com 32 32 Java Stream to List https://java2blog.com/java-stream-to-list/?utm_source=rss&utm_medium=rss&utm_campaign=java-stream-to-list https://java2blog.com/java-stream-to-list/#respond Thu, 31 Dec 2020 11:58:42 +0000 https://java2blog.com/?p=11198 In this post, we will see how to convert Stream to List in java.

There are multiple ways to convert Stream to List in java.

Using Collectors.toList()

You can pass Collectors.toList() to Stream.collect() method to convert Stream to List in java. Stream’s collect method performs mutable reduction operation on elements of Stream and Collectors.toList() provides a collector which accumulates elements of Stream into the list.

Here is an quick example:

package org.arpit.java2blog;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ConvertStreamToListMain {
    public static void main(String args[])
    {
        Stream countriesStream = Stream.of("India", "China", "France", "Germany");
        List listOfCountiesName = countriesStream.collect(Collectors.toList());
        System.out.println(listOfCountiesName);
    }
}

Output:

[India, China, France, Germany]

Using Collectors.toCollection()

You can pass Collectors.toCollection() to Stream.collect() method to convert Stream to List in java. This is similar to previous approach, but it gives you more control over type of collection you want.

Here is an example to create LinkedList from Stream.

package org.arpit.java2blog;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ConvertStreamToListMain {
    public static void main(String args[])
    {
        Stream countriesStream = Stream.of("India", "China", "France", "Germany");
        List listOfCountiesName = countriesStream.collect(Collectors.toCollection(LinkedList::new));
        System.out.println(listOfCountiesName);
    }
}
[India, China, France, Germany]

Using foreach

You can iterate over Stream using foreach() method and add elements to the List.

Here is an example to create LinkedList from Stream.

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class ConvertStreamToListMain {
    public static void main(String args[])
    {
        Stream countriesStream = Stream.of("India", "China", "France", "Germany");
        List listOfCountiesName=new ArrayList<>();
        countriesStream.forEach(listOfCountiesName::add);
        System.out.println(listOfCountiesName);
    }
}

This approach is not recommended in case you are using Parallel Stream as elements of the Streams may not be processed in original order. You can use forEachOrdered() method to preserve the order in the List.
Output:

[India, China, France, Germany]

Filter Stream and convert to List

If you want to filter elements from Stream, you can use Stream’s filter method.

package org.arpit.java2blog;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ConvertStreamToListMain {
    public static void main(String args[])
    {
        Stream countriesStream = Stream.of("India", "China", "France", "Germany","Indonesia");
        List listOfCountiesName = countriesStream.filter(country ->country.startsWith("I"))
                                                         .collect(Collectors.toList());
        System.out.println(listOfCountiesName);
    }
}

Output:

[India, Indonesia]

Filter method accepts predicate functional interface to filter a Stream.

Convert infinite Stream to List

You need to limit infinite Stream and then convert it to list.

Here is an exmple:

package org.arpit.java2blog;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ConvertStreamToListMain {
    public static void main(String args[])
    {
        IntStream infiniteIntStream = IntStream.iterate(100, i -> i+1);

        List intList = infiniteIntStream.limit(5)
                                                        .boxed()
                                                        .collect(Collectors.toList());
        System.out.println(intList);
    }
}

Output:

[100, 101, 102, 103, 104]

Here we have used iterate() method to generate an infinite Stream and limited it using limit() method and then converted it to list.

That’s all about Java Stream to List.

]]>
https://java2blog.com/java-stream-to-list/feed/ 0
A In-Depth guide to Java 8 Stream API https://java2blog.com/java-8-stream/?utm_source=rss&utm_medium=rss&utm_campaign=java-8-stream https://java2blog.com/java-8-stream/#comments Thu, 27 Aug 2020 18:30:48 +0000 https://java2blog.com/?p=9554 In this post, we will see an in-depth overview of Java 8 streams with a lot of examples and exercises.

Introduction

You may think that Stream must be similar to InputStream or OutputStream, but that’s not the case.

A Stream represents a sequence of elements supporting sequential and parallel aggregate operations. Stream does not store data, it operates on source data structures such as List, Collection, Array etc.

Most stream operations accept functional interfaces that make it a perfect candidate for lambda expressions.

If you are not well versed with functional interfaces, lambda expressions, and method references, you may want to read the following tutorials before moving ahead.

Types of Stream operations

There are two types of Stream operations.

  1. Intermediate operations: return a stream that can be chained with other intermediate operations with dot .
  2. Terminal operations: return void or non stream output.

Let’s understand with the help of simple example.

package org.arpit.java2blog.stream;

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

public class StreamOperations {

    public static void main(String[] args) {
        List<String> stringList = Arrays.asList("John", "Martin", "Mary", "Steve");

        stringList.stream()
                   .map((s) -> s.toUpperCase())
                   .forEach(System.out::println);
    }
}

Output:

JOHN
MARTIN
MARY
STEVE

Here,
To perform a computation, stream operations are built into a Stream pipeline. Stream pipeline consists of:

  1. source
  2. zero or more intermediate operations
  3. terminal operation.

In our example, Stream pipeline consists of:
Source: stringList
1 Intermediate operation: Map
1 terminal operation: forEach

The below diagram will make it more clear.
map is intermediate operation and foreach is terminal opertion.
StreamBasic

Most stream operations accept parameters as that describes user-defined behaviour, such as lambda expression map((s)->s.toUpperCase()) is passed to map operation.

To get correct behavior, streams parameters should be:
non-interfering: Stream source should not be modified while execution of Stream pipline. You can learn more about interference.
Stateless: In most cases, lambda expressions should be stateless. Its output should not depend on state that might change during execution of Stream pipeline. I have already covered stateful lambda expression in Parallel Stream tutorial.

Stream creation

There are multiple ways to create the Stream.

Empty Stream

empty() method can be used to create an empty stream.

Stream s = Stream.empty()

It is generally used to return Stream with zero elements rather than null.

Collection Stream

Stream can be created from Collection by calling .stream() or .parallelStream()

List stringList=Arrays.asList("Andy","Peter","Amy","Mary");

stringList.stream()
.map((s)->s.toUpperCase())
.forEach(System.out::println);

stringList.stream() will return you regular object stream.

Stream.of

You don’t need to create collection to get a Stream. You can also use .of()

Stream streamArray =Stream.of("X","Y","Z");

Stream.generate()

generate() method accepts Supplier for element generation. It creates infinite Stream and you can limit it by calling limit() function.

Stream<Integer> intStream=Stream.generate(() -> 1).limit(5);
intStream.forEach(System.out::println);
// Output
// 1
// 1
// 1
// 1
// 1

This will create Integer stream with 10 elements with value 1.

Stream.iterate()

Stream.iterate() can also be used to generate infinite stream.

Stream<Integer> intStream = Stream.iterate(100 , n -> n+1).limit(5);
intStream.forEach(System.out::println);
// Output
// 100
// 101
// 102
// 103
// 104

First parameter of iterate method represents first element of the Stream. All the following elements will be generated by lambda expression n->n+1 and limit() is used to convert infinite Stream to finite Stream with 5 elements.

Lazy evaluation

Streams are lazy; intermediate operation are not executed until terminal operation is encounterd.

Each intermediate operation generates a new stream, stores the provided operation or function. When terminal operation is invoked, stream pipeline execution starts and all the intermediate operations are executed one by one.

Let’s understand with the help of example:

Stream<String> nameStream = Stream.of("mohan","john","vaibhav","amit");
Stream<String> nameStartJ = nameStream.map(String::toUpperCase)
                                    .peek( e -> System.out.println(e))
                                  .filter(s -> s.startsWith("J"));

System.out.println("Calling terminal operation: count");
long count = nameStartJ.count();
System.out.println("Count: "+ count);
// Output
// Calling terminal operation: count
// MOHAN
// JOHN
// VAIBHAV
// AMIT
// Count: 1

In preceding output, you can see that unless and until terminal operation count is called, nothing was printed on console.

In the preceding example, peek() method is used to print the element of stream. peek() method is generally used for logging and debugging purpose only.

Order of operations

Let’s see how stream processes the order of operations.
Could you guess output of the program?

Stream<String> nameStream = Stream.of("mohan","john","vaibhav","amit");
Stream<String> nameStartJ = nameStream.map(
        (s) ->
        {
            System.out.println("Map: "+s);
            return s.toUpperCase();

        })
        .filter(
        (s) ->
        {
             System.out.println("Filter: "+s);
             return s.startsWith("J");
        } 
    );

Optional<String> findAny = nameStartJ.findAny();
System.out.println("Final output: "+findAny.get());

Output will be:

Map: mohan
Filter: MOHAN
Map: john
Filter: JOHN
JOHN

Here order of operations might be surprising. A common approach will be to perform intermediate operation on all elements and then perform next operation, but instead each element moves vertically.

This kind of behavior can reduce actual number of operation.
For example:
In preceding example, Strings vaibhav and amit did not go through map and filter operation as we already got result(findAny()) with String john.

Some of the intermediate operations such as sorted are executed on the entire collection. As succeding operations might depend on the result of sorted operation.

Primitive Streams

Apart from regular Stream, Java 8 also provides primitive Stream for int, long and double.
Primitive Streams are:

  1. IntStream for int
  2. LongStream for long
  3. DoubleStream for double

All the primitive Streams are similar to regular Stream with following differences.

  • It supports few terminal aggregate functions such sum(), average(), etc.
  • It accepts specialized function interface such as IntPredicate instead of Predicate, IntConsumer instead of Consumer.

Here is an example of an IntStream.

int sum = Arrays.stream(new int[] {1,2,3})
                .sum();
System.out.println(sum);

// Output 
// 6

Convert Stream to IntStream

You may need to convert Stream to IntStream to perform terminal aggregate operations such as sum or average. You can use mapToInt(), mapToLong() or mapToDouble() method to convert Stream to primitive Streams.
Here is an example:

Stream.of("10","20","30")
      .mapToInt(Integer::parseInt)
      .average()
      .ifPresent(System.out::println);
// Output
// 20.0

Convert IntStream to Stream

You may need to convert IntStream to Stream to use it as any other datatype. You can use mapToObj() convert primitive Streams to regular Stream.
Here is an example:

String collect = IntStream.of(10,20,30)
                          .mapToObj((i)->""+i)
                          .collect(Collectors.joining("-"));
System.out.println(collect);
// Output
// 10-20-30

Employee class

Consider a Employee class which has two fields name, age, listOfCities.

Here listOfCities denotes cities in which Employee has lived so far.

package org.arpit.java2blog.stream;

import java.util.List;

public class Employee implements Comparable{

    private String name;
    private int age;
    private List listOfCities;

    public Employee(String name, int age,List listOfCities) {
        super();
        this.name = name;
        this.age = age;
        this.listOfCities=listOfCities;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List getListOfCities() {
        return listOfCities;
    }

    public void setListOfCities(List listOfCities) {
        this.listOfCities = listOfCities;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + "]";
    }

    @Override
    public int compareTo(Employee o) {
        return this.getName().compareTo(o.getName());
    }
}

This Employee class will be used in all succeeding examples.
Let’s create employeesList on which we are going to perform intermediate and terminal operations.

package org.arpit.java2blog.stream;

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

public class StreamGetListOfEmployees {

    public static void main(String[] args) {
        List employeesList=getListOfEmployees();

        // Write stream code here
    }

    public static List getListOfEmployees() {

        List listOfEmployees = new ArrayList<>();

        Employee e1 = new Employee("Mohan", 24,Arrays.asList("Newyork","Banglore"));
        Employee e2 = new Employee("John", 27,Arrays.asList("Paris","London"));
        Employee e3 = new Employee("Vaibhav", 32,Arrays.asList("Pune","Seattle"));
        Employee e4 = new Employee("Amit", 22,Arrays.asList("Chennai","Hyderabad"));

        listOfEmployees.add(e1);
        listOfEmployees.add(e2);
        listOfEmployees.add(e3);
        listOfEmployees.add(e4);

        return listOfEmployees;
    }
}

Common intemediate operations

Map()

Map() operation is used to convert Stream<T> to Stream<R>. It produces one output result of type 'R' for each input value of type 'T'. It takes Function interface as parameter.
For example:
You have stream of list of employees and you need a list of employee names, you simply need to convert Stream to Stream.

List<String> employeeNames = employeesList.stream()
                                .map(e -> e.getName())
                               .collect(Collectors.toList());
System.out.println(employeeNames);

// Output
// [Mohan, John, Vaibhav, Amit]
StreamMap
Logical representation of Map operation

You can also use map even if it produces result of same type.
In case, you want employee name in uppercase, you can use another map() function to convert string to uppercase.

List<String> employeeNames = employeesList.stream()
                                .map(e -> e.getName())
                                .map(s -> s.toUpperCase())
                                .collect(Collectors.toList());
System.out.println(employeeNames);

// Output
// [MOHAN, JOHN, VAIBHAV, AMIT]

Filter()

Filter() operation is used to filter stream based on conditions. Filter method takes Predicate() interface which returns boolean value.
Let’s say you want to employees whose name starts with ‘A’.
You can write following functional code to achieve the same.

List<String> employeeNames = employeesList.stream()
                                .map(e -> e.getName())
                                .filter(s -> s.startsWith("A"))
                               .collect(Collectors.toList());
System.out.println(employeeNames);

// Output
// [AMIT]
StreamFilter
Logical representation of Filter operation
[![StreamFilter]

sorted()

You can use sorted() method to sort list of objects. sorted method without arguments sorts list in natural order. sorted() method also accepts comparator as parameter to support custom sorting.

💡 Did you know?

Natural order means sorting the list based on comparable interface implemented by list element type.
For example:
List will be sorted on the basis of comparable interface implemented by Integer class.

Here is the sorted() method example

List<Employee> employees = employeesList.stream()
                                            .sorted()
                                            .collect(Collectors.toList());
System.out.println(employees);

// Output
// [Employee [name=Amit, age=22], Employee [name=John, age=27], Employee [name=Mohan, age=24], Employee [name=Vaibhav, age=32]]

Here is the sorted() method example with Comparator as a parameter.

List<Employee> employees = employeesList.stream()
                              .sorted((e1,e2)->e1.getAge() - e2.getAge())
                               .collect(Collectors.toList());
System.out.println(employees);

// Output
// [Employee [name=Amit, age=22], Employee [name=Mohan, age=24], Employee [name=John, age=27], Employee [name=Vaibhav, age=32]]

You can also rewrite this with method reference as below:

List<Employee> employees = employeesList.stream()
                                                .sorted(Comparator.comparing(Employee::getAge))
                                                .collect(Collectors.toList());
System.out.println(employees);

// Output
// [Employee [name=Amit, age=22], Employee [name=Mohan, age=24], Employee [name=John, age=27], Employee [name=Vaibhav, age=32]]

limit()

You can use limit() to limit the number of elements in the stream.
For example:
limit(3) returns first 3 elements in the list.

Let’s see with the help of an example:

List<Employee> employees = employeesList.stream()
                                     .limit(3)
                                  .collect(Collectors.toList());
System.out.println(employees);

// Output
// [Employee [name=Mohan, age=24], Employee [name=John, age=27], Employee [name=Vaibhav, age=32]]

Skip()

skip(int n) method is used to discard first n elements from the stream.
For example:
skip(3) discards first 3 elements from stream.

Let’s see with help of example:

List<Employee> employees = employeesList.stream()
                                     .skip(3)
                                  .collect(Collectors.toList());
System.out.println(employees);

// Output
// [Employee [name=Amit, age=22]]

flatmap()

map() operation generates one output for each input element.

What if you want more than one output for each input?
flatmap() operation is exactly used for this purpose. It is used to map multiple-output for each input.
For example:
We want to accumulate list of cities in which all employees have lived. One employee could have lived in multiple cities so that we may have more than one city for each employee.

Let’s see with help of example:

List<String> listOfCities = employeesList.stream()
                                           .flatMap(e -> e.getListOfCities().stream())
                                           .collect(Collectors.toList());

System.out.println("listOfCities: " +listOfCities);

// Output
// listOfCities: [Newyork, Banglore, Paris, London, Pune, Seattle, Chennai, Hyderabad]

Common terminal operations

foreach

foreach() is terminal operation which is used to iterate over collection/stream of objects. It takes consumer as a parameter.

Let’s say you want to print elements of the stream.

employeesList.stream()
             .forEach(System.out::println);

// Output
// Employee [name=Mohan, age=24]
// Employee [name=John, age=27]
// Employee [name=Vaibhav, age=32]
// Employee [name=Amit, age=22]

collect

collect() is terminal operation which performs mutable reduction on the elements of Stream using Collector. Collectors is utility class which provides inbuilt Collector.
For example:
Collectors.toList() provides a Collector which converts Stream to a list object.
Following code accumultates Employee names into a Arraylist

List<String> employeeNames = employeesList.stream()
                                          .map(Employee::getName)
                                          .collect(Collectors.toList());
System.out.println(employeeNames);

// Output
// [Mohan, John, Vaibhav, Amit]

Reduce

The reduce operation combines all elements of Stream and produces single result.
Java 8 has three overloaded version of reduce method.

  1. Optional<T> reduce(BinaryOperator<T> accumulator):
    This method takes BinaryOperator accumulator function. BinaryOperator is BiFunction where both the operands are of same type. First parameter is result till current execution, and second parameter is the current element of the Stream.

    Let’s find name of Person with minimum age.

    employeesList.stream()
    .reduce( (e1,e2)-> (e1.getAge() < e2.getAge()? e1:e2))
    .ifPresent(System.out::println);
    // Output
    // Employee [name=Amit, age=22]
  2. T reduce(T identity, BinaryOperator accumulator):
    This method takes identity value and accumulator function. identity value is initial value of the reduction. If Stream is empty,then identity value is the result.
    Let’s find sum of all ages of Employees

    int sumAge = employeesList.stream()
    .mapToInt(Employee::getAge)
    .reduce(0, (age1,age2)-> (age1 + age2));
    
    System.out.println("Sum of ages of all Employees: "+sumAge);
    // Output
    // Sum of ages of all Employees: 105
  3. <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner):
    This method takes identity value and accumulator function and combiner. Combiner is mainy used in case of Parallel Streams. Combiner comibnes the result of sub-stream that run in Parallel.

count

count() is used to count number of elements in the stream.

long empCountStartJ = employeesList.stream()
                                   .map(Employee::getName)
                                   .filter(s -> s.startsWith("J"))
                                   .count();
System.out.println(empCountStartJ);

// Output
// 1

allMatch()

allMatch() returns true when all the elements in the stream meet provided condition.

This is a short-circuiting terminal operation because operation stops as soon as it encounters any unmatched element.

boolean allMatch = employeesList.stream()
                                .allMatch(e ->e.getAge()>18);

System.out.println("Are all the employess adult: " +allMatch);

// Output
// Are all the employess adult: true

nonMatch()

nonMatch() returns true when all the elements in the stream do not meet provided condition.

This is a short-circuiting terminal operation because operation stops as soon as it encounters any matched element.

boolean noneMatch = employeesList.stream()
                                 .noneMatch(e ->e.getAge()>60);

System.out.println("Are all the employess below 60: " +noneMatch);

// Output
// Are all the employess below 60: true

anyMatch()

anyMatch() returns true when any element in the stream meets provided condition.

This is a short-circuiting terminal operation because operation stops as soon as it encounters any matched element.

boolean anyMatch = employeesList.stream()
                                 .anyMatch(e ->e.getAge()>30);

System.out.println("is any employee's age greater than 30: " +anyMatch);

// Output
// is any employee's age greater than 30: true

min()

min(Comparator) returns minimum element in the stream based on the provided comparator. It returns an object which contains actual value.

Optional<Employee> minEmpOpt = employeesList.stream()
                                            .min(Comparator.comparing(Employee::getAge));

Employee minAgeEmp = minEmpOpt.get();
System.out.println("Employee with minimum age is: " +minAgeEmp);

// Output
// Employee with minimum age is: Employee [name=Amit, age=22]

max()

max(Comparator) returns maximum element in the stream based on the provided comparator. It returns an object which contains actual value.

Optional<Employee> maxEmpOpt = employeesList.stream()
                                            .max(Comparator.comparing(Employee::getAge));

Employee maxAgeEmp = maxEmpOpt.get();
System.out.println("Employee with maxium age is: " +maxAgeEmp);

// Output
// Employee with maxium age is: Employee [name=Vaibhav, age=32]

Parallel Streams

You can create Parallel Stream using .parallel() method on Stream object in java.
Here is an example:

int[] array= {1,2,3,4,5};

System.out.println("=================================");
System.out.println("Using Parallel Stream");
System.out.println("=================================");
IntStream intParallelStream=Arrays.stream(array).parallel();
intParallelStream.forEach((s)->
{
    System.out.println(s+" "+Thread.currentThread().getName());
}
);

Here is a comprehensive article on Java 8 Parallel Stream.

Exercises

Let’s practice some exercises on Stream.

Exercise 1

Given a list of employees, you need to find all the employees whose age is greater than 30 and print the employee names.(Java 8 APIs only)
Answer:

Exercise 2

Given the list of employees, find the count of employees with age greater than 25?
Answer:

Exercise 3

Given the list of employees, find the employee whose name is John.

Exercise 4

Given a list of employees, You need to find highest age of employee?
Answer:

Excercise 5

Given a list of employees, you need sort employee list by age? Use java 8 APIs only
Answer:

Excercise 6

Given the list of Employees, you need to join the all employee names with ","?
Answer:

Excercise 7

Given the list of employees, you need to group them by name

]]>
https://java2blog.com/java-8-stream/feed/ 2
Java 8 Method reference https://java2blog.com/java-8-method-reference/?utm_source=rss&utm_medium=rss&utm_campaign=java-8-method-reference https://java2blog.com/java-8-method-reference/#comments Wed, 22 Apr 2020 17:25:38 +0000 https://java2blog.com/?p=9355 Java 8 has introduced a lot of new features such as lambda expressions, stream, Method references etc.

In this post, we will see what are Method references and how can we use it. I will try to provide more examples rather than theory.

1. Introduction to Method Reference

Method references are special types of lambda expressions that execute only one method.
General syntax of method reference:

object::methodName

You might have already guessed that you need to understand lambda expressions first. If you are comfortable with lambda expressions, then let’s move forward.

Let’s understand this with the help of example:

Let’s create class MethodReferecesLambdaExpressionMain in which we are going to print list using stream’s foreach method.

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

public class MethodReferecesLambdaExpressionMain {

    public static void main(String args[])
    {
        List<String> countryList=Arrays.asList(new String[] {"India", "China","Nepal","Russia"});

        System.out.println("=======================");
        System.out.println("Using anonymous class");
        System.out.println("=======================");

        // Using anonymous class
        countryList.stream().forEach(
                new Consumer<String>() {

                    @Override
                    public void accept(String country) {
                        System.out.println(country);    
                    }
                });

        System.out.println("=======================");
        System.out.println("Using lambda expression");
        System.out.println("=======================");

     // Using lambda expression
        countryList.stream().forEach(
                country -> System.out.println(country)
                );

        System.out.println("=======================");
        System.out.println("Using Method references");
        System.out.println("=======================");

      // Using method reference
        countryList.stream().forEach(
                System.out::println
            );
    }   
}

Output:

=======================
Using anonymous class
=======================
India
China
Nepal
Russia
=======================
Using lambda expression
=======================
India
China
Nepal
Russia
=======================
Using Method references
=======================
India
China
Nepal
Russia

stream.foreach() method takes consumer functional interface as agrument.

Consumer is functional interface that takes a single argument and returns nothing.
We have used consumer functional interface in 3 ways.

  1. Using anonymous class
    Consumer consumer1 = new Consumer() {
    
                        @Override
                        public void accept(String country) {
                            System.out.println(country);    
                        }
                    };
            
  2. Using lambda expression
    Consumer consumer2 = country -> System.out.println(country);
    
  3. Using method reference
    Consumer consumer3 = System.out::println;
    

You might already know that you can use lambda expression instead of an anonymous class, but You can use method reference only when the lambda expression just calls to a method.

So if you look at below syntax:

Consumer consumer3 = System.out::println;

In method reference, we have Class or object before :: and method name after :: without arguments.

Did you notice the method reference does not have arguments?
Yes, we don’t need to pass arguments to method reference, arguments are passed automatically internally based on type of method reference.

The below diagrams will make it clearer.
You can use method reference as below:

MethodReference

Let’s say you want to convert country to uppercase before printing it. You can achieve it using anonymous class and lambda expression but not with method reference.

You can not use method reference as below:

MethodReferenceNot

You can obviously use the stream’s map() method to convert the country to uppercase before printing it. I just want to demonstrate when method reference can’t be used.

2. Types of method references

There are four types of method references.

  1. Reference to static method
  2. Reference to instance method of object type
  3. Reference to instance method of existing object
  4. Reference constructor

2.1 Reference to static method

When you have lambda expression which calls to static method, then you can method reference to static method.

Lambda expression syntax
(args) -> ClassName.someStaticMethod(args)
can be converted to
ClassName::someStaticMethod

Let’s see this with the help of example.

Create a class name PowerFunctions

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

class PowerFunctions {

    // This is the method we will call in method reference
    public static Integer power(int a)
    {
        return a*a;
    }

    // Function is functional interface which will be target for method reference
    public static List<Integer> calculatePowOf2ForList(List<Integer> list,
                                           Function<Integer,Integer> function)
    {
        List<Integer> powerNumbers = new ArrayList<>();

        for(Integer num:list)
        {
            Integer powOf2 = function.apply(num);
            powerNumbers.add(powOf2);
        }
        return powerNumbers;
    }

}

Function is functional interface that takes a single input T and returns a single output R.

We can call calculatePowOf2ForList() as below:

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

public class StaticMethodReferenceMain {

    public static void main(String args[])
    {

        List<Integer> list=Arrays.asList(new Integer[] {1,2,3,4,5});

        // using anonymous class
        Function<Integer,Integer> function1=new Function<Integer, Integer>() {

            @Override
            public Integer apply(Integer num) {
                return PowerFunctions.power(num);
            }
        };

        List<Integer> calculatePowForList1 = PowerFunctions.calculatePowOf2ForList(list, function1); 
        System.out.println(calculatePowForList1);

        // Using lambda expression
        Function<Integer,Integer> function2 = (num) -> PowerFunctions.power(num);

        List<Integer> calculatePowForList2 = PowerFunctions.calculatePowOf2ForList(list, function2); 
        System.out.println(calculatePowForList2);

        // Using Method reference
        Function<Integer,Integer> function3 = PowerFunctions::power;

        List<Integer> calculatePowForList3 = PowerFunctions.calculatePowOf2ForList(list, function3); 
        System.out.println(calculatePowForList3);

    }
}

When you run above program, you will get below output:

[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

If you notice,Function<Integer,Integer> function2 = (num) -> PowerFunctions.power(num); is of type (args) -> className.someStaticMethod(args)
Here,

  • PowerFunctions is className
  • someStaticMethod is power method
  • num is power method argument.

We are calling a static method power of class PowerFunctions in lambda expression, that’s why we can use it as method reference.

So instead of
Function<Integer,Integer> function2 = (num) -> PowerFunctions.power(num);
we can use
Function<Integer,Integer> function3 = PowerFunctions::power;

Here,

  • First type parameter of Function(Integer) is first parameter of static method power().
  • Second type parameter of Function(Integer) is return type of static method power().

2.2 Reference to instance method of object type

When you have lambda expression where instance of object is passed and calls to an instance method with/without parameters, then you can use method reference to an instance method with object type.

Lambda expression syntax
(obj,args) -> obj.someInstanceMethod(args)
can be converted to
objectType::someInstanceMethod

Let’s see this with the help of example.

import java.util.function.BiFunction;

public class MethodReferenceObjectType {

    public static void main(String[] args) {

        // Using anonymous class

        BiFunction<String,Integer,String> bf1=new BiFunction<>() {

            @Override
            public String apply(String t, Integer u) {
                return t.substring(u);
            }
        };
        String subString1 = getSubstring("Java2blog",2,bf1);
        System.out.println(subString1);

        // Using lambda expression
        BiFunction<String,Integer,String> bf2 =  (t,u) -> t.substring(u);
        String subString2 = getSubstring("Java2blog",2,bf2);
        System.out.println(subString2);

        // Using Method reference
        BiFunction<String,Integer,String> bf3 = String::substring;
        String subString3 = getSubstring("Java2blog",2,bf3);
        System.out.println(subString3);
    }

    public static String getSubstring(String str1,int beginIndex,BiFunction<String,Integer,String> p)
    {
        return p.apply(str1, beginIndex);

    }
}

BiFunction is functional interface that takes two arguments and returns single output.

If you notice,BiFunction<String,Integer,String> bf2 = (t,u) -> t.substring(u); is of type (obj,args) -> obj.someInstanceMethod(args)

Here

  • obj is of type String.
  • someInstanceMethod is String’s substring() method.
  • args is beginIndex for substring() method argument.

So BiFunction<String,Integer,String> bf2 = (t,u) -> t.substring(u); can be converted to
BiFunction<String,Integer,String> bf3 = String::substring;

Here,

  • First BiFunction parameter type(String) is String object itself.
  • Second BiFunction parameter type(Integer) is argument to substring() method
  • Third BiFunction parameter type(String) is return type of substring() method

2.3 Reference to instance method of existing object

When you have lambda expression where instance of object is used to call an instance method with/without parameters, then you can use method reference to an instance method with an existing object.
Lambda expression syntax
(args) -> obj.someInstanceMethod(args)
can be converted to
objectType::someInstanceMethod

Here obj is defined somewhere else and is not part of argument to lambda expression.

Let’s understand with the help of example.

Create a class named Country.java.

public class Country {
    String name;
    long population;

    Country(String name)
    {
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

    @Override
    public String toString() {
        return "[ name = "+name+" population = "+population+" ]";
    }
}

Create another class MethodReferenceExistingObjectMain.java

import java.util.function.Consumer;

public class MethodReferenceExistingObjectMain {

    public static void main(String[] args) {

        Country c=new Country("India");

        // Using anonymous class
        Consumer<Long> popCons1=new Consumer<Long>() {

            @Override
            public void accept(Long t) {
                c.setPopulation(t);
            }
        };
        popCons1.accept(20000L);
        System.out.println(c);

        // Using Lambda expression
        Consumer<Long> popCons2= (population) -> c.setPopulation(population);
        popCons2.accept(30000L);
        System.out.println(c);

        // Using method reference
        Consumer<Long> popCons3 = c::setPopulation;
        popCons3.accept(40000L);
        System.out.println(c);
    }
}

Output:

[ name = India population = 20000 ]
[ name = India population = 30000 ]
[ name = India population = 40000 ]

Consumer is functional interface which takes single argument and returns nothing.
If you notice, Consumer popCons2 = (population) -> c.setPopulation(population); is of type (args) -> obj.someInstanceMethod(args)

Here

  • obj is of type Country and declared somewhere else.
  • someInstanceMethod is Country’s setPopulation method.
  • args is population for setPopulation method argument.

So Consumer<Long> popCons2= (population) -> c.setPopulation(population); can be converted to Consumer<Long> popCons3 = c::setPopulation;

Here,

  • First Consumer parameter type(Long) is argument to setPopulation method.

2.4 Reference constructor

When lambda expression is used to create new object with/without parameters, then you can use reference method constructor.
Lambda expression syntax
(args) -> new ClassName(args)
can be converted to
ClassName::new

Let’s see with the help of example.
Here we will convert the list to set using method reference.

Function<List,Set> is functional interface which will take a list an argument and will return set by calling HashSet constructor public HashSet(Collection<? extends E> c)

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

public class MethodReferenceConstructorMain {

    public static void main(String[] args) {

        ArrayList<String> list=new ArrayList<>();
        list.add("Rohan");
        list.add("Andy");
        list.add("Sneha");
        list.add("Rohan");

        // Anonymous class
        Function<List<String>,Set<String>> f1= new Function<List<String>, Set<String>>() {

            @Override
            public Set<String> apply(List<String> nameList) {

                return new HashSet<>(nameList);
            }
        };
        Set<String> set1 = f1.apply(list);
        System.out.println(set1);

        // Using lambda expression
        Function<List<String>,Set<String>> f2 = (nameList) -> new HashSet<>(nameList);
        Set<String> set2 = f2.apply(list);
        System.out.println(set2);

        // Using Method reference
        Function<List<String>,Set<String>> f3= HashSet::new;
        Set<String> set = f3.apply(list);
        System.out.println(set);
    }
}

Output:

[Sneha, Andy, Rohan]
[Sneha, Andy, Rohan]
[Sneha, Andy, Rohan]

If you notice, Function<List<String>,Set<String>> f2 = (nameList) -> new HashSet<>(nameList); is of type (args) -> new ClassName(args)

Here

  • args is of type list
  • ClassName is HashSet

So Function<List<String>,Set<String>> f2 = (nameList) -> new HashSet<>(nameList); can be converted to Function<List<String>,Set<String>> f3= HashSet::new;

Here,

  • First Function parameter type(List) is argument to HashSet constructor.

3. Excercise

Let’s practice few exercises based on Method reference.

3.1 Excercise:1

Given a list of Integer, you need to find square root of each number in the list and return it as List<Double>.
You need to call Math’s sqrt static method to find square root of number and use it as method reference.

3.2 Excercise:2

Given a [list of Strings](https://java2blog.com/list-string-java/ “list of Strings”), you need to convert all the String to uppercase and then return a new list.

3.3 Excercise:3

Given a list of Color objects, you need to sort them of color’s name and return a sorted list of color names(List)
Here is the definition of Color class.

public class Color {

    String name;
    String htmlCode;

    public Color(String name, String htmlCode) {
        super();
        this.name = name;
        this.htmlCode = htmlCode;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHtmlCode() {
        return htmlCode;
    }
    public void setHtmlCode(String htmlCode) {
        this.htmlCode = htmlCode;
    }

    @Override
    public String toString() {
        return "Color [name:"+name+" HtmlCode:"+htmlCode+"]";
    }

}

4. Conclusion

Method references are special type of lambda expression that simply calls a method. It makes code more readable and concise, but if method references lead to any confusion, then there is no point in using them.

That’s all about method references in java.

]]>
https://java2blog.com/java-8-method-reference/feed/ 1
Why wait(), notify() And notifyAll() methods are in Object Class https://java2blog.com/why-wait-notify-notifyall-methods-object-class/?utm_source=rss&utm_medium=rss&utm_campaign=why-wait-notify-notifyall-methods-object-class https://java2blog.com/why-wait-notify-notifyall-methods-object-class/#comments Mon, 22 Oct 2018 16:29:51 +0000 https://java2blog.com/?p=6735 In this post, we will see why wait(), notify() And notifyAll() methods are in Object Class And Not in Thread Class.

This is one of the most asked java multithreading interview questions.

You might know that wait(), notify() And notifyAll() Methods are in Object class and do you know the reason for the same?

Let’s discuss why wait(), notify() And notifyAll() Methods Are in Object Class.

In Java, thread waits on monitor assigned to the object and when you want to send a signal to another thread who is waiting for the same monitor, you call notify() method to wake one thread and notifyAll() to wake up all the threads.

If wait, notify and notifyAll method are in thread class, then each thread should be aware of the status of another thread.

For example: Let’s say you have two threads, T1 and T2. Now T1 must know that T2 was waiting for this particular resource which I have just freed because T1 will need to call T2.notify().

In Java, the object itself is shared among the threads and facilitates inter-thread communication. Threads have no specific knowledge of each other. They can run asynchronously and are independent. They just run, lock, wait and get notified. They do not need to know about the status of other threads. They just need to call notify method on an object, so whomever thread is waiting on that resource will be notified.

As stated before,

  • When you call wait() method on the object, then it gives up monitor and go to sleep
  • When you call notify() method, then the single thread which is waiting for the object’s monitor will be notified.

Hence wait, notify() And notifyAll() work at object’s monitor level. If thread which is currently holding the monitor, wants to give up the monitor then it will call wait method on the object and if it want to notify other thread, then it will call notify method on the object.

Shared objects allow threads to communicate by calling wait(), notify() And notifyAll() Methods, so these methods are in the object class.

That’s all about why wait(), notify() And notifyAll() methods Are in Object Class And Not in Thread Class.

]]>
https://java2blog.com/why-wait-notify-notifyall-methods-object-class/feed/ 1
100+ Core Java Interview Questions and Answers for 2022 https://java2blog.com/java-interview-questions/?utm_source=rss&utm_medium=rss&utm_campaign=java-interview-questions https://java2blog.com/java-interview-questions/#respond Mon, 21 May 2018 18:33:15 +0000 https://java2blog.com/?p=5606 Introduction

In this post we will look into the most commonly asked Interview questions related to Java. We will take a look at the most common topics in Java for interviews and provide the answer to the questions in detail with examples to help you ace your next interview.

We recommend following this post step by step to match the topics according to their difficulty level.

Java Interview Questions

Given below are about 100 Java Interview Questions, that questions you will see are among the common and top questions asked in interviews. These will also help you in your Computer Science degree subjects as well as other entrance exams.

So, without further ado let’s dive into it.

1. What is the key difference between C++ and Java programming languages?

Ans. C++ is both Procedural and Object Oriented Programming Language, primarily used for system programming, as opposed to other applications. Java is a pure Object Oriented Programming Language, primarily used for application development, as opposed to server programming. It is widely used in the development of a variety of applications, including desktop, web-based, enterprise, and mobile applications.

2. Is Java completely object-oriented or 100% Object Oriented?

Ans. Java uses the concepts of object-oriented language but we cannot say that it is completely or 100% object-oriented. It is because it still makes use of the primitive data types like int, float, double etc. An object-oriented programming language functions using objects only. Primitive data types are not objects. Hence, Java is not 100% object- oriented.

3. Is there a way to convert primitive data types to objects in Java?

Ans. Yes, there is a way to convert primitive data types to objects in Java. We can do so by using the Wrapper class. The Wrapper class in Java is used for interconversion between objects and primitive data types. For example, int is converted to Integer, char to Character, byte to Byte, and so on. These are 8 wrapper classes in total.

4. What are Autoboxing and Unboxing?

Ans. The automatic conversion of a primitive data type to an object is known as Autoboxing, it can be seen as a promotion of data type. Similarly, the automatic conversion of an object to its corresponding primitive data type is known as Unboxing.

In simple words, if we assign a literal value to a Wrapper Class Object it is called Autoboxing, whereas if we assign a Wrapper Class to its equivalent primitive type it is known as Unboxing.

Important Note: After Autoboxing, if we assign a Wrapper Class Object to a Primitive type it is known as Auto-Unboxing, a special case of Autoboxing. We will look at this in example:

Example Program:

public class Java2Blog
{
    public static void main (String[] args)
    {
        // creating an Integer Object
        // with value 20.
        Integer j = new Integer(20);

        // Unboxing the Object by assigning to primitve type int.
        int j1 = j;

        System.out.println("Value of j: " + j);
        System.out.println("Value of Unboxed j1: " + j1);

        //Autoboxing of char by assign a literal value to Wrapper Type Object.
        Character j2b = 'a';

        // Auto-Unboxing of Character by assigning to a primitve type again.
        char ch = j2b;
        System.out.println("Value of Autoboxed j2b: " + j2b);
        System.out.println("Value of Auto-Unboxed ch: " + j2b);

    }
}

Output:

Value of j: 20
Value of Unboxed j1: 20
Value of Autoboxed j2b: a
Value of Auto-Unboxed ch: a

5. Does Java support pointers?

Ans. Java does not support pointers. Pointers are used to directly point a location in memory. This will pose a threat to security of Java and compromise its purpose. As we know that Java uses the concepts of OOP, it is already complex. Hence to make it less complex and remove ambiguity, pointers are not allowed in Java.

6. What is a string literal?

Ans. In Java, a string literal is basically a string enclosed in double quotes “”. A string literal can contain alphabets, numbers, and special characters. Java uses string literal because in this way if a string literal already exists in the string pool, then Java does not create a new object for it. This property makes it memory efficient. Although we concatenate two String literals using + operator.

Example:

String s = "Welcome to ";
String str = "Java2Blog";
String total = s + str;
System.out.println(total);

Output:

Welcome to Java2Blog

The sample code does not include the main method and class declaration. Please write the sample code inside the main method and a class to get the above desired output.

7. What do you know about StringBuffer?

Ans. The string is immutable in Java. We can use its mutable version with the StringBuffer class. Any changes done to a StringBuffer type String using methods will reflect in the original string. We can also set the size of the buffer for the string. By default, its size is 16 characters. We can also perform other string functions on StringBuffer like append, insert, etc.

Example of StringBuffer in Java:

public class Java2Blog 
{
public static void main(String args[]) 
{
StringBuffer sb = new StringBuffer("Hello ");
System.out.println(sb);

sb.append(" World!");
System.out.println(sb);
}
}

Output:

Hello 
Hello World!

8. What do you know about Java String Pool?

Ans. The Java String Pool is a pool that contains all the strings created. It is possible to have many strings in the string pool in Java, each of which has its own heap memory allocation.

Whenever a new string object is generated, the String pool checks to see if the object has already been created and stored somewhere else. The relevant reference will be returned if it is there. Otherwise, a new object will be generated in the String pool and the new reference will be returned to the variable.

9. Are Java strings mutable?

Ans. No, java strings are not mutable. String objects in Java are immutable by nature, which basically implies that once a string object has been created, its state cannot be changed in any way. Java creates a new string object whenever you attempt to edit the value of that object rather than modifying the values of that particular object.

Java String objects are immutable because string objects are typically cached in the String pool, which makes them immutable. Due to the fact that strings are typically shared between numerous clients, an action taken by one client may have an impact on the rest.

10. What do you know about garbage collection?

Ans. Garbage collection is an interesting feature of Java. In simple words, unreferenced objects are garbage in Java. Unused runtime memory is automatically recollected by Garbage Collection. Also, it is a method of destroying useless objects. Java garbage collection automates memory management in Java applications.

A program’s heap is formed when it runs on the JVM. After the execution, some objects eventually become obsolete. These obsolete objects are found and deleted by the garbage collector. This feature makes it convenient for programmers to build large scale applications as they need not worry about every object. If it is unused it will be garbage collected.

11. Explain the gc() method?

Ans. In Java, the gc() method is used to start the process of garbage collection. Calling it implies that
the Java Virtual Machine recycles or deallocates memory of unwanted objects to free up memory for reuse. It is
a method of System class. The gc() method is also present in the Runtime Class but is not used commonly.

In order to view the object before it goes for garbage collection we can use the finalize() method.

Note: An object is eligible for garbage collection if it is unreachable or contains null value.

Example:

public class Test
{
    public static void main(String[] args)
    {
        Test t1 = new Test();

        // Nullifying the reference variable
        t1 = null;
        // requesting JVM for running Garbage Collector
        System.gc();

        System.out.println("Garbage Collected! ");
    }
}

Output:

Garbage Collected!

12. What is inner class?

Ans. Classes in Java can have members of other classes, exactly like methods. Java permits the creation of classes that extend other classes. Inner classes are classes that include other classes, and classes that hold other classes are referred to as outer classes. In other words, the non-static nested classes are also known as inner classes.

13. What do you know about the types of inner class?

Ans. There are four types of inner classes. These are:

  • Anonymous inner class
  • Local inner class
  • Member inner class
  • Static member inner class

14. What do you mean when you say Java virtual machine?

Ans. The Java Virtual Machine allows a computer to run a Java program without the need for any additional software. The Java Virtual Machine (JVM) functions as a run-time engine, invoking the main method defined in the Java code.

The Java Virtual Machine (JVM) specification must be implemented in the computer system. The Java code is compiled into bytecode by the JVM, which is machine-independent and very near to the native code in terms of performance.

The Java Virtual Machine (JVM) executes the following tasks:

  •  It loads the code into memory.
  •  It checks for errors in the code.
  •  It generates an output by executing the program.
  •  It sets up a runtime environment.

15. What makes the Classloader important?

Ans. A class file is a file that contains the bytecode generated by Java Virtual Machine (JVM). It is an important file as it makes the code transferable and executable on any platform containing JVM. Class loader loads class files. Its ability to load class files first when a java program is run makes it important for Java virtual machines.

16. What do you know about the Just-In-Time compiler?

Ans. It is commonly known as the JIT compiler. Its purpose is to increase the overall performance. JIT compiler translates portions of bytecode that have similar functionality as the original, reducing the amount of time required for compilation. It enhances the performance by converting the instruction set of a Java virtual machine (JVM) into the instruction set of a particular CPU where the program is run.

17. Is an empty java file name considered to be an acceptable source file name?

Ans. Yes, only Java permits us to save our java files as .java extensions; nevertheless, we must compile them as javac .java. What Java does by default is that it uses the name of the class as the file name.

18. What is an interface?

Ans. To put it another way, an interface is in Java what you might refer to as the blueprint of a class, or as a collection of abstract methods and constants. Each method in an interface is public and abstract, but it lacks a constructor.

This means that in its most basic form, an interface is nothing more than a collection of undefined methods. Only method signatures and constant declarations are allowed in interfaces. Interfaces are specified with the interface keyword.

19. Is there any marker interface in Java?
Ans. A Marker interface is one that lacks data members and member functions. To put it another way, an empty interface is referred to as the Marker interface. Serializable, Cloneable, and others are the most frequently used Marker interfaces in Java.

20. What do you know about packages in Java?
Ans. A package is a collection of classes, interfaces, and other packages. Java classes and interfaces are packaged. Java has two types of packages: built-in and user-created. In order to use a package, we need to import it. For example, if we want to use Arrays Class in Java, we import a package like this:

import java.util.Arrays
Here, java is the top-level package, util is a sub-package, and Arrays is a class in util.

21. How to create a package in Java?

Ans. It is quite easy to create a package in Java. One should follow the given steps to create a package in Java. These are:

  • Select the name of the package.
  • Write package command in Java source file on the first line.
  • Compile

22. Are empty and null two different things in Java?

Ans. In Java, empty and null are totally two different concepts. Even if it is an empty string or null string; or empty collection or null collection there exists a difference between the two terms.

If we talk about empty string and null string, then an empty string is a string that contains no value but is allocated memory i.e. it exists. On the other hand, a null string does not exist at all. It has no value nor any memory identity.

If we print the length of an empty string literal we get 0. Whereas, if we print the length of a null string we will get a NullPointerException. This explains the difference regarding memory allocation. We will look at this in example program.

public class Java2Blog {
    public static void main(String args[]) {

      String emptyString = "";
      String nullString = null;

      System.out.println(emptyString.length());
      System.out.println(nullString.length());
    }
}

Output:

0

Exception in thread "main" java.lang.NullPointerException
    at Java2Blog.main(Java2Blog.java:8)

23. What are the main types of access specifiers available in Java?

Ans. Access specifiers are keywords in Java that we use to describe the access scope of a method, a class, or a variable. They are also known as access modifiers. There are four main access specifiers in Java, which are listed below.

  • Public: The public classes, methods, and variables are those that can be accessed by any class or method that has been designated as public. These members are accessible from everywhere in the program as well as outside the package.
  • Protected: The protected class, method, or variable can only be accessible by classes belonging to the same package, or by subclasses of this class, or by classes belonging to the same package.
  • Default: All of the default terms are only accessible within the package. By default, all classes, methods, and variables are included in the default scope of the application.
  • Private: It is only possible to access the class, methods, and variables designated as private from within the same class.

24. What are the key points that one should keep in mind while changing access specifiers of a method?

Ans. Following are the key points that one should keep in mind while changing access specifiers of a method:

  • We can change the private method to public, default, and protected.
  • We can change the protected method to public and default only.
  • We can change the default method to the public only.
  • The public method cannot be changed.

25. Can we access one class in another class?

Ans. Yes, we can access another class from another class. There are two methods for it.

  • By using the package name along with the class name. By doing so, one doesn’t need to import the package.
  • By using its path with the entire package structure.

26. Can a private method be accessed outside the class?

Ans. The fields that are private cannot be accessed outside the class. But a private method can be accessed outside the class using Java Class and Method classes.

27. Give an example explaining the function of static keyword.

Ans. The static variable is a property of the class rather than of the object. We use the static keyword when we need to declare variables or methods that are shared by all instances of a class and are not specific to any one object.

It is not necessary to create an object in order to access static variables or methods because they are stored in the class area. Static members are allocated memory only once. Whereas other instance variables are allocated memory every time we create an object.

Example: Suppose, we are storing the details of a class then we can declare the name of the class teacher as static as all students of a class have the same class teacher. Let us understand this with help of a program.

public class Java2Blog {
    public static void main(String args[]) {

      Student student1 = new Student(1,"James");
      Student student2 = new Student(2,"Steve");

      System.out.println(student1.roll +" "+student1.name+" "+student1.teacherinCharge);
      System.out.println(student2.roll +" "+student2.name+" "+student2.teacherinCharge);
    }
}

class Student
{
    int roll;
    String name;
    // Static variable to be shared with all instances.
    static String teacherinCharge = "Amanda Jones";

    Student(int roll,String name)
    {
        this.roll = roll;
        this.name = name;
    }

}

Output:

1 James Amanda Jones
2 Steve Amanda Jones

28. Do the order of specifiers, modifiers, and keywords matter in Java?

Ans. No, the order doesn’t matter as the program gets compiled perfectly. As we have generated the class file, we can run it without any problem. There will be no errors.

public static final name = "Java2Blog"

static final public name = "Java2Blog"

final static public name = "Java2Blog"

All the three variable naming conventions are same to Java.

29. What do you know about the term method?

Ans. A method is basically a procedure for carrying out a specific task. Similar in nature, a Java method is a collection of instructions that are used to do a certain task. It allows code to be reused in multiple places. A method can be built-in as well as user-defined. A method can be parameterized or non-parameterized.

30. What are the types of a method?

Ans. A method in Java has two main types; predefined method and user-defined method. The predefined methods are built-in methods. In Java these methods usually belong to a class. Whereas user-defined methods are the methods that a user writes according to his/her need. User-defined methods increase the scope of a programming language as one is able to perform his/her specific task.

Example:

An example of pre-defined method in Java is the length() method of String Class.

31. Can we make a method static?

Ans. Yes, we can use the static keyword to make a method static. Variables, methods, blocks, and nested classes can be static. A static method is a method that uses the static keyword. A static method belongs to the class, not the object. A static method can be called without creating a class instance or object. We can use a static method to access and modify the value of a static data member.

32. Can we run a Java program without a main method?

Ans. It was possible in the older versions of JDK. But after the release of JDK 1.7, it is impossible to run and execute a Java program without a main method. In older versions prior to Java 7, we could use a Java static block to run the program without the main method.

33. When we create the main method, we define it as static. Why is that so?

Ans. In Java, we use objects to call methods. But we can invoke static methods without creating a class object. This property of static methods is useful while invoking the main method.

This helps the JVM to automatically invoke the main method without any instance of the class having the main method. We define the main method as static so that we do not have to create a class object to invoke the main method.

34. Will our program compile, if we remove static keyword from the main method?

Ans. Yes, our program will get compiled. The program will not show any error on compiling but during execution it will show a run time error. The run time error will be Main Method is not Static.

35. Can a Java program have more than one main method?

Ans. Yes, a Java program can have more than one main method. Having more than one method with the same name is known as method overloading. We can use method overloading to create more than one main method in a Java program.

We know that the name is the same and parameters are different in overloaded methods. But it is necessary for us to write the original main method one with String array parameter. During compilation, the JVM will search for that method.

We will have a look at this in example program.

public class Java2Blog 
{
    // Here we have a main method without any parameter.
    public static void main()
    {
        System.out.print("Hello ");
    }

    public static void main (String[] args) {

        main();
        System.out.println("World");
    }
}

Output:

Hello World

36. What do you know about the instance method?

Ans. A method that is not static is known as an instance method. As obvious from its name, an object is needed to invoke an instance method.

37. What do you know about method overloading?

Ans. If there are two methods with the same name and different parameters in the same class, then these methods are called overloaded methods, and the process is known as overloading. If two methods have the same name and number of parameters but their parameter types are different, then such methods are also overloaded. This helps us achieve Compile Time Polymorphism in java.

Overloading is useful when we need scalability in our program. Scalability in sense of parameters, sometimes we need two parameters and sometimes we need three or more. In such cases, overloaded methods become handy and increase the readability of the code.

Example Program for Method Overloading:

public class Java2Blog {

    static void printNumbers(int a,int b)
    {
        System.out.println("Integer Numbers: "+a+" "+b);
    }

    static void printNumbers(float a,float b)
    {
        System.out.println("Float Numbers: "+a+" "+b);
    }
    public static void main(String args[]) {

      printNumbers(1,2);
      printNumbers(3.5f,4.5f);
    }

}

Output:

Integer Numbers: 1 2
Float Numbers: 3.5 4.5

38. Can we overload methods by changing their return types only?

Ans. No, we cannot overload methods by changing their return type. The only golden rule of method overloading is that the number of parameters must be different.

39. What is method overriding?

Ans. The concept of overriding rises when we talk about inheritance. When there is a parent and child class or super or subclass. Method overriding is the act of adding a method to a subclass that already exists in the superclass. Overriding allows a child class to provide its own implementation of a method given by the parent class.

Method Overriding helps us achieve Run Time Polymorphism in Java. In this situation, the parent class method is overridden method and the child class method is an overriding method.

class Parent
{
     // Parent Class Implementation of Method.
     static void printNumbers(int a,int b)
    {
        System.out.println("Integer Numbers: "+a+" "+b);
    } 
}

class Child extends Parent
{
    // Child Class Overriden 

    static void printNumbers(float a,float b)
    {
        System.out.println("Float Numbers: "+a+" "+b);
    }
}

public class Java2Blog {

    public static void main(String args[]) {

      Child obj = new Child();

      obj.printNumbers(5.5f,6.5f);
    }

}

Output:

Float Numbers: 5.5 6.5

40. Is Java an object-oriented programming language?

Ans. Yes, Java is an object-oriented programming language. When we say object-oriented, the first thing that pops up in our minds is objects. An object-oriented programming language deals with the objects having methods. These objects belong to a specific class. We can safely say that we can create as many objects of a class as we want.

41. What is the purpose of a constructor?

Ans. We need a constructor while creating an object of a class. It is called when an object of a class is created and memory is allocated for the object to be created. If you create a new object with the new keyword, the default constructor of the class will be invoked every time you do so.

The constructor must have a name that is similar to the name of the class. The constructor must not return a type that is specified explicitly.

42. What are the two types of constructors?

Ans. The two types of a constructor are:

  • Default Constructor
  • Parameterized constructor

Default Constructor: The default constructor accepts no values. If no constructor is defined in the class, the compiler uses a default constructor. We use the default constructor to set default values for instance variables. We can also use it to create
objects.
Parameterized Constructor: The parameterized constructor, as obvious from its name, accepts parameters. This is the main difference between the two constructors.

43. Why is there a need for a parameterized constructor?

Ans. We need a parameterized constructor to create different objects. A default constructor initializes objects created with the same values defined in the constructor. However, if we want to allot different values to different objects then we can use a parameterized constructor. A parameterized constructor can have as many parameters as one wants.

44. What are the three important points that one should keep in mind while defining constructors?

Ans. Constructors are essential to objects. A constructor tells about the object. A constructor can be default or user-defined. A user can define a constructor while keeping the following three restrictions in mind:

  • The name of the constructor must be the same as the name of the class.
  •  The return type of the constructor must not be specified explicitly.
  • A constructor cannot be defined using keywords abstract, static, and final.

45. What makes a C++ constructor and a Java constructor different?

Ans. In C++, we have a copy constructor. However, in Java, there is no copy constructor. We use a copy constructor to create the copy of an object. It’s easy in C++ as we can use the copy constructor. In Java, there are other methods to create a copy of an object.

46. What happens when we call the default constructor and define parameterized constructor?

Ans. If we have defined a parameterized constructor and we have called a default constructor, then according to our thinking the compiler should implicitly call the default constructor. But this is not the case.

The compiler only calls the default constructor if no constructor is defined or given. Now that we have defined a parameterized constructor, the compiler will give an error. It will treat it similar to a method. Let’s see the example program as well.

class Sample
{
    Sample(String name)
    {
        System.out.println(name);
    }
}

public class Java2Blog {

    public static void main(String args[]) {
      // On Creating an object with no parameter passed into it, the default constructor will be called.
      Sample obj = new Sample();    
    }  
}

On executing this we get the below error.

47. Can a constructor be static?

Ans. The Java constructors cannot be static. The fact that a Java constructor cannot be static is an important Java design feature. Static is a keyword that refers to a class, not a specific object of a class. Constructors are used for objects so they cannot be static.

48. What are the different methods to create a copy of an object in Java?

Ans. As there is no copy constructor in Java, we will use other methods to create a copy of an object. We can create a copy of an object by defining a constructor that accepts an object as a parameter. In this way, we can copy the data of an already created object and assign it to the newly created object.
Another way is to directly assign the value of an object to the other. We can also use the clone method to create a copy of an object.

49. Can we create a copy of an object without a Cloneable interface?

Ans. The class whose object copy we wish to create must implement the Cloneable interface. If the Cloneable interface is not implemented, the clone() function throws a CloneNotSupportedException.

50. What is the difference between an object and a class?

Ans. A class can be thought of as a template from which new objects can be built. An object is something that exists in the real world, like a pen, laptop, mobile phone, bed, keyboard, mouse, or chair. A class can be thought of as a collection of comparable objects. An object is a real-world thing.

Programmers can access variables and methods inside a class by creating objects, which are instances of the class. When data and methods are combined into a single unit, they are called a class.

51. What do you know about Java blocks?

Ans. In Java, a block is a collection of one or more statements that are enclosed in braces. Beginning with an opening brace { and ending with a closing brace }, a block is formed. We can add one or more code lines in the space between the opening and closing braces. We can make a block static by using the static keyword.

52. What was the benefit of a Java block in the older versions of JDK?

Ans. There are multiple benefits of using blocks in Java. But the main benefit was that we could use a static block to execute the program without the main method. Static block is executed before the main method. It could be executed without the main method in older versions of JDK. But after the release of JDK 1.7 main method is a must to run a java program.

53. What do you know about the reference variable of Java?

Ans. The this and super keywords are means by which we can implement the concept of Reference variables in Java. The keyword this relates to the current object. This keyword has a variety of applications in Java.

It can refer to current class properties such instance methods, variables, constructors, and so forth. It can also be used as an argument in methods and constructors. It can alternatively be returned as the current class instance from the method. The super keyword is used when there is inheritance involved.

54. Can we assign value to this variable?

Ans. We cannot assign value to this variable as we use it for reference purposes. It points to the current class object. If we try to give it a value, then we will get a compile-time error.

55. Can we pass this as a parameter to a method?

Ans. Yes, we can pass this as a parameter to a method. We can also pass it as a parameter to the constructor.

56. Tell about the super keyword.

Ans. We use the super keyword whenever we talk about inheritance in Java. It is a reference variable. We use it to refer to immediate parent class methods, variables, and constructors. The super reference variable refers to an implicit parent class instance created when a subclass instance is formed.

57. What is the main difference between this and super?

Ans. The main and only difference between this and the super keyword is inheritance. Both work in the same way but the difference lies in the class to which these variables are referencing.

This keyword references the variable, method, or constructor of the current class. There is no inheritance involved in using this keyword. But the super variable is only used when there is an inheritance relationship between classes. Super keyword refers to the parent class’s variables, methods, and constructors.

58. Can a referenced object be unreferenced?

Ans. Yes, we can dereference a referenced object. There are different ways of doing that. The most common way to do that is to assign a null value to the object. Another way is to assign the reference of one object to another making the former unreferenced.

59. Is there any keyword as final in Java?

Ans. Yes, there is a keyword with name final in Java. It restricts modification to variables, methods and classes in a certain way. If we talk about final variables i.e., the variables that are using the final keyword, then we must know that we cannot modify final variables.

In the same manner, we cannot override final methods. However, we can overload final methods. Hence, we have to be very careful while using the final keyword as it restricts the normal function of a variable and a method.

60. Can we make a method, class, and variable final?

Ans. Yes, we can make a method, class, and variable final. But each has its restrictions. A final class cannot be inherited or extended. A final method can not be overridden. If we initialize a final variable with a value we cannot change its value again.

61. Can we make an interface final?

Ans. No, we cannot make an interface final. Multiple classes use or implements one interface. If we make
the interface final, then different classes will not be able to use it.

62. What is constructor chaining?

Ans. Constructor chaining is the practice of calling a constructor from another constructor in the same class. Constructor Chaining serves the function of allowing you to provide parameters across several constructors while only performing initialization once.

While offering various constructors to the user, you can preserve your initializations in a single area. You’ll have to initialize a parameter twice if we don’t chain, and if the value is modified in one constructor, you’ll have to modify it in each one instead of just the first.

63. Can constructor chaining be done using this and super?

Ans. Yes, constructor chaining can be done using this and super keywords. If we are calling the constructors of the same class, we will use this keyword. If we are using the constructor of the parent class within the child class, then we will use the super keyword.

Let us look at sample program to explain their use.

class Parent
{
    
    Parent()
    {
        System.out.println("Parent Class Constructor Chaining!");
    }
    Parent(String value)
    {
        // Constructor Chaining to same class using this keyword
        this();
        System.out.println(value);
    }
}

class Child extends Parent
{
    Child(String value)
    {
        // Constructor Chaining to other class using super keyword
        super("Parent Class Constructor Called!");
        System.out.println(value);
    }
}

public class Java2Blog 
{
    public static void main(String args[]) {
      
    Child obj = new Child("Child Class Constructor Called!");      
    }
}

Output:

64. Which main concepts of OOP are implemented in Java?

Ans. There are 4 main concepts of OOP that Java uses. These are inheritance, abstraction, polymorphism, and encapsulation.

65. Why do we use inheritance?

Ans. Inheritance in Java refers to the concept of creating new classes from existing ones. Just like a child inherits some of its characteristics from its parent, we can reuse methods and properties of the parent class when we inherit from it. In addition, we can extend our current class by adding additional methods and properties.

66. What are the types of inheritance?

Ans. Inheritance allows one object to inherit the characteristics and behavior of another object of a different class.
There are typically five types of inheritance:

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Out of the the above mentioned types, Java does not support multiple inheritance.

67. What do you know about multiple inheritance?

Ans. Multiple inheritance is a type of inheritance in which there is more than one parent class. Java does not support multiple inheritance. Because in multiple inheritance, a subclass is unable to choose between two classes that define various ways of doing the same thing. So, to decrease ambiguity, Java does not support multiple inheritance.

However we can achieve Multiple Inheritance in Java using Interfaces. Using Interface, a class can implement multiple interfaces hence can implement its own functionalities for each interface.

68. Is there any one parent class in Java?

Ans. Yes, there is a parent class to whom all other classes are subclasses. That class is Object class present in java.lang package. All other classes in java are the subclasses of the Object class.

69. What do you know about type promotion?

Ans. In Java, type promotion occurs when we use method overloading. When the data types are different than defined in the method, we promote one data type to the next higher data type in the hierarchy. We are unable to downgrade from one data type to
another.

  • It is possible to convert byte to byte, short, int, long, float, and double.
  •  Short can be made to work like short, int, long, float, and double.
  •  Int can be made to work like int, long, float, and double.
  •  Long can be made to work like long, float, and double.
  •  Float can be elevated to the status of a float and double by using type
    promotion.

70. What is Abstraction in Java?

Ans. We use data abstraction when we want to hide details from the user. Data Abstraction is the property that allows the user to see only the essential details. We use interfaces and abstract classes to implement abstraction in Java.

For example, when we eat food, we know that our food will digest but we don’t know that how our food will digest. This depicts the real-life example of abstraction. The unnecessary detail is hidden.

71. What is polymorphism?

Ans. Polymorphism refers to the fact that something exists in numerous forms. Polymorphism, put simply, is the ability of an object to appear in multiple forms.

For example, a person can have multiple traits at the same time. As a female, you are a mother, a daughter, sister, and an employee all at the same time. As a result, the same person exhibits several behaviors depending on the situation.

Polymorphism is the scientific term for this. As a result of polymorphism, we can accomplish the same action in multiple ways.

72. What are the types of polymorphism?
Ans. In Java, there are two types of polymorphism:

  • Compile-time polymorphism
  • Run-time polymorphism

Method Overloading is the best example of Compile-time polymorphism. We know that overloaded methods have the same name but different parameters. So, during compilation, the compiler decides which method will be implemented. It is also known as static polymorphism.

Method Overriding is an example of Run-time polymorphism. It is also known as Dynamic Method Dispatch where a call to a overridden method is resolved at runtime rather than compile time.

73. What are the benefits of using multithreading in Java?

Ans. The benefits of Multithreading are as follows:

  • Threads are used to speed up Java applications by allowing them to perform numerous tasks at the same time.
  • Thread is a Java feature that allows you to implement parallelism in your programs.
  • Because the CPU is extremely fast, and nowadays it even has multiple cores, a single thread cannot use all of the cores, resulting in your expensive hardware being idle most of the time. By implementing multiple threads, you may make full use of multiple cores by handling more customers and providing them more quickly than you could otherwise.

Given the importance of response time in today’s fast-paced world, multi-core CPUs are becoming increasingly popular; however, if your application does not make full use of all available resources, there is no point in adding them. Multi-threading is one method of utilizing the enormous computing power of the CPU in a Java application.

74. What is the purpose of the sleep() method in Java?

Ans. We use the sleep() method to temporarily halt the execution of a thread for a specified time, after which the thread that was executing before begins to execute again and so on. It has no return type.

75. What is the purpose of the wait() method in Java?

Ans. We use the wait() method to pause a thread and to release lock during synchronization. We cannot override it as it is a final method.

76. What is the difference between the start() and run() methods?

Ans. We use both start() and run() methods to start the execution of a thread. The difference lies in the thread itself. The run() method executes the code using the current thread. But the start() method executes the code by creating a new thread.

77. What is a daemon thread in Java?

Ans. It is a thread with the lowest possible priority that runs in the background and performs duties such as garbage collection and reloading the page. They will not be able to prevent the JVM from terminating when all of the user threads have completed their execution.

When all user threads have completed their execution, the JVM stops itself. If the JVM detects a functioning daemon thread, it stops the thread and then shuts down the entire system. The JVM is unconcerned about whether or not the Daemon thread is executing.

78. How can we check if a thread is a daemon thread or not?

Ans. We use the isDaemon() method to check if a thread is a daemon or not. It is a Boolean method. If it returns true, then the current thread is daemon. Otherwise, the current thread is not a daemon thread.

79. What do you know about shutdown hook?

Ans. In JVM, the shutdown hook is a thread that is automatically invoked just before the JVM shuts down completely. In this case, we can utilize it to do resource cleanup or state saving when the JVM goes down, whether it is properly or unexpectedly.

Shutdown hooks have been initialized, however, they can only be used if the JVM has been shut down. As a result, shutdown hooks are more dependable than the finalizer() function since there are significantly fewer chances that shutdown hooks will not be executed. By invoking the halt(int) method of the Runtime class, it is possible to terminate the shutdown hook.

80. Can we interrupt a thread?

Ans. Yes, we can interrupt a thread using the interrupt() method. We can stop its execution by throwing an InterruptedException. The interrupt() function of the Thread class can be used to wake up a thread that is asleep or waiting.

81. Why do we use the volatile keyword for threads?

Ans. We use the volatile keyword to allow several threads to alter the value of a variable at the same time. It is also employed to ensure thread safety. It means that several threads can utilize a method and an instance of a class at the same time without encountering any complications.

82. What is the purpose of execute() method?

Ans. The execute() method act as a scheduler for executing a specific task. A new thread may be created to execute the scheduled task if no thread is available.

83. What do you mean by synchronous and asynchronous programming?

Ans. There are two ways to program. In the Synchronous programming model, assigning tasks to individual threads and making them available for other activities as soon as the allocated task is completed occurs. Asynchronous programming allows numerous threads to work on the same task at the same time, making the individual threads as useful as possible.

84. What do you know about Java exceptions?

Ans. A problem that occurs during the execution of a program is known as an exception (or unusual situation). It is not advised for processes to terminate unexpectedly when an Exception occurs. As a result, these exceptions must be handled carefully. Exceptions can occur for a variety of reasons, including user mistakes, programmer errors, and failure of physical resources.

85. What are the types of exceptions?

Ans. There are mainly two types of exceptions in Java. These are:

  • Built In Exceptions
    • Checked Exceptions
    • Un-Checked Exceptions.
  • User Defined Exceptions

Built In Exceptions: These exceptions are already present in Java libraries and comes in handy when we have to throw any known exception which eases such cases. These are again subdivided into two types:

  1. Checked Exceptions: These exceptions are Compile-Time Exceptions as they are checked or evaluated by the compile during compile time. Hence, it is necessary for the programmer to handle these exceptions.
  2. Un-Checked Exceptions: These exceptions are not checked during compile time. These exceptions occur during execution of the program by the user. Hence, even if we didn’t handle such exceptions, during compilation we will not get any error.

User Defined Exception: In java, we can create our own exception as well. With the help of a try-catch block and creating a custom exception class, we can create our own custom exception as well.

Below image illustrates different types of exception.

86. What is the main difference between an exception and an error?

Ans. Both create a problem but the difference is that we can handle an exception but we cannot handle a code. Try and catch blocks are used to handle an exception.

87. What action does throw and throws perform? How do they differ?

Ans. To explicitly throw an exception, use the throw keyword. To declare multiple exceptions or if we want to show that a method will predominantly throw an exception then, use the throws keyword followed by commas to mention different exceptions. When using throw, only one exception will be thrown.

88. Can we throw an integer?

Ans. No, we cannot throw an integer. We cannot throw any primitive data type using the throw keyword as they are not objects.

89. What do you know about try and catch block?

Ans. We use the try statement with a block to test for errors while a block of code is being executed. If an error happens in the try block, you may use the catch statement to specify a code block that should be performed instead.

90. Is it necessary that every try should have a catch?

Ans. No, it is not always necessary to use a catch block after try block. But we cannot leave try on its own. If we are not using catch block, then we must use the finally block.

91. What is finally block?

Ans. Using the finally block in Java, you may execute critical pieces of code. Whether or not an exception is handled, the finally block in Java is always run. Consequently, regardless of whether an exception occurs, it provides all of the relevant statements. Contrary to catch block that depends on try block, a finally block always executes.

92. What do you know about serialization and deserialization?

Ans. When we convert an object into a byte stream, the process is referred to as serialization. When deserialization occurs, the byte stream is used to reconstruct the actual Java object in memory, which is the inverse of serialization.

The fact that the entire process is JVM independent is the most striking feature. This means that an object can be serialized on one platform and deserialized on another completely different platform.

93. Can we establish a connection between the server and a client in Java?

Ans. We can easily establish a connection between the server and a client in Java. We need to establish a connection session. Java socket programming is used to cover Java networking problems.

94. What do you know about an applet?

Ans. In computing, an applet is a Java program that runs in a web browser. Because it has access to the complete Java API, an applet can perform the functions of a fully functional Java application. An applet extends java.applet.Applet class. It is used to display information. Applets are a type of program. An applet does not have a main() method, and it does not have a main() method defined in its class. Applets are little programs that are intended to be embedded within an HTML page.

95. How can we create an applet in Java?

Ans. To create an applet in Java, first, write a program extending the Java Applet class. Then embed this program into your HTML code. Run your HTML code. The output available on the Web page will be the output of the applet.

96. What do you know about JDBC?
Ans. Connection and execution of the query to the database are accomplished through the use of the JDBC Java API. When connecting to a database, the JDBC API makes use of JDBC drivers. The JDBC API can be used to retrieve tabular data from any relational database that supports the JDBC standard. It is a piece of software that lets Java applications communicate with databases through the use of JDBC.

97. Tell about the BLOB and CLOB data types?

Ans. BLOB is an abbreviation for the Binary Large Object. This type of data is a collection of binary data that is saved as a single entity in a database management system (DBMS). CLOB is an acronym that stands for Character Large Object. In several database management systems, character files are stored in this data type. CLOB is identical to Blob with the exception that BLOB represents binary data such as photos, audio and video files, and so on, whereas CLOB represents character stream data such as character files and so on.

98. Are Collection and Collections the same in Java?

Ans. No, these are two different terms. The Collection is an interface while Collections is a class.

99. What is the difference between array and Arraylist?

Ans. An array is a data structure with a fixed length, whereas Array List is a Collection class with a variable length. Once an array has been constructed in Java, its length cannot be modified; however, we can alter the length of an Arraylist. Arraylist does not support the storage of primitive data types; it can only store objects. In Java, however, an array can include both primitive data types and objects.

100. What are HashSet and Linked HashSet?

Ans. The HashSet class of the Java collection framework is for creating a collection that stores objects using a hash table as the primary storage mechanism.  It does not maintain the order of insertion.

The LinkedHashSet class, on the other hand, is very similar to the HashSet class. Furthermore, it preserves the order of insertions. The HashSet class inherits the features of the Java class known as AbstractSet and it uses the Set interface. The L1inkedHashSet class is derived from the HashSet class and implements the Set interface, among other things.

That’s it, folks! These were the basic 100 Java interview questions. If you perfectly prepare these questions for your interview or even any entrance exam, then we can guarantee that you will ace it. These are the most important interview questions related to Java that everyone
must know.


Java Interview Tips

The interview tips here are for both fresher and experienced candidates appearing for their next Java Interview.

  • As Java has its primary use in application programming so if you’re a fresher or an experienced candidate; expect the focus of the interview aligned with questions on Java API’s, Java Design Pattern in OOP and Concepts.
  • However if you are a fresher candidate with 0-2 years of experience will see more questions on topics like Java fundamentals, Java API’s like Collections, their implementation with respective data structure, and algorithms.
  • If you are an experienced Java developer applying for senior developer profiles, you might find more questions on concurrent programming, Java concurrency API, JVM internals, GC tuning, and Java Performance.
  • If you are preparing for a interview related to Java Backend developer profile, it is recommended to be well versed with Frameworks like Spring & Spring Boot and one Database server(of your choice).
  • When it comes to your interview, make sure you answer the questions to the point any misleading argument that might lead to another question which will waste the interviewer’s time and pose a negative feedback.
  • Instead try to pay attention and listen to the hints carefully given by the interviewer before answering the questions related to coding problems.
  • After this, make note of key topics that you find hard to understand. Then make sure you go through them in depth to avoid any problems.

If you follow these tips it will be much easier for you to ace your next java interview.

More Java Interview Q&A

Core java interview questions

This list includes top 50 core java interview questions. Whether you are fresher or experienced programmer, this interview questions will definitely help you to crack core java interview.


Collections interview questions

Collection is one of the major important parts of core java. These interview questions include questions on HashMap, Hashet, Arraylist etc. These are logical interview questions which will help you built reasoning for these questions.


Multithreading interview questions

Multithreading concepts are the tricky one. This java interview questions list covers threads, synchronization, inter thread communication and executor frameworks.


Java 8 interview questions

Java 8 has a lot of new features. If you are going to core java interview, you might be asked about lambda expressions, function interface, streams, new Date and time APIs etc.


OOPs interview questions

Object-oriented principles are build blocks of java. This list includes questions on Abstraction, encapsulation, inheritance, and polymorphism.


Exception Handling interview questions

This java interview questions list covers questions on Exception hierarchy, check, unchecked exceptions, try catch block etc.


String interview questions

String is one of the most used datatype in Java. These interview questions will check your knowledge on String concepts.


Serialization interview questions

Serialization is one of the most important topic in core java. These interview question covers some of the tricky questions on Serialization.


method overloading and method overriding interview questions

This java interview question list includes tricky method overloading and overriding interview questions. It will help you to understand method overloading and overriding in the better way.


Immutable class interview questions

Immutable class is one of the most important concepts as immutable classes are by default thread safe. This interview question list will check your knowledge on immutable classes.


Java tricky interview questions

This interview question list includes some tricky interview questions. These java interview questions will help you to build logic.


Basic interview questions for fresher

This java interview questions list includes basic interview questions on beginner java programmers.


Interview questions for 5 to 7 years experienced

This java interview questions list includes some good questions for an experienced programmer. It includes concepts from multithreading and collections .


How HashMap works in java?

This is most asked java interview question and it is favorite interview questions for most of the interviewer. This interview question checks your knowledge on HashMap, hashcode and equals method.


Difference between Interface and abstract class? What are changes made to interface in Java 8?

You can have default and static method in java from Java 8 onwards.


Spring

Spring interview questions

Spring framework is most widely used Java EE framework. Spring interview questions check your knowledge on spring framework. It covers topics like dependency injection, scopes, Spring AOP concepts and some important Spring annotations.


Spring boot interview questions

Spring boot is getting popular day by day because it helps you to bootstrap spring application faster. These spring boot interview questions check your knowledge on Spring boot.


Web services

Web services interview questions

Web services interview questions check your knowledge on soap and restful web services.


Rest web services interview questions

These interview questions include restful web services,HTTP methods, and various web service annotations.


Data structure and algorithms

Introduction

This post provides an introduction to important data structures in java. It will help you to understand basic data structures such as queue, stack and linked list.


Data structures and algorithms interview questions

These 40+ interview questions check your knowledge on Stack, queue, linked list, binary tree, binary search tree etc.

Java interview programs

For beginners

If you are freshers or novice programmer, here is the list of interview programs which you can practice.

For experienced programmer

If you are experienced programmer and looking for the list of some good java interview programs, here is the list of java interview programs which you can practice.

If you are looking for java developer remote job, I will recommend jooble job portal.
I hope this Java interview questions list will help you to crack java interview. If you want to add more interview questions, please do comment.

]]>
https://java2blog.com/java-interview-questions/feed/ 0
Difference between Runnable and Callable in java https://java2blog.com/difference-runnable-callable-java/?utm_source=rss&utm_medium=rss&utm_campaign=difference-runnable-callable-java https://java2blog.com/difference-runnable-callable-java/#comments Fri, 15 Dec 2017 19:50:30 +0000 https://www.java2blog.com/?p=4351 Runnable and Callable interface both are used in the multithreading environment.Callable is available in java.util.concurrent.Callable package and Runnable in java.lang.Thread.

Difference between Runnable and Callable interface in java

  • Runnable was introduced in java 1.0 version While Callable is an extended version of Runnable and introduced in java 1.5 to address the limitation of Runnable.
  • Runnable does not return any value; its return type is void, while Callable have a return type.So, after completion of task, we can get the result using get() method of Future class. Future class has various methods such as get(), cancel() and isDone() by which you can get or perform various operations with respect to tasks.Ex:
    //Runnable interface method's run method has return type as void
    public void run()
    {
    
    }
    
    //Callable interface method's call method has return type as generic V
    V call() throws Exception;
    {
    
    }
    Callable is a generic interface means implementing class will decide the type of value it will return.
  • Runnable does not throws checked exception while Callable throws checked exception(i.e exception that are checked at compile time)so, at compile time we can identify the error.
  • In Runnable, we override run() method, while in Callable, we need to override call() method.
  • Runnable is used when we don’t want any return value after completion of task for ex: logging, while Callable is used  when we want to get a result of the computation.
  • First, we create the instance of class which has implemented Runnable interface and after that create instance of Thread class and then pass the object of Runnable class as parameter in Thread class.
    Runnable Class rc=new RunnableClass();
    Thread t=new Thread(rc);
    t.start();
    In case of Callable,we can not pass Callable into Thread to execute, so we need to use ExecutorService to execute Callable object.
]]>
https://java2blog.com/difference-runnable-callable-java/feed/ 1
Print Numbers Using Multiple Threads in Java https://java2blog.com/print-sequence-3-threads-java/?utm_source=rss&utm_medium=rss&utm_campaign=print-sequence-3-threads-java https://java2blog.com/print-sequence-3-threads-java/#comments Thu, 16 Nov 2017 18:55:28 +0000 https://www.java2blog.com/?p=4669 In this post, we will see how to print numbers using multiple threads in java.It is similar to printing odd-even numbers using two threads in java.

Problem

You are given 3 threads. You need to print sequence using these 3 threads.You need to print in natural order up to MAX.

For example:
Let’s say you have 3 threads. T1,T2 and T3.
If MAX is 10, you need to print:

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

Solution

We will use concept of remainder here.

  • If number%3==1 then T1 will print the number and increment it else will go in the wait state.
  • If number%3==2 then T2 will print the number and increment it else will go in the wait state.
  • If number%3==0 then T3 will print the number and increment it else will go in the wait state.

Let me provide simple program for it.
Let’s create a class named "PrintSequenceRunnable" which will implement the Runnable interface.

public class PrintSequenceRunnable implements Runnable{

    public int PRINT_NUMBERS_UPTO=10;
    static int  number=1;
    int remainder;
    static Object lock=new Object();

    PrintSequenceRunnable(int remainder)
    {
        this.remainder=remainder;
    }

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO-1) {
            synchronized (lock) {
                while (number % 3 != remainder) { // wait for numbers other than remainder
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}

Let’s create a class named "PrintThreadsSequentiallyMain" which will implement the Runnable interface.

public class PrintThreadsSequentiallyMain {

    public static void main(String[] args) {

        PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
        PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
        PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);

        Thread t1=new Thread(runnable1,"T1");
        Thread t2=new Thread(runnable2,"T2");
        Thread t3=new Thread(runnable3,"T3");

        t1.start();
        t2.start();
        t3.start();   
    }
}

When you run above program, you will get below output.

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

That’s all about printing numbers using multiple threads in java.

]]>
https://java2blog.com/print-sequence-3-threads-java/feed/ 1
SOLID Principles in Java https://java2blog.com/solid-principles-java/?utm_source=rss&utm_medium=rss&utm_campaign=solid-principles-java https://java2blog.com/solid-principles-java/#comments Thu, 09 Nov 2017 14:17:00 +0000 https://www.java2blog.com/?p=4517 In this post, we will see 5 SOLID Principles in Java.

Robert C. Martin gave five objected oriented design principles, and the acronym S.O.L.I.D is used for it. Each letter of this acronym talks about principles in Java. When you use all the principles of S.O.L.I.D in a combined manner, it becomes easier for you to develop software that can be managed easily. The other features of using S.O.L.I.D are:

  • It avoids code smells
  • Quickly refractor code
  • Can do adaptive or agile software development

When you use the principle of S.O.L.I.D in your coding, you start writing the code that is both efficient and effective.

What is the meaning of S.O.L.I.D?

As stated above, S.O.L.I.D represents five principles of Java which are:

  1. S: Single responsibility principle
  2. O: Open-closed principle
  3. L: Liskov substitution principle
  4. I: Interface segregation principle
  5. D: Dependency inversion principle

The article discusses each of this principle in-depth. We will start by considering the very first principle, which is single responsibility principle.

Single Responsibility Principle (SRP)

According to the single responsibility principle, there should be only one reason due to which a class has to be changed. It means that a class should have one task to do. This principle is often termed as subjective.

The principle can be well understood with an example. Imagine there is a class that performs the following operations.

  • connected to a database
  • read some data from database tables
  • finally, write it to a file.

Have you imagined the scenario? Here the class has multiple reasons to change, and few of them are the modification of file output, new database adoption. When we are talking about single principle responsibility, we would say, there are too many reasons for the class to change; hence, it doesn’t fit properly in the single responsibility principle.

Open Closed Principle

According to open closed principle, entities or objects should remain open for extension, but they should stay closed for modification. To be precise, according to this principle, a class should be written in such a manner that it performs its job flawlessly without the assumption that people in the future will simply come and change it. Hence, the class should remain closed for modification, but it should have the option to get extended. Ways of extending the class include:

  • Inheriting from the class
  • Overwriting the required behaviors from the class
  • Extending certain behaviors of the class

An excellent example of an open-closed principle can be understood with the help of browsers. Do you remember installing extensions in your chrome browser?

The primary function of chrome browser is to surf different sites. Do you want to check grammar when you are writing an email using chrome browser? If yes, you can simply use Grammarly extension, it provides you grammar check on the content.

This mechanism where you are adding things for increasing the functionality of the browser is an extension. Hence, the browser is a perfect example of functionality that is open for extension but is closed for modification. In simple words, you can enhance the functionality by adding/installing plugins on your browser, but cannot build anything new.

Let’s take another example.
You are using any Spring function functionality. You can obviously not change the core logic of it, but you can extend Spring framework classes and create your own one.

Liskov Substitution Principle

Liskov substitution principle assumes q(x) to be a property, provable about entities of x which belongs to type T. Now, according to this principle, the q (y) should be now provable for objects y that belongs to type S, and the S is actually a subtype of T. Are you now confused and don’t know what Liskov substitution principle actually mean? The definition of it might be a bit complex, but in fact, it is quite easy. The only thing is that every subclass or derived class should be substitutable for their parent or base class.

You can say that it is a unique object-oriented principle. The principle can further be simplified by understanding this principle; a child type of a particular parent type without making any complication or blowing things up should have the ability to stand in for that parent.This principle is closely related to the Liskov Substitution principle.

Interface Segregation Principle

According to interface segregation principle, a client, no matter what should never be forced to implement an interface that it does not use or the client should never be obliged to depend on any method, which is not used by them.

So basically, the interface segregation principles as you prefer the interfaces, which are small but client specific instead of the monolithic and bigger interface.

In short, it would be bad for you to force the client to depend on a certain thing, which they don’t need.

Let us now again take an example to understand this.

Let’s take a simple example. You are implementing your own ArrayList and LinkedList in java. You create an interface called List which both classes will implement.

package org.arpit.java2blog;

public interface List<T> {
    public T get();
    public void add(T t);
    public T poll();
    public T peek();    
}

Let’s create LinkedList class now.

package org.arpit.java2blog;

public class LinkedList implements List<Integer>{

    @Override
    public Integer get() {
        // Implement this method
        return null;
    }

    @Override
    public void add(Integer t) {
        // Implement this method
    }

    @Override
    public Integer poll() {
        // Implement this method
        return null;
    }

    @Override
    public Integer peek() {
        // Implement this method
        return null;
    }
}

Let’s create ArrayList class now.

package org.arpit.java2blog;

public class ArrayList implements List<Integer>{

    @Override
    public Integer get() {
        // Implement this method
        return null;
    }

    @Override
    public void add(Integer t) {
        // Implement this method
    }

    @Override
    public Integer poll() {
        // ArrayList does not require this method
        return null;
    }

    @Override
    public Integer peek() {
        // ArrayList does not require this method
        return null;
    }
}

Do you see the problem, even though you do not require poll()and peek() methods in ArrayList, we have implemented them.
The correct solution for above problem will be:
Create another interface called Deque which will have peek() and poll() methods.

package org.arpit.java2blog;

public interface Deque<T> {
    public T poll();
    public T peek();    
}

And remove peek and poll from list interface.

package org.arpit.java2blog;

public interface List<T> {
    public T get();
    public void add(T t);   
}

Let’s change LinkedList class now.

package org.arpit.java2blog;

public class LinkedList implements List<Integer>,Deque<Integer>{

    @Override
    public Integer get() {
        // Implement this method
        return null;
    }

    @Override
    public void add(Integer t) {
        // Implement this method
    }

    @Override
    public Integer poll() {
        // Implement this method
        return null;
    }

    @Override
    public Integer peek() {
        // Implement this method
        return null;
    }
}

Let’s change ArrayList class now.

package org.arpit.java2blog;

public class ArrayList implements List<Integer>{

    @Override
    public Integer get() {
        // Implement this method
        return null;
    }

    @Override
    public void add(Integer t) {
        // Implement this method
    }
}

As you can see, we have seggregated two interface to achieve required functionality.

Dependency Inversion Principle

According to this, dependency inversion principle, entities should depend only on abstractions but not on concretions. According to it, the high-level module must never rely on any low-level module but should depend on abstractions. Let us again understand it through another practical example.

You go to a local store to buy something, and you decide to pay for it by using your debit card. So, when you give your card to the clerk for making the payment, the clerk doesn’t bother to check what kind of card you have given. Even if you have given a Visa card, he will not put out a Visa machine for swiping your card. The type of credit card or debit card that you have for paying does not even matter; they will simply swipe it. So, in this example, you can see that both you and the clerk are dependent on the credit card abstraction, and you are not worried about the specifics of the card. This is what a dependency inversion principle is.

Wrap Up

I hope that now you know the basic definition of all the five components of S.O.L.I.D, which are single responsibility principle, open, closed principle, Liskov substitution principle, interface segregation principle, and dependency inversion. So, basically, whenever you write code, you have to keep these core principles in your mind, and actually, to be honest, you have to take these principles as your base map while writing those codes to make it efficient and effective.

The management of the code written by using these principles is also an easy task to do. Using this principle initially in your coding might look odd, but you need to practice writing your codes using these principles, and gradually it will become a part of you. And then, the code that you have written can be easily modified, extended, refactored, or tested without facing any problem according to the requirement that you meet. So practice this principle whenever possible to make your coding better.

]]>
https://java2blog.com/solid-principles-java/feed/ 1
Core Java interview questions https://java2blog.com/java-interview-questions-for-2-years-experience/?utm_source=rss&utm_medium=rss&utm_campaign=java-interview-questions-for-2-years-experience https://java2blog.com/java-interview-questions-for-2-years-experience/#comments Wed, 08 Nov 2017 13:57:00 +0000 https://www.java2blog.com/?p=4425 Core In this post, we are going to see Java interview questions for experienced.

These are the most asked interview questions for freshers(0-3 years experienced). This question list will help you to crack java interview. I have already shared detailed answer over here before, you might find it helpful as well.

I would like to apologize for putting so many links in this article but it is better to understand answer in good depth,so I have put links to details answers over here.

1.   Can we override static method in java?

No, you cannot override static method in java. You can only hide them. You can read the detailed answer over here.

2.   Can you overload main method in java?

Yes, you can overload main method in java.You can find the detailed answer over here.

3. Can we override private methods in java?

You can not override private methods in java as it is visible to that class only.

4. What is the base class for all the classes?

java.lang.Object is base class for the objects.

5.   Can you list down some of important method from object class?

Important methods of object classes are:

  • hashcode : It returns hash value of the object
  • equals : It compares the object references
  • wait : It causes current thread to wait until notify or notifyAll is not called
  • notify : Wakes up single thread which is waiting for lock
  • notifyAll: Wakes up all threads which is waiting for lock
  • toString : Provides String representation of the object
  • clone : This method is used to clone the object
  • finalize: This method is called when object is being garbage collected.

6.   Which two methods should you override while putting the custom object as Key in HashMap?

You need to override hashcode and equals method in custom class while putting objects of custom class in HashMap.

7.  What is the difference between HashMap and HashSet in java?

You can find details answer over here.

8. Can we have abstract class without having any abstract method in it?

Yes, you can have abstract class without having any abstract method.

9. Have you heard about transient variable? When will you use it?

Transient variables are used Serialization. If you don’t want to make variable serializable, you can make it transient variable.

10. Can you call start method twice in java?

No, you can not call Start method twice. It will throw illegal state exception. You can read detailed answer over here.

11. Do you know why String is immutable in java?

You can fin the detailed answer over here.

12. Do you know how to make a class immutable? Can you provide steps for it?

You can find detailed answer over here.

13. Can we have static method in the interface?

Yes, we can have static method in the interface from Java 8.

14. Can you declare constructor final?

No, You can not declare constructor final.

15. What is the difference between StringBuffer and StringBuilder?

Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously.
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

16. What is Java ClassPath?

ClassPath is environment variable which java virtual machine (JVM) uses to locate all classes which is used by the program.
For example: jre/lib/rt.jar has all java classes and you also need to include jar files or class file which is being used by program.

17. You have a list of Custom objects? How can you sort them?

You need to use Comparable or Comparator interface to sort list of custom objects.

18. What is volatile in java?

If you mark any variable volatile then this variable will be read from main memory rather than CPU cache so each thread will have updated value in the variable.

19. What are two different ways to call garbage collector?

System.gc() OR Runtime.getRuntime().gc().

20. What is marker interface in java? Can you provide some examples of marker interface?

Marker interfaces are those interfaces which do not have any method in it.

Examples of marker interfaces are : Serializable and Cloneable.

21. How many objects will be created below:

String str1= new String("John");
String str2= new String("John");

Three objects will be created here, two in heap memory and one in String constant pool.

22. Can you differentiate between Checked Exception and Unchecked exception?

You can find detailed answer over here.

23. What is the difference between ArrayList and LinkedList? How will you decide which one you need to use?

You can find details answer over here.

24. What is difference between wait and [sleep in java](https://java2blog.com/java-thread-sleep-example/ “sleep in java”)?

You can find details answer over here.

25. You have started three threads from main threads.You need to make sure main thread complete last. How will you do it?

You can use thread’s join method to achieve this scenario.
Without using join method:

package org.arpit.java2blog;

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() +" in run method");
    }
    public static void main(String[] args) {
        MyRunnable runnable=new MyRunnable();
        Thread t1=new Thread(runnable,"T1");
        Thread t2=new Thread(runnable,"T2");
        Thread t3=new Thread(runnable,"T3");

        t1.start();
        t2.start();
        t3.start();

        System.out.println("Main thread ends here");

    }
}

When you run above program, you might get below output:

Main thread ends here
T2 in run method
T1 in run method
T3 in run method

With the help of join method:

package org.arpit.java2blog;

class MyRunnable implements Runnable{

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() +" in run method");
    }
    public static void main(String[] args) {
        MyRunnable runnable=new MyRunnable();
        Thread t1=new Thread(runnable,"T1");
        Thread t2=new Thread(runnable,"T2");
        Thread t3=new Thread(runnable,"T3");

        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread ends here");

    }
}

When you run above program, you will get below output

T2 in run method
T3 in run method
T1 in run method
Main thread ends here

As you can see, main thread complete last in this scenario.
You can also use CountDownLatch and CyclicBarrier too to achieve same scenario.

That’s all about java interview questions.
You may also like:

]]>
https://java2blog.com/java-interview-questions-for-2-years-experience/feed/ 7