Lambda Expression
- Interface with a single abstract method is called as functional interface
- It is denoted with annotation @FunctionalInterface
- Anonymous Classes, are created When we implement an interface in line, the implementation is hidden, and all we have is the reference to that implementation. that is the interface implementation name
- Lambda is replacement of anonymous functions.
- Lambda can only be used with functional interfaces.
- Anonymous and inheritance implementation can be used with abstract classes and interfaces.
- It is an in place implementation
- It is not reusable
- They were used very often before functional interfaces.
- In line means on the spot implementation.
- Lambda in functional Interfaces replaces Anonymous functions.
- Spring exclusively deals with interfaces using inversion of control.
- Composition design pattern is easy to implement with interfaces.
- In agile methodology, where changes are consistent interfaces are valuable.
- Annotations provide metadata for code We are writing.
- Interface is a pure abstract class.
- JSR or Java specification requests Must be followed while building a JDK.
- JDBC Specs Was released for database drivers. It is filled with interfaces and has only two classes.
- JDBC driver releases must be based on JDBC specifications.
- Interfaces play a vital role in consistency while development.
- Interface once written are not modified generally.
- Lambda is an in line representation of a code.
- If we are inheriting from a functional interface, our child interface, which is also a functional interface must not have any abstract methods in it.
- We can have default methods.
- Starting Java 9 We can write, a void main Inside interface to test other default functions and static methods.
- Whenever we declare anything in interface, it becomes public static void by default.
- Lambda expression is writing code with more symbols and less words
- Makes our code very concise and easy to maintain.
- When it comes to inheritance The child interface should not be functional. That is, it should not have abstract methods.
- Whenever we declare anything in interface, it becomes public static void by default.
- Var is a data type whose Type is revealed at run time.
- We can’t use other data types with var In method parameters.
- (int a,var b)->{} won’t compile
- Var can only be used in lambda, they can’t be used in proper methods.
- Var Was introduced in Java 9
- Primitives are not the part of object oriented concept of Java.
- Primitives Don’t have get class method() So assigning them to var Is risky As we can’t determine its time.
- Better to use var Only for objects
- Primitives are stored on top of stack(int,float,double,bool,byte)
- Each primitive gets a stack of a particular size.
- When we declare primitives within the brackets they define the scope/lifetime Of Premitive
- Garbage collection does not works on primitives.
- Garbage collection only works with reference types, which may be available outside the scope.
- Primitives may Have scope in class or method.
- It is always better to use wrapper over primitives As it supports generics.
- We can declare variables in lambda, but they will not be exposed outside.
- Controlling of threads Is done by JVM Thread scheduler.
- JVM consist of four parts
- Class loader
- Garbage collector
- Thread Scheduler
- Programme Access memory
- Program managed area.
- Thread scheduler Is responsible for managing lifetime of threads.
- NDA-Non Deterministic Automata.
- Default methods and multiple inheritance
- Default methods are also called as defender methods or virtual extension methods.
- To test default methods in interface, main method create inner class Which implements interface use its object to call default method.
- Comparable is not used with lambda’s, Because we compare objects.
- Comparator Is mostly used while overriding its sort method.
- We can override and overload default methods.
- When we implement two interfaces with same default method, then we have to override one of the methods.
- String builder in thread safe String buffer is not.
- Static methods can’t be overridden. They must be called with interface name as they are not inherited.
- Predicate Joining
- EJB(Enterprise Archive(EJB))
Predicates and Method Reference
- A lambda expression That evaluate to either true or false is called as predicate.
- Predicate interface is inside, Java util functions package.
- Predicate can be passed as a parameter to a method.
- Predicate interface has only one abstract method that is test.
- Whenever we declare in interface, everything becomes public, static final.
- We can join predicates using “and”,”or”,”negate”.
- Predicates are very useful for doing testing.
- These are used for testing boundary value conditions.
- Types of Packaging distributable in java.
- Java Archive(non exec, runnable)
- runnable has void main.
- War
- Web Archive
- Ear
- Enterprise Archive(EJB)
- Function
- A predicate which returns more than boolean That is any Java type is called as function.
- A function can return any java object.
- It is a predefined interface to return a response.
- Bifunction Can take two Inputs and returns an output.
- To send multiple values to a function, we use list or an array.
- Functions are anonymous. They take parameters and return variables.
- Predicate Takes An input type parameter and return boolean.
- Function can take two type parameters input type And output type.
- Second type parameter is return type.
- Function calls apply to execute and Predicate calls test to execute.
- Everything predicate can do function can do. But what function can do predicate cannot do.
- Predicates can only return Boolean values. Functions can return any value.
- Unit tests Will have no effect as far as lambda is concerned.
- Method Reference
- We use “::” For method reference in Java.
- We have a functional interface, and there is a class method whose signature exactly matches the functional interface.
- If there already exist a method with same signature, then we do not have to rewrite the method.
- For example, we use “tostring()” method As reference from class. We also use New to create object as reference.
- Reference means we are pointing, we are giving pointer to that method.
- Reference can be made to static or non-static methods.
- Using interface “disposed” within our class we can write destructor in Java class. Dispose is the destructor in Java class.
- If we prioritise a thread in Java There is no guarantee that it will be prioritised. It all depends on JVM.
- Set priority before we start our thread.
- There is no guarantee that after writing destructor, garbage collector will run or not.
- Finalise a method will not guarantee of GC run.
- Converting, runnable to lambda.
- It can be done by anonymous functions,Runnable Interface, Lambda, Method reference.
- We should not use lot of static in web applications.
- They are very dangerous
- Web applications like spring, boot, batch, et cetera
- Even for JSP and servlets
- Applets are not supported by Modern JDK’s
- When we start a thread From a thread It is called as spawning.
- Child, thread Cannot be synchronised.
- If we want a thread As demon thread Using setDemon() Property, it will run as background thread And response will not be displayed.
- When using interface for method, reference to create object it just act as a mediator between program and class.
- Program sends value to interface and interface calls the constructor.
- It is used in factory patterns.
- Returns the child class or implemented class Based on the parameters provided For example, we return interface with name database in abstract implementation.
- Based on the parameters passed, we return the concerned implemented class Postgres,MySQL etc
- Method references are best used in lambda’s.
- When a class, which is inheriting in which the constructor is overloaded Both in parent and child. In the child constructor, we have to account for parent constructor parameters.
Util Streams
- There are two types of streams in Java
- input/output streams
- Types of input output stream
- File input stream/File output stream
- Buffered input stream/buffered output stream
- Object output stream
- These streams are designed for handling input and output operations, primarily involving external data sources or destination.
- Input/ output streams are used for handling files.
- They are used for handling source of data.
- Source of data can be any Collection/File.
- util streams.
- Util streams are used to handle sync of data.
- Sink of data is final destination.
- In order to reach data in sink we need to commute it through a pipe from source.
- These pipes are temporarily created in memory.
- Streams provide these pipes which help data to move from source to destination.
- Util streams are transient in nature that is temporary. They are not permanent once used they are gone permanently i.e. deleted from memory.
- Transient means temporary only for time being.
- To make a Stream persistent convert to a collection like Array List, Set et cetera.
- Streams use operators to manipulate data.
- If we try to re-use stream we get an exception.
- There are two ways to convert anything to a stream.
- We use supplier consumer/ consumer producer pattern on streams.
- Consumers consumes data
- Supplier is source like Collection or Resultset
- Streams are in memory manipulator of data.
- Operations on stream
- Filter
- Transform
- Max
- Min
- Converting one stream to another stream
- Converting it to another collection.
- We can read stream via for each object which takes input as consumer interface.
- A consumer has accept method.
- Screen can only be read with consumers interface.
- Consumers allow us to capture read data and perform operations on it.
- Inside a stream, our data is converted into bits.
- It speeds up processing.
- Like streams we cannot reuse ResultSet in Java because it is a dataset curser, which is read only, forward only.
- Streams are transient/ephemeral.
- Streams are completely binary.
- Create streams and use them immediately as they carry memory cost.
- Transient objects are more effective than objects which stay in memory.
- Stream objects are immediately garbage collected once processed.
- Very effective way of handling data.
- Virtual memory will never go down if we use streams
- MAP is the most powerful, non-linear data structure.
- When we are using map and related data structures, we have to use BiConsumer.
- Linked list is the most powerful linear data structure.
- Following structures can be prepared from Linked list.
- Queue
- Vector
- Array List
- Set
- Deck
- Add comparator on SET Data structure and make it Tree Set.
- Vector is synchronised array list.
- Vector is thread safe array list.
- Vectors are heavy and old, array list are fast and modern.
- There is no queue class in Java.
- Queue is an Interface.
- Internally hash map also uses hash tables.
- Hash map internally keeps two sets of data and maps so it is not organised as table internally.
- Element from domain.
- Element of range.
- Hash table stores data as table. Hash tables are 16 times faster than relational databases.
- Even JVM uses hash tables.
- Object hash is printed when we print an object.
- The accuracy of float is up to 7 digits.
- Double has 14 digits accuracy.
- For financial applications we use BigInt, BigFloat, Big Double
- These have more accuracy.
Try Catch Blocks
- In void main if we are writing test code, it is better not to use to try catch blocks instead, use throws.
- Only for custom exception use try/catch.
- Try catch is ideal for web applications.
- If we are using throws at method level, we will have to re throw wherever this method is called.
- Exception in web services is used to determine faults and need to be presented to debug so there we need try catch.
- In Java, -1 is the end of the file. Once the fileReader or the fileInputStream object reaches end of the file it returns -1.
JDBC
- JDBC started off as more of C code with Java.
- It was initially slow. The slowness was due to interprocess communication(IPC). The C code worked slower.
- Since version 3 and Version 4 every thing was written in Java.
- Nowadays we also have private components in interface.
- Generally, JDBC assumes we know the data type of column we are fetching. So we fetch using getInteger, getString, getFloat etc when we don't know we use getObject.
- To know how many columns are there in a table using JDBC we use interface ResultSet MetaData.
- IBatis is predecessor to Spring. It uses AOP. JDBC is compatible with most frameworks and databases and never fails.
- Hibernate, ORM framework internally uses JDBC.
- JPA writes queries in object oriented language so these JSQL/JPA/JPSQL queries are converted into select queries and running on top of framework.It does not work everywhere.
- JPA queries doesn't support Postgres database directly.
- Real-time systems/ Electronic systems don't need database. Rest all systems need database.
- For data persistency we need database.
- Streams are faster than JDBC as they don't require repeated connections and do in memory processing.
- For JDBC connections, we can inject code in service the connection, but we should not write JDBC code in service as it will slow down the service.
- In live databases where connection dropping is critical during connection pooling, we can fetch data once using SQL connection and process in memory using streams.
- Such a situation is also very risky for transactional databases.
- We don't have to open connections again and again while working with streams.
- Data can also be processed in relational databases, but it is not recommended.
- We can improve database performance by increasing the pool size, by increasing connection numbers, and by using load balancer.
- These can be applicable on enterprise system, but not on local environments.
- At maximum open eight connections only.
- Most of the things we do in SQL can be done using streams.
- While loading from properties file.
- Create object of properties class.
- Do properties.load(properties file) and use the property in your application.
- Class.forName(Driver Name) is not required since JDBC4.
- The name for database drivers is given using JNDI names.
- JNDI is Java Naming directory interface.
- It is a Java registry, where a driver is registered in that registry.
- Java asks JNDI to load particular drivers from directory.
- JNDI is Java's own registry.
- For mysql driver name is "com.mysql.cj.jdbc.Driver"
- cj is required only for version 8 and 9 of driver.
- This name is given by the vendor of database.
- Java asks JNDI to load particular driver from directory.
- JNDI is Java's own registry
- We don't create any objects for JDBC components like ConnectionStatement, ResultSet, DriverManager
- Only the registered names are pulled out of the JNDI registry.
- The registry is kept up-to-date when ever we start installing our database. It is updated automatically.
- Even the connection string has a particular format
- jdbc:mysql://localhost:3306/database.
- Class.forName(driver) is used when we don't want to unload our driver before our program finishes execution.
- We alert garbage collector for not touching our driver class. It will be unloaded eventually.
Static Block Code
- To use static block code effectively, put it inside constructor.
- In fact, if we use constructor, we don't have to use static.
- In web applications, mostly we use constructors because in distributed scenarios, statics don't work effectively.
- In normal applications, we can use statics.
- In spring, it is better to create the object outside.
- We create object in main which implements to interfaces, command line runner and spring application runner.
- Use command line runner for static, initialisations and inject in application.
- When we write a code in static method it acts as singleton. It executes only once.
- When we do System.out.println we do not have to call toString() explicitly.
- If we do it in any other framework such as Spring,Struts,JSF,MVC toString() needs to be called explicitly.
- Singleton classes do not have performance as compared to static blocks.
- Most compiler time is lost in creating additional constructors.
- Static is factory style of creating Singleton.
- Static blocks are only initialised once during the life span of a class.
- Static methods are called using :: operator in Java. This was added after Java 1.9
- Private constructors are very helpful in inner classes.
- These are used in builder pattern.
- Generics are used to create classes, interfaces and methods that operate on various data types without requiring the exact type to be specified in advance.
- T is used to represent Type
- E is used to represent Elements
- K is used to represent Key
- N is used to represent Number
- V is used to represent Value
- From Java seven onwards, we don't have to mention type while initialising with new statement.
- Genetics can be used using upper bounds
- List<? extends Number>
- Will accept all the classes which extend number.
- Helps us to optimise hardware usage as our program executes on all cause of all processors on need basis.
- It is also called as HPC(High Performance Cluster).
- Each core is divided into one area of our HPC cluster.
- Load balancer divides our request automatically amongst all of them.
- Parallel stream in Java was added in 1.9
- Parallel stream uses parallel processing.
- Parallel stream returns unordered results.
Records
- Model/Pojo classes are repetitive in nature.
- There was too much of boiler plate code like toString, constructor, hash code.
- JDBC centralised connectivity, but JDK didn't had any such feature.
- JDK started having Records.
- Records are thread safe.
- Records are immutable in nature. We can't modify them.
- Scala, Groovy are sub languages of Java.
- Scala emphasis on the functional nature of the code.
- There are no interfaces in Scala or groovy they have traits.
- Never touch overloaded constructor of Records.
- We can add additional constructor, static methods.
- A record is a POJO but immutable POJO.
- ToString is already implemented.
- Constructor is already implemented.
- Hash code is already implemented.
- Equals method is already implemented.
- OOPS is not enough for modern day programming.
- Immutable classes can be modified. They cannot be overridden.
- That is, Data can't be changed in same class.
- Records are basically immutable classes
- Best used for transactional data which changes fast.
- Java is slow at processing data so the data may get changed in between for example, while persisting a database object overriding by another object all adding the same is very common scenario.
- A record is basically a row in your database.
- Database views cannot be parameterised.
- Difference between table and view is view are completely read only.
- Views are virtual tables, a sophisticated way of storing our Json.
- Views cannot be modified. To modify the view we need to modify table view is composed of.
- Views, are precompiled so they work faster than normal joins.
- Stored procedure works the fastest.
- We cannot do crud operations on view.
- We have two engines in Mysql the default engine is InnoDb.
- The difference between Engines is the accuracy with which they store numerical data.
- It is known as collation order.
- Mysql uses Transact SQL(TSQL). Also used by Sysbase, SQL Server and Mysql.
- Superset of all SQL's is NC SQL. Every database must follow NC SQL.
- Stored procedure is precompiled. All other SQL statements are compiled on spot. These are called as ad hoc queries.
- A procedure is first compiled and result is stored in cache of the database
- It has fastest execution.
- It is used for writing business logic in backend.
- Stored procedures are 4 times faster than adhoc queries.
- For transactional queries we must use stored procedures.
- In mysql we should not start stored procedure with sp.
- If we are starting with sp don't use capital letters.
- System stores procedures in mysql database "sys" start with "sp".
- Mysql gets confused and starts looking for stored procedures at wrong place.
- We call stored procedure in java using callable statement.
Queues
- Blocking queue is useful for those working on messaging.
No comments:
Post a Comment