You are on page 1of 34

What is JAVA?

Java is the most popular, widely used object-oriented programming language.


The security feature of Java makes it popular and widely used.
It used by many Java enthusiasts for different purposes.
By using Java, we can develop a variety of applications such as enterprise
applications,
network applications, desktop applications, web applications, games, android app,
and many more.

===================================================================================
========================
Why we use Java?

Why 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.

It is one of the most popular programming language in the world


It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has a huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs and
allows code to be reused,
lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java
or vice versa

More Advantages/feautures in java:

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.

Java Architecture can be explained by using the following steps:


------------------------------------------------------------------
There is a process of compilation and interpretation in Java.

Java compiler converts the Java code into byte code.

After that, the JVM converts the byte code into machine code.

The machine code is then executed by the machine.

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.

Components of Java Architecture

The Java architecture includes the three main components:

Java Virtual Machine (JVM)


Java Runtime Environment (JRE)
Java Development Kit (JDK)
-----------------------------------------------------------------------------------
---------------------------
Java Virtual Machine:
---------------------
The main feature of Java is WORA. WORA stands for Write Once Run Anywhere.

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.

The falling figure represents the architecture of the JVM.

-----------------------------------------------------------------------------------
-------------------------------------
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.

.==================================================================================
===================================

What is IDE(Integrated development environment)?

An integrated development environment (IDE) is a software application that


helps programmers develop software code efficiently.
It increases developer productivity by combining
capabilities such as software editing, building, testing, and
packaging in an easy-to-use application.

.NetBeans
.InteeliJ
.Eclipse
.Notepad etc....
===================================================================================
====================================
Why EClipse?

The Eclipse is defined as platform for developing the computer-based


applications using
various programming language like JAVA, Python, C/C++, Ruby and many
more that make
the platform favorable for the programmers to use for application
development.

The Eclipse is IDE(Integrated development kit) and mainly JAVA based


programming is done
in this platform.The Eclipse IDE is rich features IDE that supports
various programming
features for the developers and ease their work for development of
advanced application
in eclipse platform.

Importance of Eclipse IDE:


--------------------------
1. Code insight or code competition.
2. Provide workspace.
3. Provide editors and views.
===================================================================================
====================================
What is workspace?

Your workspace is a folder where you keep your projects.

===================================================================================
===================================
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.

PascalNotation -- is a programming naming convention where the first letter


of each word in a variable is capitalized.Pascal naming in Class,Project,
Interface Example FirstWord,GoodMorning.

camelNotation -- is a programming naming convention where the first letter


of each word in a variable is capitalized except the first word.camel naming in
variables,
method Example firstWord,goodMorning.

package Notation -- is a programming naming convention it is different from pascal


& camel naming
all letters/words should be lower case,starts with com.organisation name.jobscope
for identification.
Example com.aiite.javaprogram

===================================================================================
=======================================
Types of Brackets:
------------------

{} - Curly brace bracket


() - Paranthesis
[] - Suare Bracket
<> - Angle Bracket
===================================================================================
========================================
We have to write code inside main?

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.

What happens if the main() method is written without String args[]?

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.

Main () method Explanation:


---------------------------

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?
-------------------

A method is a block of code or collection of statements or a set of code grouped


together to perform a certain
task or operation. It is used to achieve the reusability of code. We write a method
once and use it many times.
We do not require to write code again and again. It also provides the easy
modification and readability of code,
just by adding or removing a chunk of code. The method is executed only when we
call or invoke it.

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.

Public - Access Specifier/Visibility.


