Java Se Imp Notes
Java Se Imp Notes
Java is a programming language and a platform from oracle corporation. It’s a high-level language having following
features:
Features of Java
1) Simple
Simple syntax. No pointers, no multiple inheritance with the classes which causes ambiguity error. For almost every
task API (Application Programming Interface) is available; Programmer just need to know how to use that API.
2) Object Oriented
Java is strong object oriented as it does not allow features like global data, friend function which are against OOP
principles.
4) Robust
Robust means strong. Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to
detect many problems that would first show up during execution time in other languages.
It provides the powerful exception handling and type checking mechanism as compare to other programming
languages.
5) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform specific machines. Java is
guaranteed to be compile-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on any
machine. Any machine with Java Runtime Environment can run Java Programs
6) Secure
If a bytecode contains any virus or malicious code, JVM will not execute it. This feature saves your system especially
when u download java code and try to execute.
7) Multi-Threading
Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
8) Portable
9) Architectural Neutral
No implementation dependent features. Everything related to storage is predefined, example: size of primitive data
types
Java enables high performance with the use of Just-In-Time (JIT) compiler.
Local Variable: A variable that is declared inside the method is called local variable.
Instance Variable: A variable that is declared inside the class but outside the method is called instance variable. It is
not declared as static.
Static variable: A variable that is declared as static is called static variable. It cannot be local.
Since Java is designed to support Internationalization (I18N), it makes sense that it would use Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the characters found in all
human languages. It is a unification of dozens of character sets such as Latin, Greek, Arabic, Russia and many
more. Developer will convert this application in such a way that clients from different countries can see the labels in
their languages.
For this purpose, it requires 16 bits. Thus, char in java is 16-bit type. The range of char is 0 to 65535. There are no
negative chars.
Note: java is platform independent. Compile once run anywhere [on any platform]
Every platform has its own jdk.
Ascii values
0-9 = 48-57
A-Z = 65 – 90
a-z = 97-122
JDK, JRE, JVM and API
JDK – java development kit in which there is JRE. JRE (java runtime environment) is a combination of JVM (java
virtual machine) and API (application programming interface).
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is the implementation
of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.
JVM - A .class file does not contain code that is native to your processor; it instead contains bytecodes — the
machine language of the Java Virtual Machine1 (Java VM). JVM that provides runtime environment in which java
bytecode can be executed.
Internationalization: is the process of designing an application so that it can be adapted to various languages and
regions without engineering changes. Sometimes the term internationalization is abbreviated as i18n, because there
are 18 letters between the first "i" and the last "n."
what is "this"?
"this" is a reference which refers to the current or invoking object.
What is the importance of "this"?
when u create multiple objects, u have those many copies of instance members however u have only one copy of
member function/s. In that case how will member function keep a track of invoking object.
member function/s will come to know about invoking or current object through "this" reference.
static block
syntax
static
static member
static members are allocated memory as soon as class gets loaded in the memory. They are not associated with the
instance.
Since they are not associated with instance, they are having only one copy in the memory, irrespective of no of
instances created.
They can be accessed by class name. They are also called as "class variables".
static member function is used to access private static member.
Static members can be share by all objects
e.g.
Account object
non-static members - accid, name, balance
static member - rateofinterest.
ABSTRACTION
Abstraction is the process of extracting the relevant properties of an object that are relative to the perspective of the
viewer, while ignoring nonessential details.
ENCAPSULATION
Encapsulation is the process of separating the aspects of an object into external and internal aspects. The external
aspects of an object need to be visible or known, to other objects in the system. The internal aspects are details that
should not affect other parts of the system. Hiding the internal aspects of an object means that they can be changed
without affecting external aspects of the system.
EX. ATM
User: EXTERNAL ASPECTS
Insert card
Withdraw money
get the balance
change the pin
get the statement
INTERNAL ASPECTS:
Algorithms connect to the database
Check sufficient balance
Debit the balance.
Main purpose of encapsulation is External aspects remain same even though Internal aspects change.
EX. CAR
Abstraction
From the driver’s perspective, acceleration and braking actions which can be performed on the car.
Encapsulation
When the driver presses the accelerator pedal (external aspect), there are a lot of things that happen within the car
which actually cause the rpm (rotations per minute of the wheel) to increase (Internal aspect). Is the driver concerned
about what actually happens within the engine? No. The driver just wants the car to accelerate on pressing the pedal
(external aspect) and is least bothered about the underlying mechanisms used by the manufacturers to achieve this.
He doesn’t care about how the engine is designed or as to how the piston is moving to achieve acceleration (internal
aspect). All he knows (and wants to know generally) is that the car should accelerate when he presses the pedal.
Inheritance
The ability for a new class to be created from an existing class by extending its properties is known as inheritance. It
provides reusability.
Basically, you go for inheritance when u realize that "new type is same as existing type".
Java allows only 3 types of inheritance
a) single level
b) multi-level
c) Hierarchical
Inheritance is inbuilt in java i.e. if your class is not derived from any base class, "[Link]" is the base class of
it.
Reusability
means using existing type while defining a new type. It can be achieved in two ways:
a) composition/aggregation [has-a relationship]
b) inheritance [is-a relationship]
composition/aggregation: you go for composition/aggregation when you want to use some of the functionalities of
existing type inside new type.
Ex. while designing "Car" you would reuse "Engine" by composition/aggregation, because "Car" is not an "Engine" it
just needs some functionalities of Engine.
Inheritance: you go for inheritance when you realize that new type is "same as" existing type.
Ex. while designing "Car" you would reuse "Four-wheeler" because Car is same as Four-wheeler.
Finalize method:
finalize method can be defined in order to release resources such as File, Database connection or Socket.
Since there is no guarantee as to when exactly object gets garbage collected, we cannot completely rely upon
"finalize" method for releasing resources. We have to have some alternate mechanism in order to release resources.
package
1. package is a collection of related classes and interfaces.
2. package is mainly used to avoid name conflicts.
3. package concept is similar to "namespace" concept of C++.
4. java has so many in-built packages. e.g.
[Link]
[Link]
[Link]
[Link]
by def. [Link] is available to all the java applications.
in order to use package, you need to use the keyword "import".
when u say "import", nothing is physically included (unlike #include of c and c++). It is only for compiler. Runtime
performance is not at all affected with "import" statements.
Class Loaders:
There are 3 types of class loaders in java
1. Bootstrap Class Loader or Primordial Class Loader
2. Extension Class Loader
3. System Class Loader
public: It is an access specifier. We should use a public keyword before the main() method so that JVM can identify
the execution point of the program. If we use private, protected, and default before the main() method, it will not be
visible to JVM.
static: You can make a method static by using the keyword static. We should call the main() method without creating
an object. Static methods are the method which invokes without creating the objects, so we do not need any object to
call the main() method.
void: In Java, every method has the return type. Void keyword acknowledges the compiler that main() method does
not return any value.
main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute a program line by line
and end the execution after completion of this method. We can also overload the main() method.
String args[]: The main() method also accepts some data from the user. It accepts a group of strings, which is called
a string array. It is used to hold the command line arguments in the form of string values.
[Link]("hello"); - SOP
c) both the methods are non-static in "PrintStream" class, so you need reference of "PrintStream" class
e) "out" is also a static member of "System" class which can be accessed as "[Link]" i.e.
[Link]("hello");
Accessibility modifiers:
Accessibility Same class Sub class in Different class Sub class in Different
modifiers same package in same different class in
package package different
package
Private Yes No No No no
<default> Yes Yes Yes No no
Protected Yes Yes Yes Yes no
Public Yes Yes Yes Yes yes
JVM Architecture:
1. Class loader sub system
Loading: loading of class
Linking:
1. Verifying: verify for security
2. Preparing: initialize static variables with default values.
3. Resolving: checked resolution if any
initializing: initializing static variables with the value given by programmer.
3. Execution Engine
Converts byte code into native code of that machine.
Interpreter
JIT compiler
Hotspot profiler: used to sort code for compilers.
gc()
Overriding
we do override to provide specific version to base class method.
Rules:
1) arguments must be same otherwise it becomes "overloading".
2) return type of overriding can be co-variant.
3) overriding method must be having same or more accessibility as compare to overridden method.
4) overriding and checked-exception rule:
a) overriding method may not declare any checked exception.
b) overriding method can declare same checked exception or its sub-type declared by overridden method.
c) overriding method cannot declare checked exception not declared by overridden method.
Binding
Resolving function call with function body is called binding.
Abstract class
When to use abstract class in java?
- while designing Parent class, if u realize that there is some functionality compulsorily required in child classes
but Parent class is not able to define it.
- This functionality is a contract or abstract function. Since abstract function cannot be declared inside non-
abstract class, u have to make class as abstract.
- abstract class cannot be instantiated. because abstract class is incomplete i.e., it has at least one contract
[abstract method]
- in java as soon as u define a class with "abstract" keyword, class becomes abstract.
- abstract class cannot be instantiated.
- abstract class can contain abstract as well as non-abstract methods.
- abstract method is a method which is declared with "abstract" keyword. (it cannot be private)
- a child class of an abstract class has to provide implementation to the method which is declared "abstract" in
parent class or else make child class also "abstract".
- a class cannot be "abstract" and "final" both.
Suppose we have,
base ref=new sub1(); // upcasting
[Link](); // late binding
Why interface?
- If we want to extend 2 classes for implementation in one class then it is not possible by using abstract class, -
we need interface.
- It contains only contract (abstract class) classes.
- By default, all methods in interface are public and abstract.
- When we implement parent class in child class then we need to give public accessibility to child methods else
we get weaker method exception.
- interfaces are abstract in nature. i.e., they cannot be instantiated.
- variable which is declared in interface is by default "public", "static" and "final".
- a class can be derived from one or more interfaces. ("implements" keyword)
- child class has to define all the methods of parent interface/s otherwise u need to make child class as
"abstract".
- one interface can be derived from one or more other interfaces. ("extends" keyword)
- if a class is derived from some other class and some interfaces, "extends" keyword should precede
"implements".
Abstract class is used when you know something and rely on others for what you don't know. (here it is partial
abstraction as some of the things you know and some you don't know.)
What is aggregation?
Aggregation is a specialize form of Association where all object has their own lifecycle but there is ownership and child
object cannot belong to another parent object. Let’s take an example of Department and teacher. A single teacher
cannot belong to multiple departments, but if we delete the department teacher object will not destroy. We can think
about “has-a” relationship.
What is composition?
Composition is again specializing form of Aggregation and we can call this as a “death” relationship. It is a strong type
of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be
deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms
there is no independent life of room and any room cannot belong to two different housespoly if we delete the house
room will automatically delete. Let’s take another example relationship between Questions and options. Single
questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will
automatically delete.
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is
derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So,
polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can
perform polymorphism in java by method overloading and method overriding.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overriding method is
resolved at runtime rather than compile-time.
In this process, an overriding method is called through the reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the reference variable.(upcasting)
example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run()
method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object
and subclass method overrides the Parent class method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
person behaves like student at college, son at home, customer in the mall.
Compile Time Polymorphism: Whenever an object is bound with their functionality at the compile-time, this is known
as the compile-time polymorphism. At compile-time, java knows which method to call by checking the method
signatures. So this is called compile-time polymorphism or static or early binding. Compile-time polymorphism is
achieved through method overloading. Method Overloading says you can have more than one function with the same
name in one class having a different prototype. Function overloading is one of the ways to achieve polymorphism but
it depends on technology that which type of polymorphism we adopt. In java, we achieve function overloading at
compile-Time.
Association
Association refers to the relationship between multiple objects. It refers to how objects are related to each other and
how they are using each other's functionality. Composition and aggregation are two types of association.
Composition
The composition is the strong type of association. An association is said to composition if an Object owns another
object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here
Human object contains the heart and heart cannot exist without Human.
Aggregation
Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently.
For example, a Team object and a Player object. The team contains multiple players but a player can exist without a
team.
Association relationship is represented Aggregation relationship is represented by a The composition relationship is represented by a
using an arrow. straight line with an empty diamond at one straight line with a black diamond at one end.
end.
In UML, it can exist between two or It is a part of the association relationship. It is a part of the aggregation relationship.
more classes.
It incorporates one-to-one, one-to- It exhibits a kind of weak relationship. It exhibits a strong type of relationship.
It can associate one more objects In an aggregation relationship, the associated In a composition relationship, the associated
together. objects exist independently within the scope of objects cannot exist independently within the
In this, objects are linked together. In this, the linked objects are independent of Here the linked objects are dependent on each
It may or may not affect the other Deleting one element in the aggregation It affects the other element if one of its associated
associated element if one element is relationship does not affect other associated element is deleted.
deleted. elements.
Example: A tutor can associate with Example: A car needs a wheel for its proper Example: If a file is placed in a folder and that is
multiple students, or one student can functioning, but it may not require the same folder is deleted. The file residing inside that folder
associate with multiple teachers. wheel. It may function with another wheel as will also get deleted at the time of folder deletion.
well.
################################################################
Favour composition over inheritance is a one of the popular object-oriented design principles, which helps to create
flexible and maintainable code in object-oriented languages.
Inheritance drawbacks:
Tight coupling- if base class (Four-wheeler) is changed, sub class (Car) will break.
Composition Advantages:
black-box reuse as it does not break encapsulation. “Car” knows only an interface “Engine”. It doesn’t know the
implementation.
Loose coupling, program to interface. During runtime any implementations (such as “HondaEngine” or
“MarutiEngine” or “BMWEngine” can be passed to “Engine ref” and “on()” method can be invoked polymorphically.
#################################################################
Here we use ref of parent and call child at runtime. And it’s a Black box reuse
Here we directly made object of parent in side child class which is tight coupling. And it’s a white box.
is used to achieve total abstraction. Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance. It is also used to achieve loose coupling.
Why we do override?
The benefit of overriding is: ability to define a behaviour that's specific to the subclass type, which means a subclass
can implement a parent class method based on its requirement. In object-oriented terms, overriding means
to override the functionality of an existing method.
Why we do upcasting?
Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class
members using this feature. This type of initialization is used to access only the members present in the parent class
and the methods which are overridden in the child class. This is because the parent class is upcasted to the child
class.
Class VS Interface
Class Interface
A class describes the attributes and behaviours of an object.
An interface contains behaviours that a class implements.
A class may contain abstract methods, concrete methods.
An interface contains only abstract methods.
Members of a class can be public, private, protected or default. All the members of the interface are public by default.
Abstract vs interface
1. An abstract class allows you to create functionality that subclasses can implement or override.
An interface only allows you to define functionality, not implement it.
2. And whereas a class can extend only one abstract class,
interface can take advantage of multiple inheritance
This method returns o/p like myclass@12135153 which is not readable. So, to make it readable we need to override it.
checks the equality of two references. If they are referring to same instance then they are equal otherwise not.
If client wants to check whether to references which are referring to the objects have the same value or not then we
need to override this method.
Return [Link]=(MyNum)[Link];
every object is given a unique number inside memory. This number is called as hashcode. This method returns the
hashcode of caller object.
When we need to show hashcodes of two object same base on content of objects then we need to override the
hashCode() method
Return num;
When we override the equals() method then we have to override hashCode() method to be in contract rules.
1. Whenever Hashcode() method is invoked on the same object more than once during an execution of a Java
application, the hash Code method must consistently return the same integer. This integer need not remain
consistent from one execution of an application to another execution of the same application.
2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result.
3. It is not required that if two objects are unequal according to the equals([Link]) method, then calling
the hashCode method on each of the two objects must produce distinct integer results. However, the
programmer should be aware that producing distinct integer results for unequal objects may improve the
performance of hashtables.
Intern();
String s2=[Link]();
If String class instance with the value "hello" inside String pool is already there then no new instance will create.
s2 directly refer to existing one instance.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined
by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to
the pool and a reference to this String object is returned.
Immutable
It means whenever we perform any action on an instance it does not affect that instance, rather it creates another
instance.
String is immutable class.
Immutable does not have setter method.
String VS StringBuffer
String is immutable
StringBuffer is mutable
String s1="hello";
s1+"hi";
a new object is not created, rather existing object gets modified. Thus, reducing memory consumption.
Conclusion:
It is always recommended to work with StringBuffer
a) it is faster
b) less memory consumption
String methods
[Link](s2);
s2=[Link](“hello”);
go for diary
[Link](s2)
IndexOf(char)
Substring(int)
LowerCase();
UpperCase();
Trim();
Replace(char1,char2);
Exception Handling
What is exception?
An exception is an event, which occurs during the execution of a program, that interrupts the normal flow of the
program's instructions.
Exception can arise from different kind of situations such as wrong data entered by user, network connection
failure etc.
Whenever any exception occurs while executing a java statement, an exception object is created and then JVM
tries to find exception handler to handle the exception. If suitable exception handler is found then the exception
object is passed to the handler code to process the exception, known as catching the exception. If no handler is
found then the application gets terminated.
All exceptions are inbuild classes. Object is a grand parent of all exception and exception class is parent of all
other exceptions.
Advantages of exceptions:
1. In traditional programming, error detection, reporting, and handling often lead to confusing code because
programmers would use error code inside the main logic. Exceptions enable you to write the main flow of your
code and to deal with the exceptional cases elsewhere.
2. A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. i.e.,
if a method does not want to handle an exception it can propagate it to the caller and so on. we did not have
this advantage in traditional programming.
3. because all exceptions thrown within a program are objects, categorizing of exceptions is a natural outcome
of the class hierarchy.
Exception
[ they can be avoided using simple [ java enforces programmer to handle these]
"if....else" , so, java does not enforce]
[Link] [Link]
[Link] [Link]
[Link] [Link]
[Link]
Unchecked exceptions: Unchecked exceptions are those exceptions which can be raised due to programming
(logical) mistakes. RuntimeException also extends from Exception. However, all of the exceptions that inherit
from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and
hence they are called unchecked exceptions.
In case of one try multiple catch, when u define one try and multiple catch, the rule is most specific catch block
should precede most generic catch block, else compiler will throw an error.
finally
{
}
We have one more block called as finally block.
on what basis you will decide whether to create checked or unchecked exception?
you create checked exception when you would like your client to take corrective action/s in case of exception. i.e.
checked exception somehow enforces client to handle it. (using try...catch) and the corrective action/s can be
taken inside catch block.
you create unchecked exception when you feel there is no need of any corrective action by client in case of
exception.
What is “handle or declare” rule?
a) whenever any method raises checked exception/s, method has to either handle [try….catch] or declare [throws]
that checked exception/s.
b) whenever u invoke a method which has declared [using throws] checked exception/s, caller method has to
either handle [try….catch] or declare [throws] that checked exception/s.
try
{
FileInputStream fis=new FileInputStream("[Link]");
// code to read the file
}
catch(FileNotFoundException e)
{
[Link]();
}
finally
{
[Link]();
}
// ARM block
//here we write try with round brackets inside which we declare object.
try(FileInputStream fis=new FileInputStream("[Link]"))
{
// code to read the file
}
catch(FileNotFoundException e)
{
[Link]();
}
when you compile above code, compiler will convert this code automatically with the finally block
compiler provide "finally" block which has "[Link]()" statement. So since compiler takes care of releasing
resource/s, It is known as "Automatic Resource Management"
Assertions
Assertions are used to test the program. The advantage is assertions are by default disable, u need to enable
them.
if u write S.o.p statements while testing the code, u need to remove or comment them while the code goes to
client.
if u write assert statements u need not do anything as assertions are by default disable.
here if boolean expression is true, remaining code will get executed. if expression is false, then AssertionError will
come.
As we know by default assertion is disabled. So, to enable the assertion we need to use command “-ea
classname”.
NoClassDefFoundError vs ClassNotFoundException
Application should not try to catch Error - Because, in most of cases recovery from an Error is almost impossible.
So, application must be allowed to terminate.
Example> VirtualMachineError, IOError, AssertionError,OutOfMemoryError, StackOverflowError.
Let’s say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able
to free up memory for rest of application to execute, so it will be better if application don’t catch these errors and is
allowed to terminate.
Wrapper classes are used to wrap primitives. in java Wrapper classes are available for each primitive.
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
char - Character
boolean- Boolean
all the wrapper classes are derived from "[Link]". They all are "final".
All wrapper classes are immutable, once initialised will not change during runtime.
}
}
solution here is to convert int to Integer (autoboxing) and pass Integer to "add" method. This is acceptable because
Integer is a child class of Object.
Enum
- enum is a user defined data type.
- it is used to define set of predefined values. It helps in making the program more readable and also helps to
reduce programming bugs.
- Every enum in java is derived from "Enum" class
- Any wrong input will not compile hence there is no javac risk of unpredictable result. Which is happen in case
of static final variables.
Overloading- considering
a) Widening (upcasting) b) Autoboxing c) Var-args
Microsoft Word
Document
Bridge methods in java.
In above example (inside word file), return type of overriding method is co-variant. We know this is overriding, compiler also
compile this but jvm doesn’t know the co-variant rule of the overriding. For jvm both methods are different. So, compiler
internally inherit the base disp method inside sub class and inside it calls the sub disp method which has co-variant return type
and control goes to that sub disp method.
Why cloning?
The clone() saves the extra processing task for creating exact same copy of an object. If we perform it by using the new keyword,
it will take a lot of processing to be performed that is why we use object cloning.
If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface
Cloneable and call clone() method to clone the object.
[Link] [Link]
Protected accessibility
Protected members are “accessible outside the package only through inheritance “.
protected member will be accessible in the subclass outside the package by calling function name directly.
protected member will not be accessible in the subclass outside the package by using parent class’s reference.
2) If the instance fields include references to mutable objects, don't allow those objects to be changed:
i.e., Don't provide methods that modify the mutable objects.
3) If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't share references to the mutable objects.
The standard argument for making immutable classes final is that if you don't do this, then subclasses can add mutability,
thereby violating the contract of the superclass. Clients of the class will assume immutability, but will be surprised when
something mutates out from under them.
Innerclass/nested class
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are called static nested classes.
Non-static nested classes are called inner classes.
classes which are defined inside any method are known as "Local Inner Classes".
here when inner class gets instantiated, compiler puts a reference of "Outer" class inside inner class object. That reference
refers to the object where "o1" refers to.
Note:
Top level classes only be public and default but nested classes can be private, public, protected, default.
Nested class are used for encapsulation. They separate aspects into outer aspects and inner aspects.
How we can access outer class members inside inner class directly?
When we create a object of inner class compiler adds 1 member secretly called noname reference and that member is nothing
but reference of outer class and it refers to that object by using which we have created inner class object. Because of this we can
call outer class members directly.
In case of inner class:
[Link] i=[Link] inner();
Here static nested class cannot access non-static instance members of outer class. It only accesses static instance member of
outer class. Because static nested class does not required object of outer class to initiate the object which is in case of inner
[Link] when inner class instantiate by that time my be outer class is not instantiated so, how can we access members of outer
class.
Anonymous class
Drawback: Anonymous class can either implements a class or extend a class both things can-not be come together
When we say,
New emp() //anonymous class which implementing class emp or interface emp.
Void disp()
{
//code
}
}
It means this class has no name and it implementing emp class / interface
Reflection API
The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java Virtual Machine. You'll want to
use the reflection API if you are writing development tools such as debuggers, class browsers, and GUI builders. With the
reflection API you can:
It means an ability to find out about classes, methods, properties etc. during runtime.
It can also mean we can instantiate classes during runtime even though we don’t know their name till runtime.
This API is used by programmers who designs IDE’s, web browsers, web servers, application servers.
reflection does not show parent class methods if parent class is in different package.
- forName() is a static method of class “Class” which is used to load a given class.
- getDeclaredMethods(); returns method list which (Method)
- getDeclaredConstructors() returns constructor list (Constructor)
- getParameterTypes(); returns all parameters of method /constructor (class arr[])
- getDeclaringClass() return class name
- getExceptionTypes() return all exceptions (class arr[])
- getReturnType() return return type of method
- getName() return method/constructor name
- getDeclaredFields() return field/variable name (Field)
- getType() return field type ex. Int, double, [Link]
- getModifiers() return modifiers (int)
[Link](mod) ; - to get readable modifier name
getDeclaredMethod("disp1",null);
invoke(class reference,null)
setAccessible(true);
getDeclaredField("num1");
[Link](true);
[Link](class reference, value to be set);
To give security for no to access private members outside the class even using reflection API
Use constructor
Sample ()
{
[Link](new SecurityManager ());
}
Multithreading
- Thread class and Runnable interface have connection between them. Thread class implements Runnable interface.
- In multithreading thread Scheduler always call run method of Runnable interface in case of implements Runnable.
process-based multitasking: - more than one processes are running simultaneously. e.g. word and excel applications are
running simultaneously.
thread-based multitasking: - more than one threads are running simultaneously. e.g. within a word application, you can start
formatting as well as printing.
whether process-based or thread-based, a CPU can handle only one task at a time, unless it is multiprocessor machine. It is just
an impression given to the user. what actually CPU does is context switching, i.e., jump from one task to another and vice-versa.
process-based vs thread-based
Application of multi-threading in java: - due to multithreading feature, java has become effective on server side. e.g. Servlet, JSP
etc.
Thread-Schedular
a) pre-emptive
b) time-slice.
Java has given certain mechanisms (functions) whereby u can make sure, Ur multi-threading application can run more or less
same on any os.
a) [Link]
b) [Link] (interface)
c) [Link]
Thread class:- this is the most imp. class required in order to create multi-threading application.
Following are its methods.
a) start
is used to register thread with jvm schedular
b) run
is used by the programmer to define thread execution body, but will be called by jvm schedular whenever it executes a
particular thread.
when the run method is over, thread is dead.
c) sleep (static)
is used to make thread sleep for some time
d) setName
to set the name of thread
e) getName
to get the name of thread
f) currentThread
returns the currently running thread
g) setPriority
to set the priority
in java priorities are numbers from 1 to 10
1 - minimum priority
5 - normal priority
10 - maximum priority
h) getPriority
to get the priority
i) join
join() method is used for waiting the thread in execution until the thread on which join is called is not completed.
void run();
e.g.
extends Thread
when main function is over, main thread dies, but user defined thread/s can continue. They will be taken care by JVM.
i.e. in the above code, after "[Link]()" when main() function is over, main thread dies , but t1's execution will be managed by
JVM.
we can call run() directly. But in that case it won't be thread execution , it is a normal method call. That is different call stacks
won't be created.
2. by extending Thread, each of your threads has a unique object associated with it, whereas implementing
Runnable, many threads can share the same object instance.
what is the use of implements Runnable?
if your class is already extending some class, you can't say extends Thread, because multiple inheritance is not allowed
in java. In that case you have to go for implements Runnable.
above program also proves that threads can share the memory.
e.g.
Synchronized Block
synchronized keyword
method :- all the statements are protected.
block :- only those statements are protected which are given inside synchronized block.
in java every object has a lock. This lock can be accessed by only one thread at a time. The lock will be released as soon as the
thread completes its job and thus another thread can acquire the lock.
This lock comes into picture only when object has got non-static synchronized method/s or block. whichever thread executes
the synchronized method first, it acquires the lock. Other thread/s have to be in "seeking lock state".
once a thread acquires a lock on an object, it can have control on all the non-static synchronized methods of that object.
Synchronized is used only and only when threads share the same object. Because synchronise will provide the lock on object
and that lock will not give permission to interrupt any other thread to work on same object while already 1 st thread is working
on that. So synchronized is related to single object only to avoid race condition.
In Following code, threads are sharing different objects so synchronise has no use in this. Race condition will not occur.
Even though synchronized method or block is used to avoid "Race Condition", there can be danger of "DeadLock" inside it.
e.g. if one thread is working inside synchronized block or method and if it gets stuck up ! imagine what will happen ?
neither this thread can complete and release the lock, nor other thread can acquire the lock.
a) wait
it will make thread, release the lock and go to wait pool.
Wait will execute when thread stuck or blocked, then this thread executes wait on himself to come out from lock.
b) notify
it will make the thread to move from wait pool to seeking lock state.
c) notifyAll
it will make all the threads to move from wait pool to seeking lock state.
In wait pool there are only those threads who called on himself wait
These methods are defined in "[Link]" class and are final so u cannot override them.
Thread-safety
Thread-safe classes are those classes, which contain synchronized non-static methods.
We use class lock when we want synchronization between two objects and both objects have independent threads only in case
class have static synchronise methods.
They share one instance of class class.
every class has a lock. It is actually a lock on an instance of class Class. This is because , whenever any class is loaded in java, it is
represented by instance of class Class.
The class lock comes into picture in case of synchronized static methods.
Thread which gives a call to synchronized static method can acquire a class lock. Only after thread complete that static method,
lock is released.
in the above code "Both the threads are over" will not be displayed in the end because it is a statement of main. It is because as
we know , main thread completes first and user defined thread are continue, they are taken care by JVM.
if we want that "Both the threads are over" should be displayed at the end, we have to make sure that main thread will
complete only after the completion of "t1" and "t2".
join() method
join method makes caller thread (main thread) to wait for called thread (t1 and t2) to complete.
in the above code, when main() function calls "[Link]()" for example, it says "join me at your end".
Since main() is calling "[Link]()" and "[Link]()" , it is added to the end of both t1 and t2. That's why now the statement "Both the
threads are over" is getting executed at the end.
whenever thread is in a blocked state [Link] to sleep, join or wait methods, it can get interrupted by other threads. Whenever
blocked thread gets interrupted, it throws "InterruptedException".
But this can not be predictable, hence we have to be ready with "try... catch(InterruptedException)"
Thread states
User threads
user defined threads
main thread
Daemon thread
e.g. garbage collection thread (low priority thread)
Daemon threads are the threads which are at the mercy (servant) of user thread/s. Their only purpose is to serve user defined
thread/s. When there is no user thread alive, Daemon thread will die.
package core1;
//[Link]().gc();
[Link]("Done");
output:
Done
inside finalized method
Thread[Finalizer,8,system]
Difference between
in above case, we have all 10 statements are blocked for a particular thread. i.e. unless a particular thread executes all 10
staements , second thread will not execute. It should be avoided if all 10 statements are not critical.
above code will give u performance advantage as compare to previous code because only first 4 statements are blocked. once a
thread completes first 4 statements , other thread can execute.
In case of Class lock, When u say [Link]() [Link]() or [Link]() what does it mean ?
It means that,
wait(), notify() and notifyAll() are in Object class and they are final , so they cannot be overridden.
Class class is a child of Object class.
When we say [Link](),[Link]() or [Link]() it means that these methods are inherited in Class class which we are invoking.
1) The first and most important difference between extending Thread and implementing Runnable comes from the fact that a
class can only extend one class in Java. So, if you extend the Thread class then your class lose that option and it cannot extend
another class, but if you implement Runnable then your class can still extend another class e.g. Applet. It's a common pattern in
Java GUI programming that your class extends Applet and implements Runnable, EventListener etc.
2) The second difference between extends Thread and implements Runnable is that using the Runnable instance to encapsulate
the code which should run in parallel provides better reusability. You can pass that Runnable to any other thread or thread pool.
[ Reusability ]
3) when you implement Runnable, [ Thread creation and Thread Execution body can be loosely coupled ] but if you extend
Thread then they are tightly coupled.
4) Another difference between Thread and Runnable comes from the fact that you are extending Thread class just
for run() method but you will get overhead of all other methods which come from Thread class. So, if your goal is to just write
some code in run() method for parallel execution then use Runnable instead of extending Thread class.
5) The fifth difference between extending Thread and implementing Runnable also comes from OOP perspective. In Object
oriented programming you extend a class to enhance it, to put some new features on it. if you just want to execute thread/s and
get the work done, then stick with implementing the Runnable interface rather than extending Thread class.
Conclusion: -
When to use "extends Thread" over "implements Runnable"
The only time it makes sense to use "extends Thread” is when you have a more specialized version of Thread class. In other
words, because you have more specialized thread specific behaviour.
But practically we just would like to get the work done by thread/s so in that case you need to use "implements Runnable"
which also leaves your class free to extend some other class.
Class lock vs object block
when u want to ensure that non-static method/s should be called by only one thread at a time, u apply lock on an
object which is shared by more than one threads. The technique to apply "object lock" is to have synchronized non-static
method/s or block/s.
What if u want to ensure that static method/s should be called by only one thread at a time?
here object lock will not help at all because static methods are not at all associated with the object. Hence u need to
apply "class lock" i.e. lock on an instance of class "Class". The technique to apply "class lock" is to have synchronized static
method/s or block/s .
What is ThreadPool in Java?
A thread pool contains previously created threads to execute a given task. These threads are initially idle. Once any task comes a
randomly selected thread from thread pool will be made active and asked to perform the task. Once the task is over the thread
is not destroyed but simply sent back to the pool for reuse.
Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the
application more responsive
Since active threads consume system resources, a JVM creating too many threads at the same time can cause the system to run
out of memory. This necessitates the need to limit the number of threads being created.
ExecutorService exec=[Link]();
It creats a threads which will store inside threadpool which will be in ideal state
Where ExecutorService is a interface and Executors is a class
ExecutorService exec=[Link](2);
It creates fixed number of threads
[Link](new myapp());
gives a task to jvm
[Link]();
If u write this then after u won’t give any task to jvm
shutdown() prevents new tasks from being submitted to that Executor. The current thread ( e.g. main thread ) will continue to
run all tasks submitted before shutdown() was called.
Reentrant
Condiations
import [Link].*;
ReentrantLock mylock=new ReentrantLock();
Condition value=[Link]();
[Link]();
[Link]();
Imp note:- call to “signalAll()” does not immediately activate a waiting thread. It only unblocks the waiting threads so that they
can compete for entry into the object after the current thread has exited the “synchronized” method.
“signal()” method unblocks only a single thread from the wait state, chosen at random.
Imp note:- a thread can only call “await()”,”signal()” and “signalAll()” on a “Condition” object when it owns lock of the condition.
ReentrantLock is mutual exclusive lock, similar to implicit locking provided by synchronized keyword in Java, with extended
feature like fairness, which can be used to provide lock to longest waiting thread. Lock is acquired by lock() method and held
by Thread until a call to unlock() method. Fairness parameter is provided while creating instance of ReentrantLock in
constructor. ReentrantLock provides same visibility and ordering guarantee, provided by implicitly locking, which
means, unlock() happens before another thread get lock().
2) extended feature like fairness, which can be used to provide lock to longest waiting thread.
3) ability to trying for lock with or without timeout. Thread doesn’t need to block infinitely, which was the case with implicit
synchronization.
Though ReentrantLock provides same visibility and orderings guaranteed as implicit lock, acquired by synchronized keyword in
Java, it provides more functionality and differ in certain aspect. main difference between synchronized and ReentrantLock is
ability to trying for lock with or without timeout. Thread doesn’t need to block infinitely, which was the case with synchronized.
Let’s see few more differences between synchronized and Lock in Java.
1) Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't
support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can
make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides
lock to longest waiting thread, in case of conflict.
2) Second difference between synchronized and Reentrant lock is tryLock() method. ReentrantLock provides
convenient tryLock() method, which acquires lock only if its available or not held by any other thread. This reduce blocking of
thread waiting for lock in Java application.
Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.
3) ReentrantLock also provides convenient method to get List of all threads waiting for lock.
In short, Lock interface adds lot of power and flexibility and allows some control over lock acquisition process, which can be
influenced to write highly scalable systems in Java.
Major drawback of using ReentrantLock in Java is , wrapping method body inside try-finally block, which makes code unreadable
and error-prone. Another disadvantage is that, now programmer is responsible for acquiring and releasing lock, which is a power
but also opens gate for new subtle bugs, when programmer forget to release the lock in finally block.
Things to remember:
boolean tryLock()
tries to acquire the lock without blocking, returns true if it was successful.
Note:
Case : synchronise
in case of synchronise execution of thread if any exception is raised then lock will automatically release and second thread get
the chance to run.
#####################################################################################################
FILE HANDLING
#####################################################################################################
stream
if u want to read, u need to open input stream on the source ( e.g. file, array, network )
if u want to write ,u need to open output stream on destination ( e.g. file, array, network )
Java has two categories of streams
byte streams :- for reading and writing bytes , image or sound files also. It is also used to read and write java Objects.
unicode character streams :- for reading and writing unicode characters.
Hierarchy of stream
byte streams
FileInputStream FileOutputStream
FileReader FileWriter
[Link]();
[Link]();
[Link]();
[Link]()?"Exists":"Doesn't Exists";
[Link]()?"Can Write":"Can Not Write";
[Link]()?"Can Read":"Can Not Read";
[Link]()?"It is Directory":"It is not Directory";
[Link]()?"Yes File":"No File";
[Link]()?"is Absolute":"It is Not Absolute";
new Date([Link]());
[Link]();
RandomAccessFile
A random-access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the
implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the
bytes read.
RandomAccessFile rf=new RandomAccessFile("path","rw");
[Link]([Link]());
//method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
[Link](0);
[Link](10);
[Link]('A');
[Link](3.9f);
[Link](true);
[Link]("hello world");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]())
object persistence
it means saving the state of an object inside either filesystem or database so that it can be retrieved back in future.
When we save the state of an object inside filesystem, it is known as "Serialization".
When we read the state of an object from filesystem, it is known as "Deserialization".
in java there are two rules for Serialization:
a) a class has to implement either Serializable or Externalizable interface.
b) class must have all the instance members of type serialized. (Serialized type means which can be easily converted into
sequence of bytes).
Object Graph
when we implement Serializable, entire object graph is saved inside file.
What are the things get written when u serialize an object using Serializable?
- it writes out the metadata (description) of the class associated with an instance such as length of the class, the name of
the class, serialVersionUID (or serial version), the number of fields in this class.
- Then it recursively writes out the metadata of the superclass until it finds [Link].
- Once it finishes writing the metadata information, it then starts with the actual data associated with the instance. But
this time, it starts from the top most superclass.
- Finally it writes the data of objects associated with the instance starting from metadata to actual content recursively.
(has-a relationship objects)
[Link](s)
when u call "writeObject" , it will check whether "s" implements "Serializable" or "Externalizable"
if it implements "Serializable" it will check whether u have defined "private writeObject
if yes
it will invoke it
if no
it will go for def. serialization
[Link]()
when u call "readObject",it will check whether class has implement "Serializable" or "Externalizable"
if it implements "Serializable" it will check whether u have defined "private readObject"
if it implements "Externalizable"
invoke default constructor
invoke "readExternal()" method
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
Externalization
- Here we have control on serialization. Like in case of serialization we have a control on has-a but don’t have control on
is-a relationship.
- In this case while deserialization default constructor gets called back-to-back and then read external method gets
called.
- Class should have default constructor else externalization will fail. It will serialise but at the time of deserialize it will fail
and give InvalidClassException
- Both the methods are public. And need to define compulsory.
- externalization is fast than serialization.
In case of Externalizable when we deserialized object:
- 1) A new object gets created in heap area.
- 2) Instance members are allocated memory.
- 3) Default constructor gets invoked.
- 4) readExternal() method gets invoked which initializes instance members with the help of file info.
why in case of Serializable "default constructor" does not get called during deserialization?
Because if here default constructor gets called then we will get default values and not those values which were there when we
stored that object inside filesystem.
What is serialVersionUID ?
As per java docs, during serialization, runtime associates with each serializable class a version number, called a serialVersionUID,
which is used during de-serialization to verify that the sender and receiver of a serialized object have loaded classes for that
object that are compatible with respect to serialization.
Simply put, the serialVersionUID is a unique identifier for Serializable classes. This is used during the deserialization of an object,
to ensure that a loaded class is compatible with the serialized object. If no matching class is found, an InvalidClassException is
thrown.
Since the default serialVersionUID computation differs on different JVM implementations, it is highly recommended for a class
which implements Serializable or Externalizable interfaces to declare serialversionuid explicitly in order to ensure successful
deserialization across all the platforms.
Ex.
<any access modifier> static final long serialVersionUID = 42L;
Addition of new fields or classes does not affect serialization you cannot change the default signatures for readObject()
and writeObject()
We can change field access modifiers like private, public, We can not change a class which implement serializable to
protected or default implement externalizable and vice versa
Addition of new methods we also cannot change the field types within a class
we can change a transient or static field to a non-transient or You cannot alter the position of the class in the class
non-static field hierarchy
we can change the access modifiers for constructors and You cannot change the name of the class or the package it
methods of the class belongs to, as that information is written to the stream
during serialization.
############################################################################################
Generics
[Link](new Integer(100));
[Link]("hello");
[Link](new Double(3.4));
now compiler will see to it that mylist will be used with String only or else it will give error which is much better than
ClassCastException.
e.g.
[Link]("hello");
[Link]("welcome");
[Link](100); // compilation error
Type Eraser
public class Generic1<T>
{
private T first;
void setVal(T first)
{
[Link]=first;
}
T getVal()
{
return first;
}
when u compile above class, compiler will remove all the generic information because JVM can't understand Generics. This is
known as "Type Erasure". So after compilation the above class will be as follows:
Hierarchy:
Iterable: The Java Iterable interface represents a collection of objects which is iterable - meaning which can be iterated.
Collection: Enables you to work with groups of objects. It is at the top of the collection’s hierarchy. It is the foundation upon
which the collections framework is built.
List: Duplicates allowed. Cares about index. Has methods related to index. All 3 List implementation are ordered by index
position.
ArrayList: Fast insertion and fast random access. Ordered collection (by index), but not sorted. Choose this over LinkedList, when
you need fast iteration but are not likely to be doing a lot of insertion and deletion.
Vector: Similar to ArrayList but with two differences. Vector is synchronized (hence there is always a performance hit as
compare to ArrayList) and it contains many legacy methods that are not part of the collections framework.
Extends AbstractList and implements List.
ArrayList Vector
2) ArrayList increments 50% of current array size if the Vector increments 100% means doubles the array size if the total number of elements exceeds than its
number of elements exceeds from its capacity. capacity.
3) ArrayList is not a legacy class. It is introduced in JDK 1.2. Vector is a legacy class.
4) ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads
in runnable or non-runnable state until current thread releases the lock of the object.
5) ArrayList uses the Iterator interface to traverse the A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
elements.
LinkedList: It is like ArrayList except elements are doubly-linked to each other. Even though iterates slowly as compare to
ArrayList, insertions and deletions in a doubly-linked list are very efficient. I.e., elements are not shifted, as in case for an array.
when frequent insertions and deletions occur inside a list, a LinkedList can be worth considering.
Stack: Subclass of Vector that implements a standard last in first out stack.
CopyOnWriteArrayList: Creates a copy of original ArrayList when you open an iterator on it. So that any updates can happen on
original list while traversing is going on the copy.
Hashcode() method: HashSet or LinkedHashSet, the objects you add to them must override hashcode() , otherwise Object’s
hashcode() method will allow multiple object that u might consider “meaningfully equal” to be added to your “no duplicates
allowed set”.
TreeSet: Sorted, ascending order, optionally you can set the order using Comparator interface.
Map Interface: Maps unique keys to values. after the value is stored, you can retrieve it by using its [Link] is not allowed.
Although keys are typically String names, a key can be any object. [Link] [Link] is an inner interface of [Link] describes an
element (a key/value pair) in a map.
HashMap: Does not guarantee the order of its elements .Therefore ,the order in which elements are added to a hash map is not
necessarily the order in which they are read by an iterator.
Elements are stored as key,value pair.
Compare to this, other maps add a little more overhead. It is the quickest map.
Searching in a HashSet or HashMap can be faster than in a TreeSet or TreeMap, as hashing algorithms usually offer better
performance than the search algorithms for balanced trees.
Hashtable: Implements Map. Similar to HashMap but it is synchronized. Stores key/value pair.
TreeMap: Sorted map, that is keys are stored in sorted order. Natural order like TreeSet. Custom sort possible using
Comparable.
Concurrent HashMap:
Difference Iterator vs ListIterator:
Iterator is an interface use for traversal through List, Set and Map
ListIterator is a child of Iterator, which has two features
1) it allows modification
2) it allows bidirectional traversal
Fail-Fast Iterator
in case of ArrayList while u r traversing through the list using iterator if u try to
add inside the list, u get "ConcurrentModificationException". It means iterator of
ArrayList is "Fail-Fast".
Fail-Safe Iterator
in case of CopyOnWriteArrayList when u create an iterator, it creates a snapshot of original list so that u can traverse it. If u try
to add inside the list, element gets added inside original list. It means iterator of
CopyOnWriteArrayList is "Fail-Safe".
subsequent entries
hashcode - different - different bucket
hashcode
bucket is determined for search
== true - get the value
false
equals - true - get the value
false - linked list will be traverse and subsequently == and equals are invoked.
Hashtable vs Hashmap
HashMap Hashtable
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null
key or value.
5) We can make the HashMap as synchronized by calling this Hashtable is internally synchronized
code and can't be unsynchronized.
Map m = [Link](hashMap);
Concurrent HashMap
It’s a combination of HashTable and HashMap. It has bucket lock. It’s a thread safe and can be shared with multiple threads. This
lock’s are on write only, not for read.
TreeMap
Note: collections always stores an references and while serialization copy of collection and copy object both the save in file.
Collections
Is a class which has set of algorithms in the form of static methods.
##################################################################################################
DAY 13
##################################################################################################
A default method is a method declared and defined in an interface whose method header begins with the default keyword.
Every class that implements the interface inherits the interface's default methods and can override them.
child class of an interface has to provide implementation of the method/s which are declared abstract in parent or else child
class also has to be declared as "abstract".
default method/s may or may not be overridden by child class. (If overridden, "public" modifier is compulsory)
static methods are like utility methods which can be invoked only on the interface in which they are defined.
Functional Interface: An interface with exactly one abstract method is called Functional Interface. It may have static and default
methods. "functional interface" was known as "SAM (Single Abstract Method interface" before Java8.
Note: if we have an abstract class with just one abstract method, lambda does not work. Lambda works only with Functional
Interface
##################################################################################################
DAY 14
##################################################################################################
Stream in Java
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports
various methods which can be pipelined to produce the desired result.
The features of Java stream are –
- A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
- Streams don’t change the original data structure; they only provide the result as per the pipelined methods.
- Each intermediate operation returns a stream as a result, hence various intermediate operations can be pipelined.
- Terminal operations mark the end of the stream and return the result.
- We can use Stream API to implement internal iteration
- Internal iteration provides several features such as sequential and parallel execution, filtering based on the given
criteria, mapping etc
[Link](i, "val" + i); // it prevents us from writing additional and if null checks then write the value (default method
inside map)
[Link]((id, val) -> [Link](val)); // forEach accepts a consumer to perform operations for each value of the
map.
[Link](3, (num, val) -> val + num); //concatenation where num is key & val is value
[Link](23, num -> "val" + num); //if key is not there then it will be created with value as given lambda expres.
[Link](3, null);
[Link]([Link](42, "not found")); // if key is there inside then return the value and if it is not there then
[Link]([Link](4, "not found")); // it will return not found
[Link]([Link](9, "concat", (value, newValue) -> [Link](newValue))); // merge old value with new value
// if key is not there then new entry is put with new given value
#######################################################################################################
DAY 12 - Socket
#######################################################################################################
import [Link].*;
1. UDP Client-Server
2. TCP Client-Server
3. Object passing over network
Layers of Network:
1. Application Layer – HTTP, FTP, SMTP, JRMP (Java Remote Method Protocol), IIOP (Internet Inter-ORB protocol)
2. Transport Layer (UDP, TCP) – how communication happens
3. Internet Layer (IP) – how data should go from 1 end to another end.
4. Physical Layer – wires, cables
Note: In java when u write socket program you have to use port no.
Total range of port no.: 1 to 65535
out of that,
1 to 1023 = system applications.
1024 to 65535 = java application.
#######################################################################################################
NIO Buffers
Buffers are a cornerstone upon which the NIO operations are built. Basically, all operations that involve NIO use buffers as a
staging area for transferring data in and out from the data source to/from target. In the NIO library, data travels into buffers and
out of buffers on a regular basis. Anytime you write data, you are writing data into a buffer and when you read data you are
reading from a buffer.
NIO Channels
Channels are similar to Streams in traditional Java I/O API with the exceptions that they can provide three modes: input, output
or bi-directional.
Streams on the other hand, are uni-directional (you were either using InputStream or OutputStream).
Channels interact directly with buffers and the native IO source, that is, file, or socket.
Channels Working:
for reading purpose:
1. channel writes data into buffer
2. program reads from buffer.
}); // due to completion handler if I/O operation completes successfully then completed method is called else failed
method is called.
Optional Class