Showing posts with label Technical. Show all posts
Showing posts with label Technical. Show all posts

January 01, 2020

#Java8 Transform object into another type

Sometimes we need to convert or cast or transform an object from one type to another class. There are many ways, by which we can do it.

Let's say we have two objects ExternalPeopleInfo and InternalPeopleInfo. Assume we get ExternalPeopleInfo by calling some external API, but to save the details in our system we need to convert it in to InternalPeopleInfo.

January 11, 2019

#RxJava Part 5 : map() vs flatMap()

What is the difference between map() and flatMap()?
The map() method works well with Optional if the function returns the exact type we need. e.g:

Optional s = Optional.of("employee");

But in more complex cases we might be given a function that returns an Optional too. In such cases using map() would lead to a nested structure, as the map() implementation does an additional wrapping internally.

assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") .map(s -> Optional.of("STRING")));

#RxJava Part 4: Operators in RxJava

An operator is a function that takes one Observable as a source as its first argument and returns another Observable as the destination. For every item that the source observable emits, it will apply a function to that item, and then emit the result on the destination Observable.

When we want to create complex data flows that filter event based on certain criteria, we can chain the operators one after another. i.e we can apply multiple operators to the same observable.

#RxJava Part 3 : from(), just(), range(), interval(), timer()

Observable.from() Example
In the below example, the from() method dissolves the list/array and emits each value one at a time.

GIT URL: RxJavaDemoFrom.java
Observable.just()
The Observable.just() will emit whatever is present inside the just function. It can take between 2 to 9 parameters, we can pass a List/Array in it and it’ll emit the List/Array only.

GIT URL: RxJavaDemoJust.java

Observable.range()
Observable.range(start,n) methiod is used to emit 'n' number of values starting from and inclusive of start. e.g:

Observable rangeObservable = Observable.range(3,5);
rangeObservable.subscribe(intSubscriber); //emits 3,4,5,6,7
Observable.empty() //creates an empty observable that emits nothing. It just completes.
Observable.error() //creates an error. The onError() of all the subscribers would be called.
Observable.never() //does nothing. Neither emits a complete nor an error.

Observable.interval()
Observable.interval() emits constant sequences of integers in ascending order which are evenly spaced by the interval specified. e.g: Below code will emit 0 to 4 each second. We’ve set the thread to sleep to prevent the main function from returning immediately.

Observable intervalObservable = Observable.interval(1, TimeUnit.SECONDS);
intervalObservable.subscribe(System.out::println);
Thread.sleep(5000);

Observable.timer()
Unlike interval, an Observable.timer() emits value only after a certain time/delay. e.g: below code will emit only a single value after the delay.

Observable intervalObservable = Observable.timer(2, TimeUnit.SECONDS);
intervalObservable.subscribe(System.out::println);
Thread.sleep(5000);

Observable.defer()
The Observable.defer() is similar to create() except that it postpones the actual creation until an Observer subscribes. Each subscription would recall the Observable creation. This ensures that the Observer would always receive the latest data. It also ensures that no API call occurs until Subscription. The data would be only fetched when required by the observer. e.g:

Observable deferObservable = Observable.defer(() -> Observable.just(1, 2, 3));

-K Himaanshu Shuklaa..

#RxJava Part 2 : Creating Observable, Observers and Subscribers

Creating Observers and Subscribers
While creating Observers and Subscribers, we need to override three methods:
  • onNext(): It gets the current value. It is called on observer each time a new event is published to the attached Observable. This is the method where we'll perform some action on each event.
  • onComplete(): It gets triggered when there is no more data left to be sent by the observable. This method indicate that we should not expect any more onNext calls on our observer
  • onError(): It gets triggered in case an exception  is thrown during the RxJava framework code or our event handling code.
FYI, the Iterator does have the equivalents for onNext() and onComplete() (hasNext()). It doesn’t have one when an exception is thrown. This is another advantage of Reactive code.

#RxJava Part 1

Reactive Programming
  • In reactive programming, we react to changes in the state instead of actually doing the state change.
  • The reactive model listens to changes in the event and runs the relevant code accordingly.
  • e.g if in an excel file we have three columns A, B and C. In the C column we added a formula because of which value in C is A+B. All the rows of column C is populated with the summation of values in A and B. Now if we change the formula from A+B to A-B, it will automatically change the values in all the rows of column C.
  • Reactive Programming is a programming paradigm that’s concerned with data streams and propagation of change.
  • Assume the data streams are in the form of a river that flows continuously. Any observer/subscriber attached listening to the stream would receive the data. The data received can be further transformed using functions and this is where Functional Programming joins the already so powerful Reactive Programming.
  • In reactive programming, the flow is asynchronous thereby preventing any blocks on the main thread.

May 07, 2017

#Part 8: Hibernate Interview Questions

Should all the mapping files of hibernate have .hbm.xml extension to work properly?
No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.

#Part 7: Hibernate Interview Questions ( N+1 problem)

What is N+1 SELECT problem in Hibernate? How to identify and resolve it?
The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.

