Java Notes
Java Notes
===================================================================================
========================
Why we use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
Java isolates itself from other programming languages because of functionality and
security and it is relevant too.
Open source
More source
Platform independent
Portable
Multi-Threading
-----------------------------------------------------------------------------------
------------------------------------------
Cross-Platform/Platform Independent:
------------------------------------
Cross-platform means,a compiled Java program can be run on all
the platforms.
Remember that the system must have JVM. After compiling a Java program, the Java
code gets converted
into the bytecode which is platform-independent.This bytecode is understood by the
JVM.
We can run this bytecode on any platform.
-----------------------------------------------------------------------------------
-----------------------------------------
Memory-Management:
-------------------
Java provides its own mechanism for managing the memory isknown as
garbage collection.
We need not to care about memory and do not required to implement it to manage the
memory.It automatically
deletes the objects when they no longer used by the application. It improves the
speed of the application.
-----------------------------------------------------------------------------------
------------------------------------------
Multi-threading:
-----------------
Thread is a light-weight subprocess.Multi-threading in Java allows
concurrent execution of
two or more threads simultaneously. It maximizes the utilization of the CPU.
===================================================================================
=================================================
Java Architecture:
-------------------
Java Architecture is a collection of components, i.e., JVM, JRE, and
JDK. It integrates the process of
interpretation and compilation. It defines all the processes involved in creating a
Java program.
Java Architecture explains each and every step of how a program is compiled and
executed.
After that, the JVM converts the byte code into machine code.
The following figure represents the Java Architecture in which each step is
elaborate graphically.
Java Architecture:
-------------------
Now let's dive deep to get more knowledge about Java Architecture. As
we know that the Java architecture
is a collection of components, so we will discuss each and every component into
detail.
The feature states that we can write our code once and use it anywhere or on
any operating system. Our Java program can run any of the platforms only
because
of the Java Virtual Machine. It is a Java platform component that gives us an
environment to execute java programs. JVM's main task is to convert byte code
into machine code.
JVM, first of all, loads the code into memory and verifies it. After that, it
executes the code
and provides a runtime environment. Java Virtual Machine (JVM)
has its own architecture, which is given below:
JVM Architecture:
-------------------
JVM is an abstract machine that provides the environment in which Java
bytecode is executed.
-----------------------------------------------------------------------------------
-------------------------------------
ClassLoader: ClassLoader is a subsystem used to load class files.
ClassLoader first loads the Java code whenever we run it.
-----------------------------------------------------------------------------------
-----------------------------------
Class Method Area: In the memory, there is an area where the class data is stored
during the code's execution.
Class method area holds the information of static variables,
static methods, static blocks,
and instance methods.
-----------------------------------------------------------------------------------
---------------------------
Heap: The heap area is a part of the JVM memory and is created when the JVM starts
up. Its size cannot be static
because it increase or decrease during the application runs.
-----------------------------------------------------------------------------------
----------------------------
Stack: It is also referred to as thread stack. It is created for a single execution
thread. The thread uses this
area to store the elements like the partial result, local variable, data used
for calling method and returns etc.
-----------------------------------------------------------------------------------
-----------------------------
Native Stack: It contains the information of all the native methods used in our
application.
-----------------------------------------------------------------------------------
----------------------------
Execution Engine: It is the central part of the JVM. Its main task is to execute
the byte code and execute the Java classes.
The execution engine has three main components used for executing
Java classes.
-----------------------------------------------------------------------------------
-----------------------------
Interpreter: It converts the byte code into native code and executes. It
sequentially executes the code.
The interpreter interprets continuously and even the same method
multiple times.
This reduces the performance of the system, and to solve this, the JIT
compiler is introduced.
-----------------------------------------------------------------------------------
-------------------------------
JIT Compiler: JIT compiler is introduced to remove the drawback of the interpreter.
It increases the speed of execution and improves performance.
-----------------------------------------------------------------------------------
--------------------------------
Garbage Collector: The garbage collector is used to manage the memory, and it is a
program written in Java.
----------------- t works in two phases, i.e., Mark and Sweep. Mark is an area
where the garbage collector
identifies the used and unused chunks of memory. The Sweep
removes the identified object
from the Mark
-----------------------------------------------------------------------------------
-------------------------------
Java Native Interface
---------------------
Java Native Interface works as a mediator between Java method calls and native
libraries.
-----------------------------------------------------------------------------------
-------------------------------
Java Runtime Environment:
------------------------
It provides an environment in which Java programs are executed. JRE takes our Java
code, integrates it with
the required libraries, and then starts the JVM to execute it.
.
-----------------------------------------------------------------------------------
---------------------------------
Java Development Kit:
---------------------
It is a software development environment used in the development of Java
applications and applets.
Java Development Kit holds JRE, a compiler, an interpreter or loader, and several
development tools in it.
.==================================================================================
===================================
.NetBeans
.InteeliJ
.Eclipse
.Notepad etc....
===================================================================================
====================================
Why EClipse?
===================================================================================
===================================
Why Use Naming Conventions?
Different Java programmers can have different styles and approaches to the way they
program.
By using standard Java naming conventions they make their code easier to read for
themselves
and for other programmers. Readability of Java code is important because it means
less time
is spent trying to figure out what the code does, leaving more time to fix or
modify it.
===================================================================================
=======================================
Types of Brackets:
------------------
The main() is the starting/Entry point for JVM to start execution of a Java
program. Without the main() method,
JVM will not execute the program.
The program will compile, but not run, because JVM will not recognize the main()
method.Remember JVM always
looks for the main() method with a string type array as a parameter.
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.
-----------------------------------------------------------------------------------
--------------------------------------------------
main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it
can store a group of string.
Remember, this array can also store a group of numbers but in the form of string
only. Values passed to the
main() method is called arguments. These arguments are stored into args[] array, so
the name args[] is generally used for it.
===================================================================================
=======================================
Method or FUnction?
-------------------
Method Declaration:
-------------------
The method declaration provides information about method attributes, such as
visibility, return-type, name, and
arguments. It has six components that are known as method header.
Method Signature:
-----------------
Every method has a method signature. It is a part of the method
declaration.It includes the
method name and parameter list.
1)Predefined Method
2)User-defined Method
Predefined Method:
------------------
In Java, predefined methods are the method that is already defined in
the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods
just by calling them in the program at any point. Some pre-defined methods are
length(), equals(), compareTo(), sqrt(), etc.
When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the
background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method
is defined in the java.io.PrintStream class.
It prints the statement that we write inside the method. For example,
print("Java"), it prints Java on the console.
User-defined Method:
--------------------
The method written by the user or programmer is known as a user-defined
method. These methods are modified according
to the requirement.
Parameterized methods:
--------------------
These methods contain a parameter list or an argument list which
receives a value from the calling method.
Formal Parameter:
-----------------
Formal parameter is the one that is present in the function
definition.
This parameter receives the arguments that are passed to the method.
For example:
public int sum(int a, int b) { //this is the formal parameter
//body
}
---------------------------------------------------------------------------
Actual Parameter:
-----------------
Actual parameter is the one that is present in the function call
statement.
This parameter sends the arguments that are passed to the method.
For example:
ob.sum(num1, num2); //this is the actual parameter
Note: Argument refers to the value that is being passed by the calling method to
the called method.
-----------------------------------------------------------------------------------
----------------
Non-Parameterized methods:
-------------------------
These methods do not have any parameter-list. The programmer can simply
call the function without sending
any values to the function.
===================================================================================
==============================================
Data ytpes:
-----------
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
-----------------------------------------------------------------------------------
-------------------
Non-primitive data types:
-------------------------
The non-primitive data types include String,Arrays,Classes,Objects and
Interfaces.
String - stores text, such as "Hello". String values are surrounded by double
quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
Object:
-------
An object is an instance of a class,Memory for an Object creates at runtime.
Syntax:
-------
classname objectreferance=new classname();
() - Constructor
-----------------------------------------------------
Constructor:
------------
It is a special method.
It is used to Initialize an object.
===================================================================================
============================================
There are two types of packages:
---------------------------------
Built-in-package:
-----------------
These are the packages that are predefined in the java jar file.The
most commonly used
package in java. util and java.io package in java.
User-defined package:
---------------------
These packages are created by the user that used to store related
classes some other
utility functions, interfaces and abstract classes, etc which are defined for the
specific task is
called a user-defined package.
-----------------------------------------------------------------------------------
---
Same Package:
-------------
Java Program to Create a Package to Access the Member of External Class and
Same Package
by creating object refence for the reuired class.
Different Package:
-----------------
Java Program to Create a Package to Access the Member of External Class and
different Package
by creating object refence for the reuired class.
we need to import packages for different package.
===================================================================================
===============================================
Method with ReturnType:
-----------------------
Parameterized method with return outcome of this method execution/result will
used as input to
someother place wherever reuired.
These return types required a return statement at the end of the method. A
return keyword is used
for returning the resulted value.
The void return type doesn't require any return statement.If we try to return
a value from a void method,
the compiler shows an error.
===================================================================================
=============================================
Modifiers:
----------
Access Specifiers:
------------------
1)Public:
---------
The method is accessible by all classes when we use public specifier in our
application.
public keyword can Use at Atribute,Method and Class level.
Scope/Visibility will be throughout the project level.
-----------------------------------------------------------------------------------
----------------------------------------
2)Private:
----------
When we use a private access specifier, the method is accessible only in the
classes in
which it is defined.
Private keyword can Use at Atribute,Method level.
Scope/Visibility restricted only to the current class level.
-----------------------------------------------------------------------------------
----------------------------------------
3)Protected:
------------
When we use protected access specifier, the method is accessible within the
same package
or subclasses in a different package.
Protected keyword can Use at Atribute,Method level.
Scope/Visibility to package level by using extends inherit happens in
different package-
protected member will be acuired.
-----------------------------------------------------------------------------------
----------------------------------------
4)Default:
----------
When we do not use any access specifier in the method declaration, Java uses
default access
specifier by default.
Default keyword can Use at Atribute,Method and Class level.
It is visible or scope only from the same package only.
Non-Access Modifiers:
----------------------
5)Static:
---------
The static keyword in Java is used for memory management mainly.
We can apply static keyword with variables, methods, blocks and nested
classes.
The static keyword belongs to the class than an instance of the class
No need to create Object reference to call.
we can call directly static members.
6)Final:
--------
We can apply final keyword with variables, methods and classes.
If Class declared as final -can't able to inherit the class.
If members declared as final can't able to change the value.
If method declared as final can't able to override the method.
===================================================================================
=================================================
Types of Variables:
-------------------
1)Local Variable:
Declared inside a method - must be initialized.
2)Instance Variable:
Declared inside main method - must be initialized.
3)Global Variable:
Declared outside a method but inside the class,initalization is not
mandate,if not takes default vale.
==> Instance Variable & Global variable are called as global variable in real
time.
===================================================================================
=================================================
Scanner Class:
--------------
===================================================================================
=================================================
OOPS:
------
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
-----------------------------------------------------------------------------------
-------------------------------------------------------
Inheritance:
-------------
.Inheritance is one of the OOPS Concept.
.Acuiring the properties of one class to another by using the extends
keyword.
.Code reuse(Avoid code redundancy).
.Reduce the memory wastage.
.The extends keyword indicates that you are making a new class that derives
from an existing class.
.The meaning of "extends" is to increase the functionality.
.A class which is inherited is called a parent or superclass, and the new
class is called child or subclass.
Single Inheritance:
-------------------
When a single Child class inherits another single Parent class, it is known
as a single inheritance.
Multi-Level Inheritance:
------------------------
When there is a chain of inheritance Tree like structure GrandParent class to
Parent class,Parent class
to Childclass, it is known as multilevel inheritance.
Hirerarchical Inheritance:
--------------------------
When more one child classes inherits a single Child class, it is known as
hierarchical inheritance.
Multiple Inheritance:
---------------------
When one child class inherits multiple Parent classes, it is known as
multiple inheritance
Hybrid Inheritance:
-------------------
Combination of single inheritance & multilevel inheritance.
===================================================================================
=================================================
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.
* Method Overload:
-------------------
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
.Same Class.
.Same Method name.
.Different Arguments
1.No of Args.
2.Se of Args.
3.Datatype of Args.
-----------------------------------------------------------------------------------
---------------------------------------------------------------
*Method Override:
------------------
.Same Method name.
.Same Arguments.
.Different class
.Override the same method with simple modify in business logic.
.@Override is an in build Annotation.
===================================================================================
===========================================================
Abstraction:
------------
Data abstraction is the process of hiding Sensitive information and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
----------------
Abstract method: can only be used in an abstract class, and it does not have a
body(Implementation).
---------------- The body is provided by the subclass (inherited from).
Abstract:
---------
An abstract class can have both abstract and Non-Abstract(Regular) methods.
Method only have declaration not the implementation.
Interface:
-----------
To achieve Interface Abstraction:
----------------------------------
Interface can have only Abstract method.
Interface Supports Multiple Inheritance.
Interface keyword is used to declare Interface
Interface can be implemented using "Implements" keyword.
Abstract class and Interface both cant be instantiated.
no need Abstract or any keywords,default is consider as interface.
===================================================================================
=========================================================
Encapsulation:
--------------
Benefits of Encapsulation:
--------------------------
===================================================================================
===========================================================
Operator in Java:
-----------------
Operator is a symbol that is used to perform operations. For example: +, -,
*, / etc.
There are many types of operators in Java which are given below:
-----------------------------------------------------------------------------------
--------
Operator Type Category Precedence
-----------------------------------------------------------------------------------
----------
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
---------------------------------------------------------------------------
Arithmetic multiplicative * / %
additive + -
----------------------------------------------------------------------------
Shift shift << >> >>>
----------------------------------------------------------------------------
Relational comparison < > <= >= instanceof
equality == !=
----------------------------------------------------------------------------
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
-----------------------------------------------------------------------------
Logical logical AND &&
logical OR ||
-------------------------------------------------------------------------------
Ternary ternary ? :
---------------------------------------------------------------------------------
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
-----------------------------------------------------------------------------------
---------------
===================================================================================
===============================================================
Note: Every code using an if-else statement cannot be replaced with a ternary
operator.
Syntax:
1) If Statemens.
2) Switch Statements.
If Statement consists of:
-------------------------
The Java if statement is used to test the condition. It checks boolean condition:
true or false.
There are various types of if statement in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
Java if Statement:
-------------------
The Java if statement tests the condition. It executes the if block if condition is
true.
Switch Statement:
-----------------------
The Java switch statement executes one statement from multiple conditions.It
is like
if-else-if ladder statement.Since Java 7, you can use strings in the
switch statement.
In other words, the switch statement tests the equality of a variable against
multiple values.
Points to Remember:
---------------------
.There can be one or N number of case values for a switch expression.
.The case value must be of switch expression type only. The case value must
be
literal or constant. It doesn't allow variables.
.The Java switch expression must be of byte, short, int, long (with its
Wrapper type), enums and string.
.Each case statement can have a break statement which is optional. When
control reaches to the break statement,
it jumps the control after the switch expression. If a break statement is
not found, it executes the next case.
===================================================================================
=============================================
Looping Statements:
---------------------
For Loop:
----------
The Java for loop is used to iterate a part of the program several times.
Initialization:
---------------
It is the initial condition which is executed once when the loop starts
Here, we can initialize the variable, or we can use an already initialized
variable.
It is an optional condition.
Condition:
-----------
It is the second condition which is executed each time to test the
condition
of the loop. It continues execution until the condition is false. It must return
boolean
value either true or false. It is an optional condition.
Increment/Decrement:
--------------------
It increments or decrements the variable value. It is an optional
condition.
Statement:
-----------
The statement of the loop is executed each time until the second condition
is false.
Syntax:
-------
for(initialization; condition; increment/decrement){
}
for-each Loop:
--------------
The for-each loop is used to traverse array or collection in Java. It is
easier to use than simple
for loop because we don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one
by one in the defined variable.
Syntax:
--------
for(data_type variable : array_name){
While Loop:
-----------
The Java for loop is used to iterate a part of the program several times.
If the number of iteration is not fixed, it is recommended to use While loop.
do While:
----------
The Java do while loop is a control flow statement that executes a part of
the programs at least once and the further execution depends upon the given boolean
condition.
If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use the do-while loop.
Jump Statements:
-----------------
1)Break Statement
2)Continue Statement
Break Statement:
------------------
When a break statement is encountered inside a loop, the loop is
immediately
terminated and the program control resumes at the next statement following the
loop.
We can use Java break statement in all types of loops such as for loop,
while loop and do-while loop.
Continue Statement:
--------------------
The continue statement is used in loop control structure when you need
to
jump to the next iteration of the loop immediately. It can be used with for loop or
while loop.
We can use Java continue statement in all types of loops such as for
loop,
while loop and do-while loop.
===================================================================================
===============================================
Static Block:
-------------
It runs before main method.
===================================================================================
=================================================
Debugging:
-----------
To launch an application into the market, it is very necessary to cross-check
it multiple
times so as to deliver an error-free product.
When we talk about delivering a bug-free product, then our main concern is all
about customer
satisfaction because if you are application is not up to the mark, then eventually
it will demolish the
company's reputation in the market.
===================================================================================
===================================================
= and == difference?
===================================================================================
=====================================================
This -- refers to current class.
Constructor:
-------------
There are many differences between constructors and methods. They are given below.
-----------------------------------------------------------------------------------
-
-----------------------------------------------------------------------------------
-------------------------------------------
Java Constructor Java Method
-----------------------------------------------------------------------------------
-------------------------------------------
A constructor is used to initialize the state of an object. A method is used
to expose the behavior of an object.
-----------------------------------------------------------------------------------
--------------------------------------------
A constructor must not have a return type. A method must have
a return type.
-----------------------------------------------------------------------------------
--------------------------------------------
The constructor is invoked implicitly. The method is
invoked explicitly.
-----------------------------------------------------------------------------------
---------------------------------------------
The Java compiler provides a default constructor if The method is not
provided by the compiler in any case.
you don't have any constructor in a class.
-----------------------------------------------------------------------------------
-----------------------------------------------
The constructor name must be same as the class name. The method name
may or may not be same as the class name.
-----------------------------------------------------------------------------------
-----------------------------------------------
Constructor Overriden:
-----------------------
Constructor looks like method but it is not.It does not have a return
type and its name is same as the class name.
===================================================================================
=======================================================
String:
-------
.String is non primitive data type.
.String is a class in java.
.String Values enclosed in double quotes.
.String works on index basis.
.Index will start from 0 to n-1.
.String class provides a lot of methods to perform operations on strings such
as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
Example:
---------
Memory Space
String name="KARTHIK";
Name
|K| A| R| T| H| I| K|
Index 0 1 2 3 4 5 6(n-1)
-----------------------------------------------------------------------------------
----------------------------------------------
There are two ways to create String object:
-----------------------------------------------------------------------------------
-------------------------------------------------------
.euals() == difference?
------------------------
.Equals() compares the actual content stored value.
.== Compares the memory Address.
===================================================================================
====================================================
Types of Memory:
----------------
1)Method Area.
2)Heap Memory - Class,Objects,Static members,String pool.
3)Stock Memory - Variable name,Local Variables,methods etc(temporary).
4)Pc Registers.
5)Native Area.
===================================================================================
=======================================================
Array:
-------
.Array is a non primitive data type.
.Array is a Class.
.Can store similar type of values in one single variable.
.by size & -- int [] arr= new int[4].
.by value -- int [] arr={10,20,30}
.Array works on index basis(0 to n-1).
.Array are fixed in size.
.Array is a class which contains elements of a similar data type
Disadvantages of Array:
--------------------------
-----------------------------------------------------------------------------------
--------------------------------------
Arrays:
---------
===================================================================================
=========================================================
Wrapper class:
---------------
The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
Autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically.
-----------------------------------------------------------------------------------
----------------
Generics <> :
--------------
we can store the data type in between the angular bracket is called Generics.
===================================================================================
==========================================================
Collection & Collections difference:
-------------------------------------
Collection -- is an interface.
Collections -- is a class.
-----------------------------------------------------------------------------------
-----------
Collection:
------------
Java collection is a framework.
Collections can achieve all the operations that you perform on a data such as
searching,
sorting, insertion, manipulation, and deletion.
Collection framework provides many interfaces (Set, List, Queue, Deque) and
classes
(ArrayList, Vector, LinkedList,HashSet, LinkedHashSet, TreeSet).
Advantages of collection:
--------------------------
Dissimilar data types can be used.
no memory wastage.
-----------------------------------------------------------------------------------
----------------
-----------------------------------------------------------------------------------
ArrayList<Integer> list = new ArrayList<Integer>();// nnot advisable..
-----------------------------------------------------------------------------------
------------------------
List:
------
List is an Interface.
It allows duplicate values
Works on index basis from o to n-1.
Default order execution-Insertion order.
ArrayList:
----------
Searching and retriving is easy.
LinkedList:
-----------
Insertion and Deletion is easy
Vector:
--------
Thread safe and Synchronize.
--------------------------------------------------------
Set:
------
Set is an Interface.
It will not allow duplicate values
Works on value basis.
Order of execution-based on its class order.
HashSet:
---------
Execution order is Random order
LinkedHashset:
--------------
Execution order is Insertion order
TreeSet:
---------
Execution order is Ascending order
Auto iteration(Increment).
-------------------------------------------------------------
Map:
-----
It is an interface
HashMap:
---------
Execution order is Random order
LinkedHashMap:
--------------
Execution order is Insertion order
TreeMap:
---------
Execution order is Ascending order
-----------------------------------------------------------------------------------
-----------------------
HashMap is non Synchronized and is not thread safe while HashTable is thread safe
and Synchronized.
===================================================================================
==========================================================
Error:
-------
Exception:
----------
1)Built-in Exceptions:
.Checked Exception
.Unchecked Exception
2)User-Defined Exceptions:
-----------------------------------------------------------------------------------
------------------------------------------------
1)Built-in Exception:
--------------------
Exceptions that are already available in Java libraries are referred to
as built-in exception.
These exceptions are able to define the error situation so that we can understand
the reason of getting this error.
It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
-----------------------------------------------------------------------------------
--------------------------------------------------
Checked Exception:
------------------
Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time
by the compiler. The compiler ensures whether the programmer handles the exception
or not.
The programmer should have to handle the exception; otherwise, the system has shown
a compilation error.
-----------------------------------------------------------------------------------
----------------------------------------------------
Unchecked Exceptions:
---------------------
The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we
didn't handle or declare it, the program would not give a compilation error.
Usually, it occurs when the
user provides bad data during the interaction with the program.
-----------------------------------------------------------------------------------
--------------------------------------------------------
User-defined Exception:
------------------------
In Java, we already have some built-in exception classes like
ArrayIndexOutOfBoundsException, NullPointerException,
and ArithmeticException. These exceptions are restricted to trigger on some
predefined conditions. In Java, we can write
our own exception class by extends the Exception class. We can throw our own
exception on a particular condition using
the throw keyword.For creating a user-defined exception, we should have basic
knowledge of the try-catch block and throw keyword.
===================================================================================
=========================================================
Throw:
------
Throws:
--------
===================================================================================
==========================================================
===================================================================================
=========================================================
Try block :
------------
We specify the block of code that might give rise to the exception in a
special block with a “Try” keyword.
Catch:
---------
When the exception is raised it needs to be caught by the program. This is
done using a “catch” keyword.
So a catch block follows the try block that raises an exception. The keyword catch
should always be used with a try.
Finally:
---------
Sometimes we have an important code in our program that needs to be executed
irrespective of whether or not
the exception is thrown. This code is placed in a special block starting with the
“Finally” keyword.
The Finally block follows the Try-catch block.
===================================================================================
===================================================================
-----------------------------------------------------------------------------------
--------------------------------------------------------------
S.No Checked Exception Unchecked
Exception
-----------------------------------------------------------------------------------
---------------------------------------------------------------
1. These exceptions are checked at compile time. 1)These exceptions
are just opposite to the checked exceptions.
These exceptions are handled at compile time too. These
exceptions are not checked and handled at compile time.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
2. These exceptions are direct subclasses of exception 2)They are the
direct subclasses of the RuntimeException class.
but not extended from RuntimeException class.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
3. The code gives a compilation error in the case when 3)The code
compiles without any error because the exceptions escape
a method throws a checked exception.The compiler is the notice of
the compiler.These exceptions are the results of
not able to handle the exception on its own. user-created
errors in programming logic.
-----------------------------------------------------------------------------------
------------------------------------------------------------------
4. These exceptions mostly occur when the probability 4)These exceptions
occur mostly due to programming mistakes.
of failure is too high.
-----------------------------------------------------------------------------------
------------------------------------------------------------------
5. Common checked exceptions include IOException, 5)Common unchecked
exceptions include ArithmeticException,
DataAccessException, InterruptedException, etc.
InvalidClassException, NullPointerException, etc.
-----------------------------------------------------------------------------------
--------------------------------------------------------------------
6. These exceptions are propagated using the throws keyword. 6)These are
automatically propagated.
-----------------------------------------------------------------------------------
----------------------------------------------------------------------
7. It is required to provide the try-catch and try-finally 7)In the
case of unchecked exception it is not mandatory.
block to handle the checked exception. Bugs or errors
that we don't want and restrict the normal execution
of the programs are referred
to as exceptions.
===================================================================================
====================================================================
Final:
-------
Finally:
--------
It is a block.
Finalize:
----------
It is a method - in object class - java supermost class.
===================================================================================
=====================================================================
Types of casting:
-----------------
In Java, type casting is a method or process that converts a
data type into another data type in both ways manually and automatically.
The automatic conversion is done by the compiler and manual conversion performed by
the programmer.
-----------------------------------------------------------------------------------
------------------------------------
-----------------------------------------------------------------------------------
--------------------------------------------
===================================================================================
========================================
===================================================================================
=====================================================================
xml:
------
Xml was released in late 90’s. it was created to provide an easy to use and
store self describing data.
XML tags are not predefined. You must define your own tags.
The key difference between XML and HTML is that XML is a framework for specifying
markup languages
(stores and transfers data). In contrast, HTML is a predefined markup language
(describes the structure of a webpage).
XML tags are not predefined whereas HTML has predefined tags.
===================================================================================
==========================================================