int - Return Type.
Sum - MethodName.
(int a,int b) - Parameter List.
Sum (int a,int b) - MethodBody,MethodSignature.
===================================================================================
========================================
Access Specifier:
-----------------
Access specifier or modifier is the access type of the method. It
specifies the visibility
of the method. Java provides four types of access specifier:
-----------------------------------------------------------------------------------
----------------------------------------
Public:
---------
The method is accessible by all classes when we use public specifier in our
application.
-----------------------------------------------------------------------------------
----------------------------------------
Private:
----------
When we use a private access specifier, the method is accessible only in the
classes in
which it is defined.
-----------------------------------------------------------------------------------
----------------------------------------
Protected:
----------
When we use protected access specifier, the method is accessible within the
same package
or subclasses in a different package.
-----------------------------------------------------------------------------------
----------------------------------------
Default:
--------
When we do not use any access specifier in the method declaration, Java uses
default access
specifier by default. It is visible only from the same package only.
-----------------------------------------------------------------------------------
------------------------------------------
Return Type:
------------
Return type is a data type that the method returns. It may have a
primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
-----------------------------------------------------------------------------------
-------------------------------------------
Method Name:
------------
It is a unique name that is used to define the name of a method. It must
be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction
of two numbers, the method name
must be subtraction(). A method is invoked by its name.
-----------------------------------------------------------------------------------
-------------------------------------------
Parameter List:
---------------
It is the list of parameters separated by a comma and enclosed in the
pair of parentheses.It contains
the data type and variable name. If the method has no parameter, left the
parentheses blank.
-----------------------------------------------------------------------------------
-------------------------------------------
Method Body:
------------
It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within
the pair of curly braces.
===================================================================================
=========================================
Types of Method:
-----------------

There are two types of methods in Java:

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.

How to Call or Invoke a User-defined Method:


--------------------------------------------
Once we have defined a method, it should be called. The calling of a
method in a program is simple. When we call or
invoke a user-defined method, the program control transfer to the called method.
===================================================================================
===============================================:
Parameterized and Non-Parameterized Methods:
-----------------------------------------------
Java allows us to create two types of methods based on the parameter list. These
are given below:

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.
===================================================================================
==============================================

What are Variables ?

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

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:

Primitive data types:


---------------------
The primitive data types include boolean, char, byte, short, int, long,
float and double.

-----------------------------------------------------------------------------------
-------------------
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

type variableName = value.


===================================================================================
===========================================
Class:
------
A class is a group of objects which have common properties.It is a template
or blueprint from which
objects are created. It is a logical entity. It can't be physical.

A class can contain:


----------------------------
1)ATribute/Fields - Description -How it is?
2)Function/Methods - Function -What it is doing?
3)Constructors
4)Blocks
5)Nested class and interface

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:
--------------

It is a predefined Class in Java it comes from the package java.util it is


used to geet input from user
at runtime.
The Java Scanner class is widely used to parse text for strings and primitive
types using a regular expression.
It is the simplest way to get input in Java. By the help of Scanner in Java,
we can get input from the user in
primitive types such as int, long, double, byte, float, short, etc.

===================================================================================
=================================================
OOPS:
------

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while
object-oriented programming is about creating objects that contain both data and
methods.

Object-oriented programming has several advantages over procedural programming:

OOP is faster and easier to execute.


OOP provides a clear structure for the programs.
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug.
OOP makes it possible to create full reusable applications with less code and
shorter development time.

Object-Oriented Programming is methodology or paradigm to design a program using


classes and objects. It simplifies software
development and maintenance by providing some concepts:

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.

In java programming, multiple and hybrid inheritance is not Supported in


inheritance due to priority issue,but supported through interface only.

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 overloading and method overriding.


If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.

1)Static Binding/compile-time polymorphism:


--------------------------------------------
.Early Binding
.Method Overload.

2)Dynamic Bindin/Runtime polymorphism:


---------------------------------------
.Later Binding.
.Method Override.

* 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).

1)Abstract - Partial Abstraction.


2)Interface - Fully Abstraction.

Abstract:
---------
An abstract class can have both abstract and Non-Abstract(Regular) methods.
Method only have declaration not the implementation.

To achieve Abstract Abstraction:


------------------------
Abstract class can have abstract and non-abstract method.
ABstract class doesn't support multiple inheritance.
Abstract keyword is used in Class and method to declare as abstract
class.

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:
--------------