This N+1 query problem is not specific to JPA or Hibernate, it can be triggered using any data access technology, even with plain SQL.

May 06, 2017

#Part 6: Hibernate Interview Questions

What is the purpose of Session.beginTransaction()?
Hibernate keeps a log of every data exchange with the help of a transaction. Thereon, in case a new exchange of date is about to get initiated, the function Session.beginTransaction is executed in order to begin the transaction.

#Part 5: Hibernate Interview Questions (Composite and Derived Identifiers)

Composite Identifiers
Hibernate also allows us to define composite identifiers. FYI, a composite id is represented by a primary key class with one or more persistent attributes.
Here are the conditions which a primary class need to fulfil:
  • It should be defined using @EmbeddedId or @IdClass annotations
  • It should be public, serializable and have a public no-arg constructor
  • It should implement equals() and hashCode() methods
  • The class's attributes can be basic, composite or ManyToOne while avoiding collections and OneToOne attributes.

#Part 4: Hibernate Interview Questions (Identifiers in Hibernate-JPA)

Generated Identifiers and Hibernate GeneratedValue Strategies
Hibernate provides a couple of generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation.

May 05, 2017

#Part 3: Hibernate Interview Questions (Mapping Relations)

How to achieve mapping in Hibernate?
Association mappings are one of the key features of Hibernate. It supports the same associations as the relational database model. We can map each of the below associations as a uni or bidirectional association.
  • One-to-One associations
  • Many-to-One associations
  • Many-to-Many associations

#Part 2: Hibernate Interview Questions


What is the difference between save() , persist() ansaveOrUpdate methods of session object?
  • save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. 
  • session.save() saves the object and returns the id of the instance, whereas persist do not return anything after saving the instance. The return type of save() is a Serializable object, while return type of persist() method is void.
  • persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (like "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.
What is the difference between get() and load() methods of session object?
  • get() returns null if no data is present, whereas load throws ObjectNotFoundException exception in such case.
  • get() always hits the database, whereas load() method doesn't hit the database.
  • get() returns actual object, whereas load() return proxy without hitting the database unless required.

#Part 1: Hibernate Interview Questions

What is an ORM tool?
Object-relational mapping (ORM) is a technique that convert the data between relational databases and object oriented programming languages such as Java, C# etc. An ORM tool helps in simplifying data creation, manipulation, and access. It internally uses the Java API to interact with the databases.

November 15, 2016

Java Annotations Interview Questions and Answers

What are Java Annotations?
Java Annotations were added to the java from JDK 5.They allow us to add metadata information into our source code, although they are not a part of the program itself.

An annotation always starts with the symbol @ followed by the annotation name. The symbol @ indicates to the compiler that this is an annotation.

April 06, 2016

#Java: Part 8-Core Java Interview Questions and Answers (Interface, final, finalize, finally)

> > Part 7-Core Java Interview Questions and Answers (Generics)

What is an interface and what are the advantages and disadvantage of using interfaces in Java?
  • With interfaces, we can achieve abstraction in Java along with abstract class.
  • Interface in java is declared using keyword interface and it represent a Type like any Class in Java. A reference variable of type interface can point to any implementation of that interface in Java.
  • All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants.
  • All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. You can not define any concrete method in interface (till java 7). That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.

#Java: Part 7-Core Java Interview Questions and Answers (Generics)

> > Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

What is Generics in Java ?
Generics is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, provides compile time type-safety and ensures that you only insert correct Type in collection and avoids ClassCastException in runtime.

#Java: Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

> >  Part 5-Core Java Interview Questions and Answers (Clone and Immutability)

What are Wrapper classes?
A wrapper class wraps (encloses) around a data type and gives it an object appearance. They include methods to unwrap the object and give back the data type. e.g
int intCount = 100;
Integer wrapperIntCount = new Integer(intCount); //this is called Boxing
int intCountBack = wrapperIntCount.intValue(); //thats unBoxing

There are mainly two uses with wrapper classes:
1) To convert simple data types into objects, i.e to give object form to a data type.
2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

#Java: Part 5-Core Java Interview Questions and Answers (Clone and Immutability)

> > Part 4-Core Java Interview Questions and Answers (HashCode & equals())

What is a Cloneable interface and what all methods does it contain?
Cloneable is a declaration that the class implementing it allows cloning or bitwise copy of it's object state. It is not having any method because it is a Marker interface.

How clone method works in Java?
The clone() method from java.lang.Object class is used to create a copy of an Object in Java. This copy is known as a clone of original instance. Constructor is not called during cloning of Object in Java.

clone() method is declared as protected and native in Object class. Since its convention to return clone() of an object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method.

#Java: Part 4-Core Java Interview Questions and Answers (HashCode & equals())

> > Part 3-Core Java Interview Questions and Answers

When you are writing equals() method, which other method or methods you need to override? 
The right answer is hashCode(). Since equals and hashCode has there contract, so overriding one and not other, will break contract between them. Interviewer may ask about what are those contracts, what happens if those contracts breaks etc.