.Encapsulation is one of the fundamental oops concept.


.Encapsulation in java is a mechanism of wrapping the data(Variables) &
code
acting on data(method) together as a single unit.
.In Encapsulation,the Variables of a class will be hidden from other
classes,
and can be accessed only through the methods of their current class.
.It is also known as a data hiding(Atribute Hiding).
.POJO-(Plain Old java object).

To achieve Encapsulation in Java:


----------------------------------
.Declare the variables of a class as private.
.Provide Public setter and getter methods to modify and view the
variables values.

Benefits of Encapsulation:
--------------------------

The fields of a class can be made read only or write only.


A class can have control over what is stored in its fields.
Data hiding provides object integrity by preventing unintended or
intended changes.

===================================================================================
===========================================================
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 = += -= *= /= %= &= ^= |= <<= >>=
>>>=
-----------------------------------------------------------------------------------
---------------

===================================================================================
===============================================================

Ternary Operator: (Short ...Hand ...if...else in C++,C#)


--------------------------------------------------------
The ternary operator (? :) consists of three operands.
It is used to evaluate Boolean expressions. The operator decides
which value will be assigned to the variable.It is the only conditional
operator that accepts three operands. It can be used instead of the if-else
statement.
It makes the code much more easy, readable, and shorter.

Note: Every code using an if-else statement cannot be replaced with a ternary
operator.

Syntax:

variable = (condition) ? expression1 : expression2


===================================================================================
============================================
Conditional Statements:
-----------------------

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.

Java if-else Statement:


-----------------------
The Java if-else statement also tests the condition. It executes the if block if
condition
is true otherwise else block is executed.

Using Ternary Operator:


------------------------
We can also use ternary operator (? :) to perform the task of if...else
statement.It is a
shorthand way to check the condition. If the condition is true, the result of ? is
returned.
But, if the condition is false, the result of : is returned.

Java if-else-if ladder Statement:


---------------------------------
The if-else-if ladder statement executes one condition from multiple statements.

Java Nested if statement:


-------------------------
The nested if statement represents the if block within another if block. Here, the
inner
if block condition executes only when outer if block 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.

The Java switch statement is fall-through. It means it executes all


statements after the first
match if a break statement is not present.

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 case values must be unique. In case of duplicate value, it renders


compile-time error.

.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.

.The case value can have a default label which is optional.

===================================================================================
=============================================
Looping Statements:
---------------------

For Loop:
----------
The Java for loop is used to iterate a part of the program several times.

If the number of iteration is fixed, it is recommended to use for loop.

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){
}

Nested for Loop:


----------------
If we have a for loop inside the another loop, it is known as nested for
loop.
The inner loop executes completely whenever outer loop executes.

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.

The Java break statement is used to break loop or switch statement.


It breaks the current flow of the program at specified condition. In case of inner
loop,
it breaks only inner 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.

The Java continue statement is used to continue the loop. It continues


the
current flow of the program and skips the remaining code at the specified
condition.
In case of an inner loop, it continues the inner loop only.

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.

Static Atribute & Method:


--------------------------
It can access only static members.
It can be called without an instance.
It is not associated with the object.
Non-static data members cannot be accessed by the static function.

===================================================================================
=================================================

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?

= is assigning a value to the variable

== is checking the condition orr comparison of values.

===================================================================================
=====================================================
This -- refers to current class.

super -- refers to parent class.


===================================================================================
======================================================

Constructor:
-------------

There are two rules defined for the constructor.


--------------------------------------------------
Constructor name must be the same as its class name

A Constructor must have no explicit return type

A Java constructor cannot be abstract, static, final, and synchronized

A constructors will invoke automatically,when object reference created.

There are two types of constructors in Java:


--------------------------------------------
Default constructor (no-arg constructor)
Parameterized constructor

Constructor Overloading in Java:


--------------------------------
In Java, a constructor is just like a method but without return type.

It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one


constructor
with different parameter lists. They are arranged in a way that each
constructor performs
a different task. They are differentiated by the compiler by the number
of parameters in the list and their types.

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.

But, a constructor cannot be overridden. If you try to write a super


class’s constructor in the sub class compiler
treats it as a method and expects a return type and generates a compile time error.

===================================================================================
=======================================================
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:

1)By string literal.


2)By new keyword.

String name = "AiiTE";// String literal

String aiite=new String();//String object - String non-Literal.


-----------------------------------------------------------------------------------
-----------------------------------------------------
Why String is Immutable or Final in Java?
------------------------------------------
In object-oriented programming, the immutable string or objects that
cannot be modified once it is created.

But we can only change the reference to the object. We restrict to


change the object itself.

The String is immutable in Java because of the security,


synchronization and concurrency, caching, and
class loading. The reason of making string final is to destroy the
immutability and to not allow others to extend it.

String in java always Immutable can't be changed.

String is Immutable whereas String buffer and String Builder are


Mutable classes.

String buffer is thread safe and synchronized whereas String builder


not.

-----------------------------------------------------------------------------------
-------------------------------------------------------
.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

Two types of Array:


--------------------
1)Single dimensional array. -- int [] arr = new int[].
2)Multi dimensional array. -- int [] [] arr = new int[] [].

Disadvantages of Array:
--------------------------

Dissimilar data types can't be used.


Memory wastage is high.
Fixed in Size.

-----------------------------------------------------------------------------------
--------------------------------------

Arrays:
---------

it is predefined class in java.


it supports array.

===================================================================================
=========================================================

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.

The automatic conversion of primitive into an object is known as autoboxing


and

The automatic conversion of an object into primitive is known as unboxing.

-----------------------------------------------------------------------------------
----------------
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.

It gives access to prepackaged data structures and algorithms for


manipulating data.

To overcome array disadvantages.

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.

Dynamic memory Allocation.

no memory wastage.

-----------------------------------------------------------------------------------
----------------

Collection has many interfaces and classes:


---------------------------------------------

Interfaces & their respond classes:


-------------------------------------

1)List -- Classes (ArrayList,LinkedList,Vector)


2)Set -- Classes (HashSet,LinkedHashset,TreeSet)
3)Map -- Classes (HashMap,LinkedHashMap,TreeMap)
4)Queue

-----------------------------------------------------------------------------------
ArrayList<Integer> list = new ArrayList<Integer>();// nnot advisable..

List<Integer> list = new ArrayList<Integer>(); //Advisable

To Achieve a dynamic polymorphism that a code can runs without a break.

-----------------------------------------------------------------------------------
------------------------

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

does not allow null value.

For each loop:


---------------
It works on value basis.

Auto iteration(Increment).

Can't print in reverse.

can't get customized result.

-------------------------------------------------------------

Map:
-----

It is an interface

It wiil not duplicate in key(recent value override) but allows duplicate


values
in value.

It works (Key,Value) pair combination.

Order of Execution based on its classes order.

HashMap:
---------
Execution order is Random order
LinkedHashMap:
--------------
Execution order is Insertion order
TreeMap:
---------
Execution order is Ascending order

does not allow null value.

-----------------------------------------------------------------------------------
-----------------------

Why HashMap print in random in order?

A HashMap is similar to a TreeMap,However the HashMap stores its items stored in


no particular order.

Also it allows more than one null values,it maintains no order.


-----------------------------------------------------------------------------------
--------------------------

Difference between Hashmap and HashTable?


------------------------------------------

HashMap is non Synchronized and is not thread safe while HashTable is thread safe
and Synchronized.

===================================================================================
==========================================================

Object --- supermost class in java


|
Throwable ---- Super class
|
------------------------------
| |
Error Exception

Error:
-------

Which cannot handle by program.

.Space Memory ranout.


.Internet not connected.
.Hard Disk.

Exception:
----------

.Unexpected events which causes problem to program.

.Exception will stop the program Execution.

Types of Exception in Java:


----------------------------
Exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program's instructions. Bugs or errors that we
don't want
and restrict our program's normal execution of code are referred to as exceptions.

Exceptions can be categorized into two ways:

1)Built-in Exceptions:

.Checked Exception
.Unchecked Exception

2)User-Defined Exceptions:

-----------------------------------------------------------------------------------
------------------------------------------------

Types of Exception in Java:


---------------------------

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:
------

Explicit throw an Exception.

used inside the method.

we can throw only one Exception.


=================================================================================

Throws:
--------

Throws Keyword used to declare the exception.

used in method signature.

we can declare multiple exception using throws.

===================================================================================
==========================================================

Possible combination of exception handling try catch finally ?

Try, Try, Try,


Catch Finally catch
Finally

===================================================================================
=========================================================

Exception can handle by try,catch,finally block:


-------------------------------------------------

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.

===================================================================================
===================================================================

Difference Between Checked and Unchecked Exception:

-----------------------------------------------------------------------------------
--------------------------------------------------------------
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:
-------

It is a keyword used at variable,Method and Class level.

Finally:
--------

It is a block.

It is used to place important code in this block.

It gets executed irrespective of whether the exception is handled or not.

Finalize:
----------
It is a method - in object class - java supermost class.

It performs cleaning up process before the object is garbage collected.

===================================================================================
=====================================================================

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.

-----------------------------------------------------------------------------------
------------------------------------

Types of Type Casting:


----------------------
There are two types of type casting:

1)Widening/Implicit Type Casting


2)Narrowing/Explicit Type Casting

-----------------------------------------------------------------------------------
--------------------------------------------

1)Implicit/Widening Type Casting:


------------------------
Converting a lower data type into a higher one is called widening type
casting.
It is also known as implicit conversion or casting down. It is done
automatically.
It is safe because there is no chance to lose data. It takes place when:
Both data types must be compatible with each other.
The target type must be larger than the source type.
-----------------------------------------------------------------------------------
----------------------------------------

2)Explicit/Narrowing Type Casting:


-------------------------
Converting a higher data type into a lower one is called narrowing type
casting.
It is also known as explicit conversion or casting up. It is done manually by
the programmer.
If we do not perform casting then the compiler reports a compile-time error.
In the following example, we have performed the narrowing type casting two
times.
First, we have converted the double type into long data type after that long
data type
is converted into int type.

===================================================================================
========================================

What is the singleton class in java?


In object-oriented programming, a singleton class is a class that can
have only one object
(an instance of the class) at a time. After the first time, if we try to
instantiate the Singleton class,
the new variable also points to the first instance created.

===================================================================================
=====================================================================

xml:
------

Xml (eXtensible Markup Language) is a mark up language.

XML is designed to store and transport data.

Xml was released in late 90’s. it was created to provide an easy to use and
store self describing data.

XML became a W3C Recommendation on February 10, 1998.

XML is not a replacement for HTML.

XML is designed to be self-descriptive.

XML is designed to carry data, not to display data.

XML tags are not predefined. You must define your own tags.

XML is platform independent and language independent.


---------------------------------------------------------------------------------
What is the Difference between XML and HTML?

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).

KEY DIFFERENCE B/W XML & HTML :


-------------------------------------------
XML is abbreviation for extensible Markup Language whereas HTML stands for
Hypertext Markup Language.

XML mainly focuses on transfer of data while HTML is focused on presentation


of the data.

XML is content driven whereas HTML is format driven.

XML is Case sensitive while HTML is Case insensitive.

XML provides namespaces support while HTML doesn’t provide namespaces


support.

XML is strict for closing tag while HTML is not strict.

XML tags are extensible whereas HTML has limited tags.

XML tags are not predefined whereas HTML has predefined tags.
===================================================================================
==========================================================

You might also like