0% found this document useful (0 votes)
62 views

CORE JAVA

Uploaded by

Mayuri Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

CORE JAVA

Uploaded by

Mayuri Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 126

CORE JAVA

Introduction:
Java is the high-level programming language that was developed by James
Gosling in the year 1995. It is based on the principles of object-oriented
programming and can be used to develop large-scale applications. It has some
important features like Platform-Independent, Portable, Architecture Neutral,
Secure, Robust, Multithreading, etc.
History:
Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed
Frank and Mike Sheridan at Sun Microsystems, Inc in 1991. Initially it was
called Oak, later it was changed to Java in 1995.

Many java versions have been released till now. The current stable release of
Java is Java SE 10.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10.Java SE 8 (18th Mar 2014)
11.Java SE 9 (21st Sep 2017)
12.Java SE 10 (20th Mar 2018)
13.Java SE 11 (September 2018)
14.Java SE 12 (March 2019)
15.Java SE 13 (September 2019)
16.Java SE 14 (Mar 2020)
17.Java SE 15 (September 2020)
18.Java SE 16 (Mar 2021)
19.Java SE 17 (September 2021)
20.Java SE 18 (to be released by March 2022)

FEATURES OF JAVA:
Object-Oriented Programming Language:
Object-Oriented Programming Language means way of developing software
based on concept of Object.
We organize our software as a combination of different types of objects that
incorporate both states (variables) and behaviour (methods).
Example: A dog is an object because it has states (variables) like colour, name,
breed, etc. as well as behaviours (methods) like wagging the tail, barking,
eating, etc.
Basic concepts of oop’s:
Class
Object
Inheritance
Polymorphism
Abstraction
Encapsulation

Robust:

Robust means Strong. Java is robust because of Strong memory management by


introducing automatic garbage collector and eliminate errors by introducing
exception handling.

Platform Independent language:


Platform Independent language java code is compiled by the java
compiler(javac) and converted into bytecode (.class file). This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere(WORA).

Architecture Neutral:

Architecture Neutral because there are no implementation dependent features,


for example, the size of primitive data types is fixed.
Example: In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable:

Portable means we can carried the Java byte code on any platform. It doesn't
require any implementation. Everything related to storage is predefined.
example: size of primitive data types.

Secure:

Secure features it enable us to develop virus free applications. Java program


always runs in Java runtime environment with almost null interaction with
system OS, hence it is more secure.

Multithreading:

Multithreading feature makes it possible to write program that can do many


tasks simultaneously. Benefit of multithreading is that it utilizes same memory
to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.

C++ vs Java
C++ Java

C++ is platform-dependent. Java is platform-independent.

C++ uses compiler only. C++ is Java uses both compiler and interpreter.
compiled and run using the compiler
Java source code is converted into
which converts source code into
machine code so, C++ is platform bytecode at compilation time. The
dependent. interpreter executes this bytecode at
runtime and produces output.
Java is interpreted that is why it is
platform-independent.
C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in Windows-
based, web-based, enterprise, and mobile
applications.

C++ is an object-oriented language. Java is also an object-oriented


However, in the C language, a single
language. However, everything
root hierarchy is not possible.
(except fundamental types) is an
object in Java. It is a single root
hierarchy as everything gets derived from
java.lang.Object.

Java vs Python

Java Python

Java is both compiled and interpreted Python is an interpreted language,


language. The source code is first i.e., it is compiled and
compiled and converted to bytecode, executed simultaneously line by line.
and afterward, it depends on JVM
whether the bytecode will be collected
or interpreted

Java vs .NET

The biggest difference between Java and .NET is that Java can run on any
operating system through its compilers and JRE (Java Runtime Environment) as
it follows the principle “write once, run anywhere”.

On the other hand, .NET works only on the Windows operating system and its
different versions.

What is JDK, JRE and JVM?


JDK:

The Java Development Kit (JDK) is a software used to develop java


applications. It contains JRE, Compilers (javac) and debuggers necessary for
developing java applications.

JRE:

Java Run-time Environment (JRE) is the part of the JDK. It consists of the Java
Virtual Machine (JVM), Classloader, Java Class Library, etc. The Java code
gets compiled and converted to Java bytecode. If you wish to run this bytecode
on any platform, you require JRE.

JVM:

Java Virtual Machine (JVM) is a virtual Machine that provides runtime


environment to execute java byte code.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code

Compilation and Execution of Java Program:


Compilation:

At compile time, the Java file is compiled by Java Compiler (javac) (It does not
interact with OS) and converts the Java code into bytecode.

Byte Code can be defined as an intermediate code generated by the compiler


after the compilation of source code (Java Program). This intermediate code
makes Java a platform-independent language.
Execution:

JVM Architecture

ClassLoader: Classloader in Java is a part of the Java Runtime


Environment(JRE).Classloader are responsible for loading Java classes
dynamically to the JVM (Java Virtual Machine) during runtime.
Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be
inspected by the bytecode verifier, whose job is to check that the instructions
don’t perform damaging actions. The following are some of the checks carried
out:
 Variables are initialized before they are used.
 Method calls match the types of object references.
 Rules for accessing private data and methods are not violated.
 Local variable accesses fall within the runtime stack.
 The run-time stack does not overflow.
 If any of the above checks fail, the verifier doesn’t allow the class to be
loaded.

JVM Memory
1. Method area: In the method area, all class level information like class
name, immediate parent class name, methods and variables information etc.
are stored, including static variables. There is only one method area per
JVM, and it is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is
also one Heap Area per JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is
stored here. Every block of this stack is called activation record/stack frame
which stores methods calls. All local variables of that method are stored in
their corresponding frame. After a thread terminates, its run-time stack will
be destroyed by JVM. It is not a shared resource.
4. PC Registers: Store address of current execution instruction of a thread.
Obviously, each thread has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created.
It stores native method information.

Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line
by line, uses data and information present in various memory area and
executes instructions. It can be classified into three parts:
 Interpreter: Interpreter is used to execute bytecode line by line.The
disadvantage here is that when one method is called multiple times, every
time interpretation is required.
 Just-In-Time Compiler(JIT): (JIT is used to convert the loaded bytecode
into machine code).It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the
interpreter sees repeated method calls, JIT provides direct native code for
that part so re-interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects.

Java Native Interface (JNI) :


It is an interface that interacts with the Native Method Libraries and provides
the native libraries(C, C++) required for the execution. It enables JVM to call
C/C++ libraries and to be called by C/C++ libraries which may be specific to
hardware.

Native Method Libraries :


It is a collection of the Native Libraries(C, C++) which are required by the
Execution Engine.

COMMENTS:
The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
Comments can be used to explain Java code, and to make it more readable.
Types of Comments:
o Documentation Comment: It starts with the delimiter (/**) and ends
with (*/).It includes basic information about a Java program. The
information includes the author's name, date of creation, version, program
name, company name, and description of the program.

For Example:

/**It is an example of documentation comment*/

o Single-line Comment: It starts with a pair of forwarding slash (//).

For Example:

//First Java Program

o Multi-line Comment: It starts with a /* and ends with */.

For Example:

/*It is an example
multiline comment*/

MAIN METHOD:

The main() is the starting point for JVM to start execution of a Java program.
Without the main() method, JVM will not execute the program. A class which
have main method is called Executable class.

Syntax:

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: static keyword allows the main method to be executed without creating
an object of that class.
void: void means 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.It’s not a keyword.
String args[]:agrs[] is the array name, and it is of String type.
Braces: The curly brackets are used to group all the commands together. To
make sure that the commands belong to a class or a method.

USER INPUT/OUTPUT:
OUTPUT:
System.out.println(“ ”);
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class. The method println
prints the text on the screen with a new line. All Java statements end with a
semicolon.
INPUT:
SCANNER CLASS:
import java.util.Scanner;
Here,
Scanner class is used to get user input, and it is found in the java.util
package.
Create object of Scanner class:
Scanner object_name=new Scanner(System.in);
Here,

new keyword is used to create an instance/object of the class. In other words, it


instantiates a class by allocating memory for a new object and returning a
reference to that memory. It allocates the memory at runtime. All objects
occupy memory in the heap area.

System.in is a standard input stream


Scanner Class Methods:
METHOD DESCRIPTION
nextBoolean() Reads a Boolean value from the user.
nextByte() Reads a Byte value from the user.
nextDouble() Reads a Double value from the user.
nextFloat() Reads a Float value from the user.
nextInt() Reads a Int value from the user.
nextLine() Reads a String value from the user.
nextLong() Reads a Long value from the user.
nextShort() Reads a Short value from the user.
next().charAt(0) Reads a Char value from the user.
Syntax:
data type variable_name=object_name.method_name();

Example:
int a=obj.nextInt();

DATA TYPES:
Data types specify size and the type of values that can be stored in an variable.
Types of data types:

1. Primitive data types: A primitive data type is pre-defined by the


programming language. The default size and value is predefined by the
programming language and it has no additional methods.

Data Default Default


Type Value Size

Boolean False 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

2. Non-primitive data types: Non-primitive types are created by the


programmer and is not defined by Java (except for String).

The non-primitive data types include Classes, Interfaces, Arrays, String,


etc.

TYPE CASTING:
In Java, type casting is a method or process that converts a one data type into
another data type in both ways manually and automatically.

Types of Type Casting:

Implicit type casting(Automatically):

Converting lower data type into higher data type is called Implicit type casting.

Explicit type casting(Manually):

Converting a higher data type into a lower one is called explicit type casting.

Example:

int x = 10;

byte y = (byte) x;

VARIABLE:
Variable is the name of memory location. When we want to store any
information, we store it in an address of the computer. Instead of remembering
the complex address where we have stored our information, we name that
address. The naming of an address is known as variable.
Rules for Variable name:
 A variable name can consist of capital letters A-Z, lowercase letters a-z,
digits 0-9, and underscore character.
 The first character must be a letter or underscore.
 Blank spaces cannot be used in variable names.
 Special characters like #, $ are not allowed.
 Java keywords cannot be used as variable names.
 Values of the variables can be numeric or alphabetic.
 Variable type can be char, int, float, double or void.
Variable Declaration:
Variable should be declared in the Java program before to use. Memory space is
not allocated for a variable while declaration. It happens only on variable
definition.
Syntax:
For Single Variable:
data_type variable_name;
Example:
int x;
For Multiple Variables:
data_type variable_name, variable_name, variable_name;
Example:
int x, y;
Initializing Variable:
When variables are declared initial values can be assigned to them in two ways.
1.The value is assigned at the declaration time.
Syntax:
data_type variable_name= value;
Example:
int x=10, y=20;
2.The values are assigned just after the declarations are made.
Syntax:
variable_name=value;
Example:
x=10;
y=20;
Types of Variables:

Local variable:
A local variable is declared within the body of a method, constructor or any
block. You can use the variable only within that method, constructor or block.
Other methods in the class aren’t even aware that the variable exists.
We can access these variable only within that block.
We can directly access local variables without any object and class name.
There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
Initialization variable:
local_variable=value;

Instance Variable/Class Member Variable:

Instance variable are variables which are declared within a class but cannot
declared within a body of method, constructor or any block.

Instance Variable can be accessed only by creating objects of class.

Each object has its own copy of each variable and thus, it doesn't affect if one
object changes the value of the instance variable.

Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null.

Creating objects:
class_name object_name=new class_name();
Intialization Variable:
object_name . instance_variable=value;
Accessing instance variable:
Object_name . instance_variable;

Static Variable/Class Member Variable:

Static variable are variables are declared within a class but cannot declared
within a body of method, constructor or any block. Static variables are declared
using the static keyword. Static variable are also known as class variable.
The static variable can be used to refer the common property of all objects(that
is not unique for each object).
Static variable belongs to class not an individual object. In Java, it means that it
will be constant for all the instances created for that class.
Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null.
Static Variable can be accessed by class name.
Example:
The company name of employees are same.
The college name of students are same.
Advantages of static variable:

It makes your program memory efficient (i.e., it saves memory).

Initialization variable:
class_name . static_variable=value;
Accessing static variable:
Class_name . static_variable;

Difference between Instance Variable and Static Variable:


Instance Variable Static Variable
Represent unique property Represent common property
Accessed using object Accessed using class
get new memory each time a new get memory only once
object is created

TOKENS:
 Each and every smallest individual unit in a program is known as tokens.
 Tokens are the basic buildings blocks in language which are constructed
together to write a program.
 Java supports 5 types of tokens which are:
1. Keyword
2. Identifiers
3. Literals
4. Special Symbol
5. Escape sequence
6. Operators

KEYWORDS:
Keywords in java are predefined or reserved words that have special meaning to
the Java compiler. Each keyword is assigned a special task or function and
cannot be changed by the user. You cannot use keywords as variables or
identifiers as they are a part of Java syntax itself. A keyword should always be
written in lowercase as Java is a case sensitive language. Java supports various
keywords, some of them are listed below:
01. abstract 02. Boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
37.
36. switch 38. this 39. throw 40. throws
synchronized
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
IDENTIFIERS:
Identifiers are the name given to various programming elements like variable
name, class name, object name, array name, function name, interface name,
package name.
Rules for constructing identifier name:
 All the identifiers must start with either a letter(a to z or A to Z),
underscore(_) or dollar sign($).
 Apart from the first character, an identifier can have any combination of
characters.
 Any identifier must not begin with a digit but can contains digits within.
 Java identifiers can be of any length.
 Identifier name cannot contain white spaces.
 A java keyword cannot use as an identifiers.
 Identifiers in java are case sensitive abc and ABC are two different
identifiers. Uppercase and lowercase are distinct.
Example:
Valid identifiers
$myvariable // correct
_variable // correct
variable // correct
edu_identifier_name // correct
edu2019var // correct

invalid identifiers
edu variable //error
Edu_identifier //error
&variable //error
23identifier //error
switch //error
var/edu //error
edureka’s //error

LITERALS:
Literals in Java are similar to normal variables but their values cannot be
changed once assigned. In other words, literals are constant variables with fixed
values. These are defined by users and can belong to any data type. Java
supports five types of literals which are as follows:

1. Integer
2. Floating Point
3. Character
4. String
5. Boolean

Example:

LITERAL TYPE
23 Int
9.86 Floating Point
‘a’ Character
“Mayuri” String
True, False Boolean
Null Any reference type

SPECIAL SYMBOLS/SEPARATORS:

Special symbols in Java are a few characters which have special meaning
known to Java compiler and cannot be used for any other purpose. The
separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:

o Square Brackets []: It is used to define array elements. A pair of square


brackets represents the single-dimensional array, two pairs of square
brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a
code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements.
It separates the two statements.
o Period (.): It separates the package name form the sub-packages and
class. It also separates a variable or method from a reference variable.

ESCAPE SEQUENCE:

A character preceded by a backslash (\) is an escape sequence and has a special


meaning to the compiler.
The following table shows the Java escape sequences.

Escape Sequence Description

\t Inserts a tab in the text at this point.


Escape Sequence Description

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.

\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.

\' Inserts a single quote character in the text at this


point.

\" Inserts a double quote character in the text at this


point.

\\ Inserts a backslash character in the text at this point.

OPERATORS:
In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can
be classified according to the functionality they provide. There are eight types
of operators in Java are as follows:
Types of operators in C:
Unary Operators:
 This type of operator works with a single operand like unary plus(+),
unary minus(-), increment(++), decrement(--),bitwise complement(~),
logical Not(!).
OPERATOR DESCRIPTION
Unary minus(-) Unary minus changes the sign of the any argument. It will change
positive number becomes negative and positive number becomes
negative.
Increment(++) Pre increment(++variable) It will increment variable value by
1 before assigning the value to the
variable.
Post increment(variable++) It will increment variable value by
1 after assigning the value to the
variable.
Decrement(--) Pre decrement(--variable) It will decrement variable value by
1 before assigning the value to the
variable.
Post decrement(variable--) It will decrement variable value by
1 after assigning the value to the
variable.
Binary Operators:
This type of operator works with two operands like arithmetic operators, logical
operators, relational operators, bitwise operators and assignment operators.
Arithmetic Operators:
OPERATOR DESCRIPTION
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Truth Table:
AND OR XOR
X Y X&&Y X||Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
NOT
X ~X
0 1
1 0

Relational Operators:
Relational operators are used to perform comparison. Relational operators
always results into Boolean value which is either 1 for- TRUE and 0 for-
FALSE.
OPERATOR DESCRIPTION
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Is equal to
!= Is not equal to
Logical Operators:
Java provides three logical operators when we test more than one condition to
make decisions. Relational operators always results into Boolean value which is
either 1 for- TRUE and 0 for- FALSE.
OPERATOR DESCRIPTION
&& AND operator. It performs logical conjunction of two
expressions. (T&&T=T)
|| OR operator. It performs a logical disjunction of two
expressions. (F||F=F)
! NOT operator. It performs logical negation on an
expression.(T=F),(F=T)
Bitwise Operators:
These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise
operators work on these bits and display output in decimal value.
OPERATOR DESCRIPTION
& Bitwise AND
This operator is a binary operator, denoted by ‘&’. It
returns bit by bit AND of input values, i.e, if both
bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

| Bitwisse OR
This operator is a binary operator, denoted by ‘|’. It
returns bit by bit OR of input values, i.e, if either of
the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

^ Bitwise X-OR
This operator is a binary operator, denoted by ‘^’. It
returns bit by bit XOR of input values, i.e, if
corresponding bits are different, it gives 1, else it
give 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

~ Bitwise Tilde
This operator is a unary operator, denoted by ‘~’. It
returns the one’s complement representation of the
input value, i.e, with all bits inverted, which means
it makes every 0 to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)

Bitwise Compliment Operation of 5

~ 0101
________
1010 = 10 (In decimal)

<< Left shift


Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the
right operand.
Example:
a=5<<2
0000 0101>>2
0 0 0 0 0 1 0 1
st
1 =Empty boxes will be marked as zero
0 0 0 1 0 1 0
nd
2 =
0 0 0 1 0 1
=10100
=20
Shortcut Method
a=5
a<<2
22*5 where 2 is the default base value power will be
left shift by 2.
4*5=20 where 5 be the value of a
Ans:20
>> Right shift
Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by the
right operand.
Example:
a= 5>>2
0000 0101>>2
0 0 0 0 0 1 0 1
st
1 =Empty boxes will be marked as zero
0 0 0 0 0 1 0
nd
2 =
0 0 0 0 0 1
=0001
=1
Shortcut Method
a=5
a>>2
22=4 where 2 is the default base value and power be
right shift by 2
5/4=1 where a=5
Ans:1

Assignment Operators:
Assignment operators applied to assign the result of an expression to a variable.
Java has a collection of shorthand assignment operators.
OPERATOR DESCRIPTION EXAMPLE
= Assign value from right side to left side variable X=Y
+= Add and assign operator. Firstly addition operations X+=Y
performed and then final value is transferred to the Is same as
variable on left hand side X=X+Y
-= Subtract and assign operator. Firstly subtraction X-=Y
operations performed and then final value is Is same as
transferred to the variable on left hand side. X=X-Y
*= Multiply and assign operator. Firstly multiplication X*=Y
operations performed and then final value is Is same as
transferred to the variable on left hand side. X=X*Y
/= Divide and assign operator. Firstly division operations X/=Y
performed and then final value is transferred to the Is same as
variable on left hand side. X=X/Y
%= Find modulus and assign operator. Firstly mod X%=Y
operations performed and then final value is Is same as
transferred to the variable on left hand side. X=X%Y
Ternary Operator(Conditional Operator):
The conditional operator is also known as a ternary operator, is one of the
operator which is used in the decision-making process.
Syntax:
test_expression? Statement1:statement2;
From the above syntax, if the given test condition is true, then it returns
statement1 and if it is false, statement2 will return.
OPERATOR DESCRIPTION
?: Conditional Expression

Instanceof Operator

The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it


compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.

An object of subclass type is also a type of parent class.(For Example:class A


extends class B).

CONTROL STATEMENTS:
Any programming language must be able to perform different sets of actions
depending on the situations. Control statements are the statements which change
the flow of execution in such a way that the programmer can execute the
statements as desired by him. These statements are called Decision Making
statements or Conditional Statements.
Types of Control Statements:
1. Selection Control Statements:
Selection Statements means executing different sections of code
depending on a specific condition or the value of variable.
 if statement
The Java if statement tests the condition. It executes the if block if
condition is true.
Syntax:
if(condition)
{
Block of statements;
}
 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.
Syntax:
if(condition)
{
Block of statements;
if(condition)
{
Block of statements;
}
if(condition)
{
Block of statements;
}
}
if(condition)
{
Block of statements;
}
 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.
Syntax:
if(condition)
{
Statement 1;
}
else
{
Statement 2;
}
Statements_4_block;

 nested if_else statement:


nested if-else is only executed when:-
 The condition of its outer if statement is true and
the condition of this nested if statement is also true.
 If condition of this nested if is false then the statement with
its connected else is executed.
Syntax:
if(condition)
{
if(condition 2)
{
Block of Statements;
}
else
{
Block of Statements;
}
else
{
if(condition 3)
{
Block of Statements;
}
else
{
Block of Statements;
}
Block of Statements;
}
 if_ else if_ else statement:
The if-else if-else ladder statement executes one condition from
multiple statements.
Syntax:
if(condition_1)
{
Statements_1_block;
}
else if(condition_2)
{
Statements_2_block;
}
else if(condition_n)
{
Statements_n_block;
}
else
statement_x;

 Switch-case statement:
Java switch statement contains multiple cases, where
each case has a value.
 The value inside the parenthesis of a switch statement expression is
tested for equality against the value of each case.
 The case with a value matching to the value of the switch statement
expression is executed.
 A break statement ends the switch case. The optional default case is for
when the variable does not equal any of the cases
Syntax:
switch(expression)
{
case expression 1: statement 1;
break;
case expression 2: statement 2;
break;
-----
-----
case expression n: statement n;
break;
default: statement;
}

2. Loop Control Statements/Iterative Statements:


Loop control statements are used when a section of code may either be
executed a fixed number of times or while some condition is true.
 While Loop:
This loop is useful to execute a group of statements repeatedly as
long as a condition is true. Once the condition becomes false, the
loop terminates.
The while tests the condition before executing any of the
statements within the while loop.
Firstly a compiler check the condition, if the condition is true then
control goes inside the while loop and executes the statement. If
the condition of while loop is false then control goes out of the
while loop.
If the number of iteration is not fixed, it is recommended to use
while loop.
Syntax:
while(condition)
{
Block of statements;
Increment/decrement;
}
 do-while loop:
The do-while tests the condition after having executed the
statements within the loop.
This means that do-while would execute its statements at least
once, even if the condition fails for the first time.
This loop is useful to execute a group of statements repeatedly as
long as a condition true. Once the condition becomes false, the
loop terminates.
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.
Syntax:
do
{
Block of statements;
Increment/decrement;
}while(condition);

 for loop:
for loop is a control flow statement that iterates a part of the
programs multiple times.
The for loop allows us to specify three things about a loop in a
single line:
 Setting a loop counter to an initial(first)value.
 Testing the loop counter to decide whether its value has
reached the number of repetitions desired.
 Increment/Decrement the value of loop counter variable each
time when the program segment within the loop has been
executed.
If the number of iterations is fixed, it is recommended to use for
loop.
Syntax:
for(initialization;condition;increment/decrement)
{
Block of statement;
}
 Enhanced for loop/for each loop:
Enhanced for loop is useful when scanning an array. It is also
known as for each loop.
Note:
It is used to scan all elements of array. We cannot use enhanced for
loop for specific number of elements. If we need some specific
number of element then we have to use the standard for loop.
We can perform addition subtraction etc with elements using
enhanced for loop.
break and continue can control the behavior of enhanced for loop.
Syntax:
for(data_type variable_name:array_name)
{
//statements;
}

NESTED LOOPS:

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

Types of Nested Loops:

Nested while loop:


The nested while loop means any type of loop which is defined inside the
“while” loop.
Step 1: First, the compiler will check for the condition inside the first while
loop.
 If the condition is True, then statements inside the while loop will be
executed. It means the compiler will enter into second while loop: Go
to, Step 2.
 If the condition is False, then the compiler will exit from while Loop.

Step 2: Java compiler will check for the condition inside the second while loop
or nested while loop.

 If the condition is True, statements inside the second while loop will
execute. It means, it will execute from Statement 1 to N.
 If the condition is False, the compiler will exit from second while Loop.

Step 3: Once it exits from second while loop, the compiler will check for the
condition inside the while loop (repeating Step 1 )

Syntax:
while(condition)
{
while(condition)
{
//statement of first loop
}
//statement of second loop
}

Nested do-while loop:


The nested do-while loop means any type of loop which is defined inside the
“do-while” loop.
Step 1: First, the compiler will check for the condition inside the first do while
loop.

 If the condition is True, then statements inside the do while loop will be
executed. It means the compiler will enter into second do while loop: Go
to, Step 2.
 If the condition is False, then the compiler will exit from do while Loop.
Step 2: Java compiler will check for the condition inside the second do while
loop or nested do while loop.

 If the condition is True, statements inside the second do while loop will
execute. It means, it will execute from Statement 1 to N.
 If the condition is False, the compiler will exit from second do while Loop.

Step 3: Once it exits from second do while loop, the compiler will check for the
condition inside the do while loop (repeating Step 1 )

Syntax:
do
{
do
{
//statement of first loop
}while(condition);
//statement of second loop
}while(condition);

Nested for loop:


The nested for loop means any type of loop which is defined inside the ‘for’
loop.
Step 1: First, the compiler will check for the condition inside the first for loop.

 If the condition is True, then statements inside the For loop will be
executed. It means the compiler will enter into second For loop: Go
to, Step 2.
 If the condition is False, then the compiler will exit from For Loop.

Step 2: Java compiler will check for the condition inside the second for loop or
nested for loop.

 If the condition is True, statements inside the second For loop will
execute. It means, it will execute from Statement 1 to N.
 If the condition is False, the compiler will exit from second For Loop.

Step 3: Once it exits from second for loop, the compiler will check for the
condition inside the for loop (repeating Step 1 )

Syntax:
for(initialization;condition;increment/decrement)
{
for(initialization;condition;increment/decrement)
{
//statement of second loop
}
//statement of first loop
}

INFINITE LOOPS:

An infinite loop is a loop whose condition is always true. As a result, it keeps


executing its body forever, until you stop manually.

Infinite while Loop Syntax:

while (true)

// statements

Infinite do-while Loop Syntax:

do

// statements
} while (true)

Infinite for Loop Syntax:

for( ; ; )

//statements

3. Branching/Jump Statements:
Branching statements in java are used to jump from a statement to
another statement, thereby the transferring the flow of execution.
 Break:
The break statement in java is used to terminate a loop and break
the current flow of the program.
Syntax:
break;
Unlabeled break: It break the inner loop when the if condition meet it doesn't
break outer loop.
Labeled break: It break the inner loop as well as outer loop if the condition
meet.
 Continue:
To jump to the next iteration of the loop, we make use of the
continue statement. This statement continues the current flow of
the program and skips a part of the code at the specified condition.
Syntax:
continue;
Unlabeled continue:It skip the inner loop when the if condition meet it doesn't
skip outer loop.
labeled continue:It skip the inner loop as well as outer loop if condition is
meet.

Array:
An array is a collection of similar data types. It is also known as static data
structure because size of an array must be specified at the time of its
declaration. Index of array starts from zero to size-1.
Types of Array:
Single-Dimensional Array:
In single-dimensional array data elements are stored in a single row or a single
column.
Syntax:
1st way:
int array_name[]=new int[5];
array_name[0]=1;
array_name[1]=2;
array_name[2]=3;
array_name[3]=4;
array_name[4]=5;
2nd way:
int array_name[]={1,2,3,4,5};
Two-Dimensional Array:
In multi-dimensional array data are stored in a multiple rows and multiple
columns.
1st way:
int array_name[][]=new int[3][4];
array_name[0][0]=11;
array_name[0][1]=22;
array_name[0][2]=33;
array_name[0][3]=44;
array_name[1][0]=55;
array_name[1][1]=66;
array_name[1][2]=77;
array_name[1][3]=88;
array_name[2][0]=1;
array_name[2][1]=2;
array_name[2][2]=3;
array_name[2][3]=4;
2nd way:
int array_name[][]={{11,22,33,44},{55,66,77,88},{1,2,3,4}};

String:
String is a sequence of characters. But in Java, string is an object that represents
a sequence of characters. The java.lang.String class is used to create a string
object.

In java, string objects are immutable. Immutable simply means unmodifiable


or unchangeable. Once string object is created its data or state can't be changed
but a new string object is created.

The java.lang.String class implements Serializable, Comparable and


CharSequence interfaces..

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters.


String, StringBuffer and StringBuilder classes implement it. It means, we can
create strings in Java by using these three classes.
Two ways to create String object:

1. By string literal:

Java String literal is created by using double quotes.

For Example:

String s="welcome";

Only one object is created in SCP area and s is pointing to that object.

SCP Area

welcome
s

What is SCP(String Constant Pool):

It is specially designed area for String Objects.

Rule For SCP:

Object creation in SCP is always optional. First JVM will check is there any
object already present in SCP with required content. If object already present
then existing object will be reused. If object not available then only one object
is created. This rule is applicable only for SCP area but not for the Heap.

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it
already exists in the string constant pool).

2. By new keyword

String s=new String("Welcome");


In this two objects will be created one in heap area and the other object in String
Constant Pool(SCP) and s is pointing to the heap object.
Heap Area SCP Area
welcome
S welcome
Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference
variables,all referes to one object. If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string objects are
immutable in java.
For Example:

class Testimmutablestring
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed
but a new object is created with sachintendulkar. That is why string is known as
immutable.

As you can see in the above figure that two objects are created but s reference
variable still refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin


Tendulkar" object.
For Example:

class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar

In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object
is not modified.

String Class Methods:


Method Description
char charAt(int index) Returns the character at the specified
index.
String concat(String str) Concatenates the specified string to the
end of this string.
boolean equals(Object anObject) Compares this string to the specified
object.
boolean equalsIgnoreCase(String Compares this String to another String,
anotherString) ignoring case considerations.
byte getBytes() Encodes this String into a sequence of
bytes using the platform's default
charset, storing the result into a new
byte array.
int indexOf(int ch) Returns the index within this string of
the first occurrence of the specified
character.
int indexOf(int ch, int fromIndex) Returns the index within this string of
the first occurrence of the specified
character, starting the search at the
specified index.
int lastIndexOf(int ch) Returns the index within this string of
the last occurrence of the specified
character.
int lastIndexOf(int ch, int fromIndex) Returns the index within this string of
the last occurrence of the specified
character, searching backward starting at
the specified index.
int length() Returns the length of this string.
String replace(char oldChar, char Returns a new string resulting from
newChar) replacing all occurrences of oldChar in
this string with newChar
char[] toCharArray() Converts this string to a new character
array.
String toLowerCase() Converts all of the characters in this
String to lower case using the rules of
the default locale.
String toUpperCase() Converts all of the characters in this
String to upper case using the rules of
the default locale.
String trim() Returns a copy of the string, with
leading and trailing whitespace omitted.

StringBuffer:

Java StringBuffer class is used to create mutable (modifiable) String objects.


The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed. Java StringBuffer class is thread-safe i.e. multiple threads
cannot access it simultaneously. So it is safe and will result in an order.
StringBuffer methods are synchronized.

Note: Its intial capacity is 16.

For Example:

StringBuffer s=new StringBuffer(“welcome”);

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of


16.

StringBuffer(String It creates a String buffer with the specified string..


str)
StringBuffer(int It creates an empty String buffer with the specified capacity
capacity) as
length.

Important methods of StringBuffer class


Modifier Method Description
and Type

public append(String s) It is used to append the specified


synchronized string
StringBuffer
with this string. The append()
method is overloaded like
append(char),
append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, String s) It is used to insert the specified


synchronized
string with this string at the
StringBuffer
specified position. The insert()
method is overloaded
like insert(int, char), insert(int,
boolean), insert(int, int), insert(int,
float), insert(int, double) etc.

public replace(int startIndex, int It is used to replace the string from


synchronized endIndex, String str) specified startIndex and endIndex.
StringBuffer

public delete(int startIndex, int It is used to delete the string from


synchronized endIndex) specified startIndex and endIndex.
StringBuffer
public reverse() is used to reverse the string.
synchronized
StringBuffer

public int capacity() It is used to return the current


capacity.

public void ensureCapacity(int It is used to ensure the capacity at


minimumCapacity) least
equal to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the


string i.e. total number of characters.

public String substring(int beginIndex) It is used to return the substring from


the specified beginIndex.

public String substring(int beginIndex, int It is used to return the substring from
endIndex) the
specified beginIndex and endIndex.

StringBuilder:

Java StringBuilder class is used to create mutable (modifiable) String. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized, which means it is not thread safe i.e. multiple threads can access
it simultaneously. Its because StringBuilder methods are not synchronised.

Note: Its intial capacity is 16.

For Example:
StringBuilder s=new StringBuilder(“welcome”);

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity


of 16.

StringBuilder(String It creates a String Builder with the specified string.


str)

StringBuilder(int It creates an empty String Builder with the specified


length) capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder It is used to append the specified string with this


append(String s) string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

public StringBuilder It is used to insert the specified string with this string
insert(int offset, String s) at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

public StringBuilder It is used to replace the string from specified


replace(int startIndex, int startIndex and endIndex.
endIndex, String str)

public StringBuilder It is used to delete the string from specified startIndex


delete(int startIndex, int and endIndex.
endIndex)
public StringBuilder It is used to reverse the string.
reverse()

public int capacity() It is used to return the current capacity.

public void It is used to ensure the capacity at least equal to the


ensureCapacity(int given minimum.
minimumCapacity)

public char charAt(int It is used to return the character at the specified


index) position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int It is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.

Difference between StringBuffer and StringBuilder


StringBuffer StringBuilder

StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e. not


safe. It means two threads can't call the thread safe. It means two threads can call
methods of StringBuffer simultaneously. the methods of StringBuilder
simultaneously.

StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

CLASS:
The class is user-defined data structure that binds the variables and methods into
a single unit. Class is a blueprint or code template for object creation. Using a
class, you can create as many objects as you want.
Syntax:
modifier_class_class _name
{
data_ type variable_ name; //instance variable
static_data_ type variable_ name; //static variable
modifier_return_type method_name() //instance method
{
data_type variable_name; //local variable
Body of method
}
modifier static return_type method_name() //static method
{
Body of method
}
}
Here,
class keyword: class keyword is used to create class.
Class name: The name should begin with an initial letter(capitalized by
convention)
Types of Classes:

There are six types of classes in Java:

1. Static Class
2. Final Class
3. Abstract Class
4. Concrete Class
5. POJO Class
6. Inner Class

POJO CLASS:
In Java, POJO stands for Plain Old Java Object. A Java class that contains
only private variables, setter and getter is known as POJO class. It is used to
define Java objects that increase the reusability and readability of a Java
program. The class provides encapsulation. It is widely used in Java because it
is easy to understand these classes.

Example:

class PojoDemo
{
//private variable
private double price=89764.34;
//getter method
public double getPrice()
{
return price;
}
//setter method
public void setPrice(int price)
{
this.price = price;
}
}
//main class
public class PojoClassExample
{
public static void main(String args[])
{
PojoDemo obj = new PojoDemo();
System.out.println("The price of an article is "+ obj.getPrice()+" Rs.");
}
}
Output:

The price of an article is 89764.34 Rs.

Object class

The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object.
The Class class can further be used to get the
metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of
CloneNotSupportedException this object.

public String toString() returns the string representation of this


object.

public final void notify() wakes up single thread, waiting on this


object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.

public final void wait(long causes the current thread to wait for the
timeout)throws
specified milliseconds, until another thread
InterruptedException
notifies (invokes notify() or notifyAll()
method).

public final void wait(long causes the current thread to wait for the
timeout,int nanos)throws
specified milliseconds and nanoseconds,
InterruptedException
until
another thread notifies (invokes notify() or
notifyAll() method).

public final void wait()throws causes the current thread to wait, until
InterruptedException another
thread notifies (invokes notify() or
notifyAll()
method).

protected void finalize()throws is invoked by the garbage collector before


Throwable object is being garbage collected.

toString() method:

If you want to represent any object as a string, toString() method comes into
existence or simply we can say converting any object in string.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method
on the object. So overriding the toString() method, returns the desired output, it
can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of
the object, so we don't need to write much code.

Understanding problem without toString() method


class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[])
{
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the
objects but I want to print the values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified values.

Example of Java toString() method

class Student
{
int rollno;
String name;
String city;

Student(int rollno, String name, String city)


{
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString() //overriding the toString() method
{
return rollno+" "+name+" "+city;
}

public static void main(String args[])


{
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}

Output:
101 Raj lucknow
102 Vijay ghaziabad

OBJECT:
An object is an instance of a class. It is a collection of variables and methods.
We use the object of a class to perform actions.
An object is a real-world entity which has a state(variables) and
behaviour(methods).

Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
Syntax:
class_name object_name=new class_name();
Accessing class member using object:
Object_name.variable_name=value;
Accessing method using object:
object_name.method_name();
ACCESS SPECIFIERS:

Access specifier or modifier is the access type of the method. It specifies the
visibility of the method.

Types of access specifier:

o Public: When we use public access specifier, the method is accessible by


all classes in our application.
o Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
o Protected: When we use a protected access specifier, the method is
accessible within the same package or subclasses in a different package.
o 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.

Access within within outside package by outside package


Modifier class packag subclass only
e

Private Y N N N

Default Y Y N N

Protect Y Y Y N
ed

Public Y Y Y Y

METHOD:

Method describe behavior of an object. A method is a collection of statements


that are group together to perform an operation.

TYPES OF METHODS:

Pre-defined Methods:
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.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(),


print(), and max(). We have used these methods directly without declaration
because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is
a method of the Math class that returns the greater of two numbers.

User defined Methods:

The method written by the user or programmer is known as a user-


defined method. These methods are modified according to the requirement.

Types of user defined methods:

1. Non-Static/Instance Method:
Non-static method belongs to object of class.

Non-static methods can be invoked/called by creating object of the class.

Non-static method is not required to have any special keyword.

Non-static method can access non-static data members(variables) and non static
methods of another class or same class as well as static data members(variables)
and static methods.

Syntax:

Access_specifier return_type method_name(parameter_list)

//method body;

Here,

Access Specifier: Access specifier or modifier is the access type of the method.
It specifies the visibility of the method.

Return Type: Return type is a data type that the method returns. It may have a
primitive data type int, float, double, char, string, 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.

Note:
Parameter: Parameter is variable defined by a method that receives value when
the method is called. Parameter are always local to the method they don’t have
scope outside the method.

Argument: Argument is a value that is passed to a method when it is called.

2. Static Method/Class method:

Static method belong to class.

Static method can be invoked/called directly by class name.

Static method is declared using static keyword.

Static method can access only static data members(variables) and static methods
of another class or same class but cannot access non-static methods and
variables.

Syntax:

modifier static return_type method_name(parameter_list)

//method body;

CONSTRUCTOR:

Constructor is a special type of method that is used to initialize the instance


variables of the class. It is called/invoked when the instance of the class is
created, and the memory is allocated for the object.

It is called constructor because it constructs the values at the time of object


creation.

Rules for constructor:

Constructor must has same name as the name of the class.


Constructor does not have any return type like void.

Constructor cannot be abstract, static, final, and synchronized.

Need of constructor:

In short, we use the constructor to initialize the instance variable of the


class.

Constructor is the first method that is invoke when you create an object.
Suppose that we have class of Employees. If we have to include name and id of
each one then for that we have to initialize each variable every time whenever
any new employee is added. But there is problem in this approach i.e., if we
have 1000’s of the employee then there variables need to declare 1000’s time.

Example:
public class Employee
{
String name;
int id;
public static void main(String[] args)
{
Employee c=new Employee();
c.name="ram"; //similarly we have to do for 1000's of the employee
c.id=101; //similarly we have to do for 1000's of the employee
System.out.println("Name is "+c.name);
System.out.println("id is "+c.id);
}
}

Output:
Name is ram
id is 101

But this is not an efficient approach because it consumes more time and sign of
bad programming. For this problem we have solution that is constructor.

Program for constructor in java:


public class Employee
{
String name;
int id;
Employee(String name,int id)
{
this.name=name;
this.id=id;
System.out.println("Name="+name);
System.out.println("Id="+id);
}
public static void main(String[] args)
{
Employee e1=new Employee("Ram",10);//by this we can initialize many
of the employees
Employee e2=new Employee("Rahul",20);
}
}

Output:
Name=Ram
Id=10
Name=Rahul
Id=20

So constructor are used to assign values to the class variable at the time of
object creation, either done by the programmer or by java itself (default
constructor).

Types of Constructor:

Default Constructor:

Default Constructors are the type of constructors which are not created by the
programmers during the program. But whenever any object is created, the
compiler by itself create an default constructor. Every time an object is created
using the new() keyword , at least one constructor is called. It calls a default
constructor if there is no constructor available in the class.

Note: Default constructor is only created by the complier if it is not created by


programmer.

What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.

Example:
public class Employee
{
String name;
int id;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String[] args)
{
Employee e1=new Employee();
Employee e2=new Employee();
e1.display();
e2.display();
}
}

Output:
0 null

0 null

no-args constructor:

It is the type of the constructor which is created by the programmer by itself


with no arguments. It is also called as the no argument constructor.

Example:
public class Employee
{
int a=10;
Employee()//constructor with no arguments
{
System.out.println(a);
System.out.println("I am user defined constructor");
}
public static void main(String[] args)
{
Employee e1=new Employee();
}
}

Output:
10

I am user defined constructor


Parameterized Constructor:

A constructor that has parameters is known as parameterized constructor. We


can initialize the class variables by own value.

Example:
public class Employee
{
String name;
Employee(String fname)
{
name=fname;
System.out.println(name);
}
public static void main(String[] args)
{
Employee e1=new Employee("mayuri");
}
}

Output:
mayuri

Copy Constructor:

There is no copy constructor in java. However, we can copy the values from one
object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They
are:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

By Constructor

//Java program to initialize the values from one object to another


class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n)
{
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan

By assigning the values of one object into another

class Student7
{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7()
{
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan

Can you make a constructor final?


No, a constructor can’t be made final.
A final method cannot be overridden by any subclasses.
In other words, constructors cannot be inherited in Java therefore, there is no
need to write final before constructors.

CONSTRUCTOR OVERLOADING:
A class can have multiple constructors, as long as they differ in their parameter
list (signature). You can define as many constructors as you need. This is called
as Constructor overloading.

CONSTURTCOR CHANING:
You can call one constructor from another one within same class or of its
subclasses. This is known as Constructor Chaining.

Need of Constructor Chaining

Suppose, there are five tasks to perform. There are two ways to perform these
tasks, either implement all the tasks in a single constructor or create separate
tasks in a single constructor.

By using the constructor chaining mechanism, we can implement multiple tasks


in a single constructor. So, whenever we face such types of problems, we should
use constructor chaining. We can make the program more readable and
understandable by using constructor chaining.

Rules of Constructor Chaining


o An expression that uses this keyword must be the first line of the
constructor.
o Order does not matter in constructor chaining.
o There must exist at least one constructor that does not use this

Constructor Calling form another Constructor

The calling of the constructor can be done in two ways:

o By using this() keyword: It is used when we want to call the current


class constructor within the same class.
o By using super() keyword: It is used when we want to call the
superclass constructor from the base class.

Note: In the same constructor block, we cannot use this() and super()
simultaneously.

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose the behavior


state of an object. of an object.

A constructor must not have a return A method must have a return type.
type.
The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

The constructor name must be same as The method name may or may not be
the class name. same as class name.

Constructors are not inherited. Methods are inherited.

GARBAGE COLLECTOR:

When there is no reference to an object, then that object is assumed to be no


longer needed and the memory occupied by the object are released. This
technique is called Garbage Collection. In Java destruction of object from
memory is done automatically by the JVM.

Advantages of Garbage Collection

1.Programmer doesn't need to worry about dereferencing an object.

2.It is done automatically by JVM.

3.Increases memory efficiency and decreases the chances for memory leak.

finalize() method

Sometime an object will need to perform some specific task before it is


destroyed such as closing an open connection or releasing any resources held.
To handle such situation finalize() method is used. finalize() method is called by
garbage collection thread before collecting object. Its the last chance for any
object to perform clean-up utility.

Signature of finalize() method

Important Points to Remember

 finalize() method is defined in java.lang.Object class, therefore it is available


to all the classes.

 finalize() method is declare as protected inside Object class.


 finalize() method gets called only once by a Daemon thread named GC
(Garbage Collector)thread.

gc() Method

gc() method is used to call garbage collector explicitly. However gc() method
does not guarantee that JVM will perform the garbage collection. It only request
the JVM for garbage collection. This method is present in System and Runtime
class.

PACKAGE:

A java package is a group of similar types of classes, interfaces and sub-


packages.

Types of Packages in Java

1. Built-in Packages
2. User Defined Packages

Built-in Packages

Built-in packages or predefined packages are those that come along as a part
of JDK (Java Development Kit) to simplify the task of Java programmer. They
consist of a huge number of predefined classes and interfaces that are a part of
Java API’s. Some of the commonly used built-in packages are java.lang, java.io,
java.util, java.applet, etc.

User Defined Packages

User-defined packages are those which are developed by users in order to group
related classes, interfaces and sub packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


How to access package from another package?

There are two ways to access the package from outside the package.

1. import packagename.*;
2. import packagename.classname;

Subpackage:

A package defined inside another package is known as sub package. It should


be created to categorize the package further.

Let's take an example, Sun Microsystem has defined a package named java that
contains many classes like String, Reader, Writer,etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation.
So, Sun has subcategorized the java package into subpackages such as io etc.
and put the Input/Output related classes in io package.

To import all classes of a sub package:

import packagename.subpackagename.*;

To import specific class of a sub package:

import packagename.subpackagename.classname;

INHERIATANCE:

Java inheritance refers to the ability of a Java Class to inherit the properties
from some other Class.

When you inherit from an existing class, you can reuse variables/field and
methods of the parent class. Moreover, you can add new methods and fields in
your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.
Inheritance gives Java the cool capability of re-using code, or sharing code
between classes.

The Class that extends or inherits is called a subclass/derived class.

The Class that is being extended or inherited is called a superclass/base class.

Extends keyword are used to describe inheritance in Java.

Types of inheritance:

 Single Inheritance:

When a sub class inherits one super another class, it is known as a single
inheritance.

For example: Son class inherits Father class.

 Multilevel Inheritance:

When there is a chain of inheritance, it is known as multilevel inheritance.

For example: Grandson class inherits Son class which inherits Father class.

 Hierarchical Inheritance:

When two or more classes inherits a single class, it is known as hierarchical


inheritance.

For example: Son and Daughter class inherits Father class.

Why multiple inheritance is not supported in Java

 To remove ambiguity.

Consider a case where class B extends class A and class C and both class have
same method display().

Now java compiler cannot decide, which display method it should inherit. To
prevent such situation, multiple inheritance is not allowed in java.
 To provide more maintainable and clear design.

AGGREGATION(HAS-A Relationship):
Aggregation means making a relationship or association between two classes.
In Java, aggregation represents HAS-A relationship, which means when a class
contains reference of another class is known has aggregation.

Aggregation is a term which is used to refer one way relationship between two
objects.

For Example:

Consider two classes Student and Address. Each student has own address that
makes has-a relationship but address has student not makes any sense.

When to use Aggregation and Inheritance?


Aggregation:
When you just want to use the properties and objects of another class without
modifying them, then Aggregation can be used.
Inheritance:
If you want to use and modify the properties and objects of another class, then
inheritance can be used.

this keyword in Java:

There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current class object.

Usage of Java this keyword

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly).
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
super Keyword in Java:

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

final keyword:

final is a special keyword in Java that is used as a non-access modifier. A final


keyword can be used in different contexts such as:

 final variable

When the final keyword is used with a variable then its value can’t be changed
once assigned. In case the no value has been assigned to the final variable then
using only the class constructor a value can be assigned to it.

 final method

When a method is declared final then it can’t be overridden by the inheriting


class.

 final class

When a class is declared as final in Java, it can’t be extended by any subclass


class but it can extend other class.
What is difference between static and final:
BASIS FOR
STATIC FINAL
COMPARISON

Applicable Static keyword is applicable to nested Final keyword is applicable to

static class, variables, methods and class, methods and variables.

block.

Initialization It is not compulsory to initialize the It is compulsory to initialize

static variable at the time of its the final variable at the time

declaration. of its declaration.

Modification The static variable can be reinitialized. The final variable cannot be

reinitialized.

Methods Static methods can only access the static Final methods cannot be

members of the class, and can only be inherited.

called by other static methods.

Class Static class's object cannot be created, A final class cannot be

and it only contains static members inherited by any class.

only.

Block Static block is used to initialize the Final keyword supports no

static variables. such block.


POLYMORPHISM:

Polymorphism in Java is a concept by which we can perform a single action


in different ways. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

Types of polymorphism:

Compile-time-polymorphism:

Whenever an object is bound with their functionality at the compile-time, this


is known as the compile-time polymorphism. At compile-time, java knows
which method to call by checking the method signatures. So this is called
compile-time polymorphism or static or early binding. Compile-time
polymorphism is achieved through method overloading.

Method-Overloading:

If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading. That means we are overloading the same
name method again again.

For a method to be overloaded in java must follow any one of the condition:

1. Number of parameters should be different.

2. Sequence of parameters should be different.

3. Data Type of parameters should be different.

Can we overload static methods?


The answer is ‘Yes’. We can have two or more static methods with the same
name, but differences in input parameters.

Can we overload methods that differ only by static keyword?


We cannot overload two methods in Java if they differ only by static keyword
(number of parameters and types of parameters is the same).

Runtime polymorphism:

Run-time polymorphism is the process of calling the overridden method through


the reference variable of superclass. It is also known as the Dynamic Binding.
In this overridden methods are resolved at Run-time rather then the compile
time. Run-time polymorphism in java is achieved by method-overriding.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:

class A{}
class B extends A{}
A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface
type. For Example:

interface I{}
class A{}
class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A
Object.

Method Overriding:

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

For a method to be overloaded in java must have following condition:

1. Number of parameters should be same.

2. Sequence of parameters should be same.


3. Types of parameters should be same.

4. There must be IS-A relationship(Inheritance).

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime


polymorphism, so we will learn it later.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to
the heap area.

Can we override java main method?

No, because the main is a static method.

In Java, private method overriding is possible?

No, we cannot override private in Java.


Because Private methods in Java are not visible to any other class which limits
their scope to the class in which they are declared.
What is the difference between static binding and dynamic binding?

In case of the static binding, the type of the object is determined at compile-time
whereas, in the dynamic binding, the type of the object is determined at runtime.

ABSTRACTION:

Abstraction is a general concept that denotes the progress of modelling real


things into programming language. Hence interfaces and abstract classes are
just two techniques used in this progress.

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract/concrete methods. It needs to be extended and its
method to be implemented. It cannot be instantiated.

Points to Remember:
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static concrete methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
o An abstract class can extends another abstract class without providing the
internal logic of the abstract methods of the abstract class it has extended.
o An abstract class can implements an interface and it doesn't need to
provide an implementation of the methods of an interface.

Example of abstract class

abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

Points to Remember:
o An abstract method can only set a visibility modifier, one of public or
protected.
o It is necessary that an abstract method must have abstract class but
abstract class can have abstract as well as concrete methods.

Example of abstract method

abstract void printStatus();//no method body and abstract


Can you use abstract and final both with a method?
No, we have to implement abstract. Final cannot be overridden.
When to Use Abstract Classes

 We want to encapsulate some common functionality in one place (code reuse)


that multiple, related subclasses will share.

 We need to partially define an API that our subclasses can easily extend and
refine

 The subclasses need to inherit one or more common methods or fields with
protected access modifiers

Abstract Class Concrete Class


Abstract class can have both abstract A concrete class can only have
as well as concrete methods. concrete methods.
Abstract class cannot be instantiated Concrete class can be instantiated
using new keyword. using new keyword.
Abstract class cannot be declared as a Concrete class can be declared final.
final class.
Abstract class declared using abstract Concrete class is not having abstract
keyword. keyword during declaration.
Example:

abstract class Animal

abstract void eat();


abstract void walk();

abstract void color();

void sleep

System.out.println(“Sleeping…..”);

INTERFACE:

Interface is similar to class which specify that what a class must do but not
explain how to do. It also contains methods and variables. Some of the
important points about interface:

1.By default all the methods are public and abstract and by default compiler put
public static final before fields/variables.

2.interface keyword is used to declare Interface.

3.Interface provide total abstraction.

4.Implement keyword is used for the implementing of interface.

5.Any class which implements the interface must need to implement all the
abstract methods declared in interface.

6.We can’t create the object of the interface.

7.Multiple Inheritance can be implemented by interface.

8.Since Java 8, interface can have default and static methods

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Class Interface

The keyword used to create a class The keyword used to create an


is “class” interface is “interface”

A class can be instantiated i.e, An Interface cannot be instantiated


objects of a class can be created. i.e, objects cannot be created.

Classes does not support multiple Interface supports multiple


inheritance. inheritance.

It can be inherited by a class by using


the keyword ‘implements’ and it can
It can be inherited by another class be inherited by an interface using the
using the keyword ‘extends’. keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class


can be declared using any access All variables and methods in a
specifier(public, private, default, interface are declared as public static
protected) final.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.
3) Abstract class can have final, static and Interface has only static and final variables.
instance variables.

4)Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }
Java Nested Interface

An interface i.e. declared within another interface or class is known as nested


interface. The nested interfaces are used to group related interfaces so that they
can be easy to maintain. The nested interface must be referred by the outer
interface or class. It can't be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java
programmer.
o Nested interface must be public if it is declared inside the interface but it
can have any access modifier if declared within the class.
o Nested interfaces are declared static implictly.

Syntax of nested interface which is declared within the interface


interface interface_name{
...
interface nested_interface_name{
...
}
}
Example:
//nested interface which is declared within the interface
package inner_classes;
interface Showable
{
void msg();
interface Message
{
void msg();
}
}
class NestedInterface implements Showable.Message
{
public void msg()
{
System.out.println("Hello Nested Interface");
}
}
public class Pratical_7
{
public static void main(String[]args)
{
Showable.Message m=new NestedInterface();
m.msg();
}
}
Explanation:
As you can see in the above example, we are accessing the Message interface
by its outer interface Showable because it cannot be accessed directly. It is just
like the almirah inside the room; we cannot access the almirah directly because
we must enter the room first. In the collection framework, the sun microsystem
has provided a nested interface Entry. Entry is the subinterface of Map, i.e.,
accessed by Map.Entry.
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example:
//nested interface which is declared within the class
package inner_classes;
class A
{
interface Message
{
void msg();
}
}
class NestedInterface1 implements A.Message
{
public void msg()
{
System.out.println("Hello Nested Interface");
}
}
public class Pratical_8
{
public static void main(String[]args)
{
A.Message m=new NestedInterface1();
m.msg();
}
}
Can we define a class inside the interface?

Yes, If we define a class inside the interface, java compiler creates a static
nested class. Let's see how can we define a class within the interface:

interface M{
class A{}
}

ENCAPSULATION:

Encapsulation in java is a mechanism of wrapping of data(variables) and code


acting on the data(methods) together as a single unit.
Steps to achieve encapsulation:
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the
variables values.
In encapsulation, the variables of a class will be hidden from other classes, and
can be accessed only through the method of their current class. This concept is
known as Data Hiding.
When to use Encapsulation:
Whenever you want get or set the data individually.

Abstraction vs Encapsulation in Java:

 In abstraction, we hide the details while in encapsulation we hide the data.

 i.e. abstraction is the implementation hiding process while the encapsulation is


Information hiding process.

 The role of encapsulation in Java is to group together the data and methods
which are acting upon the data while abstraction exposes the interface to a user
while hiding the details of implementation.
Encapsulation is done based on abstraction. Imagine you are building a house.
The house is made by bricks. Abstraction is the bricks and encapsulation is the
house.

MULTITHREADING:

Thread:

A thread is the smallest unit of processing. It is also lightweight.

Process:

A process is consist of multiple thread. It is group of threads.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:

Process-based Multitasking (Multiprocessing)

o It is a process of executing multiple processes simultaneously.


o Each process has an address in memory.
o In other words, each process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the processes is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

Thread-based Multitasking (Multithreading)

o It is a process of executing multiple threads simultaneously.


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception


occurs in a single thread.

Process Thread
A process is consist of multiple A thread is the smallest unit of
thread. processing.
Process is heavyweight. Thread is lightweight.
Switching from one process to Switching one thread to another takes
another takes more time. less time.
Each process has different address Thread shares same address space.
space.
Process are not dependent on each Thread are dependent on each other.
other.
How threads are created in java:

Threads are created in java using following classes:

1. Thread (abstract class)

2. Runnable (interface)

Thread class:
Thread class provide constructors and methods to create and perform operations
on a thread. Thread class extends Object class and implements Runnable
interface.
Syntax:
public class Thread extends Object implements Runnable
Constructors of Thread class
 Thread(): It is the default constructor of Thread class. It is used to create
an object of the Thread class.
 Thread(Runnable target): It is a parameterized constructor of Thread
class which takes a parameter of Runnable. It creates an object like a
default constructor (Thread()). The parameter target is the object
whose run() method is invoked when the start get call().
 Thread(Runnable target, String name): It is parameterized constructor
that is used to create an object of Thread class. It takes two parameters
one is the Runnable type and another String type. It is similar to the
above-mentioned constructor except you can set the name of the thread.
 Thread(String name): It is a parameterized constructor that is used to
create an object of Thread class. It takes only one parameter
of String type. You can set the name of the thread to pass the parameter
Methods of Thread class:

Thread class has many methods that are used to perform some operations on
the thread. We can change the order and behaviours of thread by use of
methods.
 start(): This method is used to start the execution of the thread. It is very
frequently used in multithreading.
 run(): This method performs the action for a thread. It gets a call from
start() method.
 sleep(long millis)throws InterruptedException: It is used to sleep the
current thread for a specific time.
 yield(): The yield() method is used to give the hint to the thread
scheduler. If the current thread is not doing anything important and any
other threads need to be run, they should run. Otherwise, the current
thread will continue to run.
 join()throws InterruptedException: The join() method is used when we
want one thread to wait until another thread completes its execution.
 getName(): This method returns the name of the thread. It is a public and
final method. Its return type is String.
 setName(String name): This method is used to set the name of the
thread. It is a public, final and synchronized method. Its return type is
void it means it doesn’t return anything.
 isDaemon(): This method returns a boolean value either true or false.
This method is used to check whether the thread is daemon thread or not.
It is a public and final method. Its return type is boolean.
 setDaemon (boolean on): This method is used to set a thread as daemon
thread. You can mark any user thread as a daemon thread bypassing the
value true (setDaemon(true)) in a parameter. If I have a Daemon thread
and you can make it user thread bypassing the value false
setDaemon(false)).
 getPriority(): This method returns the priority of the thread. It is a public
and final method. Its return type is int.
 setPriority(int newPriority): This method is used to set the priority of a
thread. Its return type is void it means it doesn’t return anything.
 currentThread(): Returns the currently running thread. It is static
method.
 IsAlive: This method returns true if the thread is alive otherwise it returns
false.

How we start a thread


Ans: By calling start() method of thread class.
Note: At a time one thread is executed only.
How threads are executed in JVM
In java each thread has its own call stack.

The main thread:


When we run any java program, the program begins to execute its code starting
from the main method. Therefore, the JVM creates a thread to start executing
the code present in main method. This thread is called as main thread. Although
the main thread is automatically created, you can control it by obtaining a
reference to it by calling currentThread() method.
Two important things to know about main thread are:
 It is the thread from which other threads will be produced.
 main thread must be always the last thread to finish execution.

Java Thread Life Cycle States


The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
New: The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
Runnable: The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
Running: The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked): This is the state when the thread is still alive, but is
currently not eligible to run.
Terminated: A thread is in terminated or dead state when its run() method
exits.

Thread Priorities:
Every thread has a priority that helps the operating system determine the order
in which threads are scheduled for execution. In java thread priority ranges
between 1 to 10.
Note: The selection of the threads for execution depends upon the thread
scheduler which is platform dependent. So there is no guarantee even if you set
priority to maximum for any thread.
Synchronization in Java

Synchronization in java is the capability to control the access of multiple


threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent inconsistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.


Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor.


Every object has an lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Java synchronized method

If you declare any method as synchronized, it is known as synchronized


method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the


lock for that object and releases it when the thread completes its task.
Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific


resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize
only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work
same as the synchronized method.

Points to remember for Synchronized block


o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression)
{
//code block
}

Static Synchronization

If you make any static method as synchronized, the lock will be on the class not
on object.
Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock. But there can be interference between t1
and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another
lock. I want no interference between t1 and t3 or t2 and t4.Static
synchronization solves this problem.

Inter-Thread Communication:

Inter-thread communication or Co-operation is all about allowing


synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed. It is implemented by following
methods of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

This method causes the thread to wait until another thread invokes notify() and
notifyAll() methods for this object.

Method Description

public final void wait()throws waits until object is notified.


InterruptedException
public final void wait(long waits for the specified amount of
timeout)throws InterruptedException time.

2) notify() method

It is used to give the notification for only one thread which is waiting for
particular object.

Syntax:

public final void notify()

3) notifyAll() method

It is used to give the notification for all thread which is waiting for particular
object.

Syntax:

public final void notifyAll()

Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?

It is because they are related to lock and object has a lock.

EXCEPTION HANDLING:

The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that the normal flow of the application can be maintained.

Exception:

In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:

Compile-time Exception or Checked Exception:

When compiler can check the exceptions at the compile time that there are
certain exceptions which can occur at the compile time are called checked
exception.

Example: ClassNotFoundException, IOException, SQLException.

Runtime Exception or Unchecked Exception:

The exception which are not checked at the compile time those exception are
called runtime exception.
Example: ArithmeticException, IndexOutOfBoundException,
NullPointerException.

Error:

Error is irrecoverable.
Example: OutOfMemoryError, VirtualMachineError, AssertionError etc.

Difference between Exception and Error:

Exception Error
Exception occurs because of our Error occurs because of lack of
programs. system resources.
Exceptions are recoverable i.e. Errors are not recoverable i.e.
programmer can handle them using programmer can’t handle them to
try-catch block. their level.
Exception are of two types: Errors are only of one type:

1.compile time or checked exception. 1.Runtime or unchecked exception.

2.runtime or unchecked exception.

Ways to print error using exception object:

 printStackTrace(): Type of error, error message and location of error is


printed.

 getMessage(): Only error message will print.

 toString(): Type of error and error message will be printed

Java Exception Keywords

Java provides five keywords that are used to handle the exception.

try:
The "try" block contains the code which can throws exception. The try block
must be followed by either catch or finally. It means we can't use try block
alone.
catch:
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. It must be preceded
by try block which means we can't use catch block alone. You can use multiple
catch block with a single try block. It can be followed by finally block later.

finally:
The "finally" block is used to execute important code such as closing
connection, stream etc. It is executed whether an exception is handled or not. If
you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
Syntax of Java try-catch
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{

}
Syntax of try-finally block
try
{
//code that may throw an exception
}
finally
{

throw:

The “throw” keyword is mainly used to throw custom exception (user defined
exception).
We can throw either checked or unchecked exception in java by throw keyword.

The syntax of java throw keyword is given below.

throw exception;
Let's see the example of throw IOException.

throw new IOException("sorry device error);

Example:
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Java Custom Exception

If you are creating your own Exception that is known as custom exception or
userdefined exception. Java custom exceptions are used to customize the
exception according to user need. By the help of custom exception, you can
have your own exception and message. Let's see a simple example of java
custom exception.

Example:
package exception_handling;
class AgeException extends Exception
{
void showmsg()
{
System.out.println("Invalid age");
}
}
public class Assignment__67
{
public static void main(String[] args)
{
int age=17;
try
{
if(age<=18)
{
throw new AgeException();
}
}
catch(AgeException ae)
{
ae.showmsg();
}
}
}

throws:

The Java throws keyword is used to declare an exception. It gives an


information to the programmer that there may occur an exception so it is better
for the programmer to provide the exception handling code so that normal flow
can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there


occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code being
used.

Syntax of java throws

return_type method_name() throws exception_class_name

//method code

Q) Which exception should be declared

Ans) checked exception only, because:

unchecked Exception: under your control so correct your code.

error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack). It
provides information to the caller of the method about the exception.

Rule: If you are calling a method that declares an exception, you must either
caught or declare the exception.

There are two cases:

Case1: You caught the exception i.e. handle the exception using try/catch.

Case2: You declare the exception i.e. specifying throws with the method.

Difference between throw and throws:

Throw Throws
throw keyword is used to create an throws keyword is used to declare the
exception object manually i.e., by exception i.e., it indicates the caller
programmer. method that given type of exception
can occur so you have to handle it
while calling.
throw keyword is mainly used for throws keyword is mainly used for
runtime exceptions or unchecked compile time exception or checked
exception. exception.
In case of throw keyword we can In case of throws keyword we can
throw only single exception. declare multiple exception.

Ex:void readFile() throws


FileNotFoundException,
NullPointerException, etc.
throw keyword is used within the throws keyword is used with method
method. signature.
throw keyword is followed by new throws keyword is followed by class.
instance.
We can’t write any statement after throws keyword does not have any
throw keyword and thus it can be such rule.
used to break the statement.
Difference between final, finally and finalize:
Final Finally Finalize
Final is a keyword. Finally is a block. Finalize is a method.
Final is used to apply Finally is used to Finalize is used to
restrictions on class, method place important perform clean up
and variable. Final class code, it will be processing just before
can't be inherited, final executed whether object is garbage
method can't be overridden exception is handled collected.
and final variable value or not.
can't be changed.

What is Framework?
Framework is collection of pre-defined classes and interfaces.
What is the Collection framework in Java?

Collection Framework is a combination of classes and interface, which is used


to store and manipulate the data in the form of objects. It provides various
classes such as ArrayList, LinkedList,Vector, Stack, and HashSet, etc. and
interfaces such as List, Queue, Set, etc. for this purpose.

Hierarchy of Collection Framework

The java.util package contains all the classes and interfaces for the Collection
framework.
What are the main differences between array and collection?

Array and Collection are somewhat similar regarding storing the references of
objects and manipulating the data, but they differ in many ways. The main
differences between the array and Collection are defined below:

o Arrays are always of fixed size, i.e., a user can not increase or decrease
the length of the array according to their requirement or at runtime, but In
Collection, size can be changed dynamically as per need.
o Arrays can only store homogeneous or similar type objects, but in
Collection, heterogeneous objects can be stored.
o Arrays cannot provide the ?ready-made? methods for user requirements
as sorting, searching, etc. but Collection includes readymade methods to
use.

Explain various interfaces used in Collection framework?

Collection framework implements various interfaces, Collection interface and


Map interface (java.util.Map) are the mainly used interfaces of Java Collection
Framework. List of interfaces of Collection Framework is given below:

1. Collection interface: Collection (java.util.Collection) is the primary


interface, and every collection must implement this interface.
Syntax:

public interface Collection<E>extends Iterable

Where <E> represents that this interface is of Generic type

2. List interface: List interface extends the Collection interface, and it is an


ordered collection of objects. It contains duplicate elements. It also allows
random access of elements.

Syntax:

public interface List<E> extends Collection<E>

3. Set interface: Set (java.util.Set) interface is a collection which cannot


contain duplicate elements. It can only include inherited methods of Collection
interface.

Syntax:

public interface Set<E> extends Collection<E>

4. Queue interface: Queue (java.util.Queue) interface defines queue data


structure, which stores the elements in the form FIFO (first in first out).

Syntax:

public interface Queue<E> extends Collection<E>

Dequeue interface: it is a double-ended-queue. It allows the insertion and


removal of elements from both ends. It implants the properties of both Stack
and queue so it can perform LIFO (Last in first out) stack and FIFO (first in first
out) queue, operations.

Syntax:

public interface Dequeue<E> extends Queue<E>

5. Map interface: A Map (java.util.Map) represents a key, value pair storage of


elements. Map interface does not implement the Collection interface. It can only
contain a unique key but can have duplicate elements. There are two interfaces
which implement Map in java that are Map interface and Sorted Map.
What is the difference between Iterator and ListIterator?

Iterator traverses the elements in the forward direction only whereas ListIterator
traverses the elements into forward and backward direction.

Iterator ListIterator

The Iterator traverses the elements ListIterator traverses the elements in


in the forward direction only. backward and forward directions both.

The Iterator can be used in List, Set, ListIterator can be used in List only.
and Queue.

The Iterator can only perform ListIterator can perform ?add,? ?


remove operation while traversing remove,?
the collection. And ?set? operation while traversing
the collection.

What is the difference between List and Set?

List Set
List can contains duplicates elements. Set cannot contains duplicates
elements.
List is an ordered collection which Set is an unordered collection which
maintains the insertion order. does not maintains the insertion
order.
List interface contains a single legacy Set interface does not have any
class i.e is vector. legacy class.
List interface can allow multiple Set interface only allows a single null
number of null values. values.

What is the difference between ArrayList and Vector?


ArrayList Vector

ArrayList is not synchronized. Vector is synchronized.

ArrayList is not a legacy class. Vector is a legacy class.


ArrayList increases its size by 50% Vector increases its size by doubling
of the array size. the array size.
Newcapacity=(oldcapacity *
3)/2+1;

ArrayList is not thread-safe as it is Vector list is thread-safe as its every


not synchronized.
method is synchronized.

What is the difference between ArrayList and LinkedList?


ArrayList LinkedList

ArrayList uses a dynamic array. LinkedList uses a doubly linked list.

ArrayList is not efficient for LinkedList is efficient for


manipulation because too much is manipulation.
required.

ArrayList is better to store and LinkedList is better to manipulate


fetch data. data.

ArrayList provides random LinkedList does not provide random


access. access.

ArrayList takes less memory LinkedList takes more memory


overhead as it stores only object overhead, as it stores the object as
well as the address of that object.

What is the difference between HashSet and TreeSet?


HashSet TreeSet
HashSet does not maintains order. TreeSet maintains ascending order.
HashSet allow one null value. TreeSet does not allow null value.

What is the difference between Set and Map?


Set Map
Set contains only values. Map contains key and values.
Set contains unique values. Map can contains unique keys with
duplicate values.
Set contains only one null value. Map contains only one null key with
multiple null values.

What is the difference between HashSet and HashMap?


HashSet HashMap
HashSet contains only values. HashMap includes the entry (key,
value).
HashSet cannot have any duplicate HashMap can contain unique keys
values. with duplicate values.
HashSet contains the only one null HashMap contains one null key with
value multiple null values.

What is the difference between HashMap and TreeMap?


HashMap TreeMap
HashMap maintains no order. TreeMap maintains ascending order.
HashMap can be sorted by Key or TreeMap can be sorted by Key.
value.
HashMap contain a one null key with TreeMap cannot hold a null key but
multiple null values
can have multiple null values.

What is the difference between Collection and Collections?


Collection Collections
Collection is an interface. Collections is a class.
Collection interface is used for Collections class is used for sorting
storing and manipulating data. data.

What is the difference between Comparable and Comparator?


Comparable Comparator

Comparable use for single sorting Comparator use for multiple sorting (as we
create new class for sorting)
It provides one method named It provides one method named compare()
compareTo() and compareTo() method and compare()method having two parameter
having only one parameter as a object. as a object.

It is present in java.lang package. It is present in java.util package.

When we use comparable interface it Comparator does not affect original class as
affects original class. we create new class for it.

Collections.sort()method have only one Collections.sort()method have two object one


object as a list. as a list and second as comparator class obj.

What is API

API (Application programming interface) is a document that contains a


description of all the features of a product or software. It represents classes and
interfaces that software programs can follow to communicate with each other.
An API can be created for applications, libraries, operating systems, etc.

JDBC

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect
and execute the query with the database. JDBC API uses JDBC drivers to
connect with the database.

We can use JDBC API to access tabular data stored in any relational database.
By the help of JDBC API, we can insert, update, delete and fetch data from the
database.

The current version of JDBC is 4.3. It is the stable release since 21st September,
2017. It is based on the X/Open SQL Call Level Interface. The java.sql package
contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on
the server) that convert requests from Java programs to a protocol that the
DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the
query with the database. But, ODBC API uses ODBC driver which is written in
C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).

We can use JDBC API to handle database using Java program and can perform
the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Java Database Connectivity Steps:


Throws SQLException or either use try-catch

Step 1: Register the Driver class:

The forName() method of the Class class is used to register the driver class.
This method is used to load the driver class dynamically.

Example:

Class.forName(“com.mysql.jdbc.Driver”);

Step 2: Create the Connection object:

The getConnection() method of DriverManager class is used to establish the


connection with the database.

Example:

Connection
conn=DriverManager.getConnection(“jdbc:mysql://localhost/dbname”,
“username”, “password”);

Step 3: Create the Statement object:

The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with the
database.

Example:

Statement st=conn.createStatement();

Step 4: Execute the query:


The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get
all the records of a table.

Example:

ResultSet rs=st.executeQuery("select * from emp");


while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Step 5: Close the Connection object:

The close() method of Connection interface is used to close the connection.

By closing connection object statement and ResultSet will be closed


automatically.

Example:

conn.close();
Connection Interface

A Connection is the session between java application and database. It helps to


establish a connection with the database. An object of Connection can be used
to get the object of Statement, PreparedStatement and DatabaseMetaData.

Methods of Connection Interface:


Method Description
public Statement createStatement() creates a statement object that can be
used to execute SQL queries.
public Statement createStatement(int Creates a Statement object that will
resultSetType,int resultSetConcurrency) generate ResultSet objects with the given
type and concurrency.
public void setAutoCommit(boolean is used to set the commit status. By
status) default, it is true.
public void commit() saves the changes made since the
previous commit/rollback is permanent.
public void rollback() Drops all changes made since the
previous commit/rollback.
public void close() closes the connection and Releases a
JDBC resources immediately.

Statement Interface

The Statement Interface provides methods to execute static SQL queries with
the database. The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.

Methods of Statement Interface:

Description
Method
Public ResultSet executeQuery(String is used to execute SELECT query. It
sql) returns one ResultSet object that
contains rows and columns that
represented data requested by query.
public int executeUpdate(String sql) is used to execute insert, update, delete
etc. It returns an integer value
indicating number of rows that were
inserted/ updated/deleted by these
query.
public boolean execute(String sql) is used to execute any SQL queries. It
returns a boolean value. TRUE
indicates that query returned a Result
Set object and FALSE indicate
returned an int value or returned
nothing.
public int[] executeBatch() is used to execute batch of commands.

PreparedStatement Interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute

parameterized query.

Example:

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");

As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.

Methods of PreparedStatement Interface


Method Description

public void setInt(int sets the integer value to the given parameter
paramIndex, int value) index.

public void setString(int sets the String value to the given parameter
paramIndex, String value) index.

public void setFloat(int sets the float value to the given parameter
paramIndex, float value) index.

public void setDouble(int sets the double value to the given parameter
paramIndex, double value) index.

public int executeUpdate() is used to execute insert, update, delete etc. It


returns an integer value indicating number of
rows that were inserted/ updated/deleted by
these query.

public ResultSet executeQuery() is used to execute SELECT query. It


returns one ResultSet object that contains
rows and columns that represented data
requested by query.

CallableStatement Interface

CallableStatement interface is used to call the stored procedures and


functions.

We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth,
you may create a function that receives date as the input and returns age of the
employee as the output.
How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of


CallableStatement.

Syntax:

public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

Example:

CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

ResultSet Interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially,


cursor points to before the first row.

Methods of ResultSet Interface

public boolean next() is used to move the cursor to the one row next
from the current position.

public boolean previous() is used to move the cursor to the one row
previous from the current position.

public boolean first() is used to move the cursor to the first row in
result set object.

public boolean last() is used to move the cursor to the last row in
result
set object.

public boolean absolute(int is used to move the cursor to the specified row
row) number in the ResultSet object.

public boolean relative(int is used to move the cursor to the relative


row) row number in the ResultSet object, it may
be positive or negative.

public int getInt(int is used to return the data of specified column


columnIndex) index of the current row as int.
public int getInt(String is used to return the data of specified column
columnName) name of the current row as int.

public String getString(int is used to return the data of specified column


columnIndex) index of the current row as String.

public String is used to return the data of specified column


getString(String name of the current row as String.
columnName)

ResultSetMetaData Interface

The metadata means data about data i.e. we can get further information from the
data.

If you have to get metadata of a table like total number of column, column
name, column type etc. , ResultSetMetaData interface is useful because it
provides methods to get metadata from the ResultSet object.

Methods of ResultSetMetaData Interface

Method Description

public int getColumnCount()throws it returns the total number of columns in the


SQLException
ResultSet object.

public String getColumnName(int it returns the column name of the specified


index)throws SQLException
column index.

public String it returns the column type name for the


getColumnTypeName(int
specified index.
index)throws SQLException

public String getTableName(int it returns the table name for the specified
index)throws SQLException
column index.

How to get the object of ResultSetMetaData:


The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.
Syntax:
public ResultSetMetaData getMetaData()throws SQLException
DatabaseMetaData Interface

DatabaseMetaData interface provides methods to get meta data of a database


such as database product name, database product version, driver name, name of
total number of tables, name of total number of views etc.

Methods of DatabaseMetaData Interface

Method Description
public String getDriverName()throws it returns the name of the JDBC driver.
SQLException
public String getDriverVersion()throws it returns the version number of the JDBC
SQLException driver.
public String getUserName()throws it returns the username of the database.
SQLException
public String it returns the product name of the database.
getDatabaseProductName()throws
SQLException
public String it returns the product version of the
getDatabaseProductVersion()throws database.
SQLException
public ResultSet getTables(String catalog, it returns the description of the tables of the
String schemaPattern, String specified catalog. The table type can be
tableNamePattern, String[] types)throws TABLE, VIEW, ALIAS, SYSTEM
SQLException TABLE, SYNONYM etc.
How to get the object of DatabaseMetaData:

The getMetaData() method of Connection interface returns the object of


DatabaseMetaData.

Syntax:

public DatabaseMetaData getMetaData()throws SQLException

DriverManager Class
The DriverManager class acts as an interface between user and drivers. It keeps
track of the drivers that are available and handles establishing a connection
between a database and the appropriate driver. The DriverManager class
maintains a list of Driver classes that have registered themselves by calling the
method DriverManager.registerDriver().

Methods of the DriverManager Class

Method Description

public static synchronized void is used to register the given driver with DriverManager. No
registerDriver(Driver driver):
action is performed by the method when the given driver is
already registered.

public static synchronized void is used to deregister the given driver (drop the driver from
deregisterDriver(Driver driver):
the list) with DriverManager. If the given driver has been
removed from the list, then no action is performed by the
method.

public static Connection is used to establish the connection with the specified url.
getConnection(String url) throws
The SQLException is thrown when the corresponding
SQLException:
Driver class of the given database is not registered
with the DriverManager.

public static Connection is used to establish the connection with the specified
getConnection(String url,String
url, username, and password. The SQLException is thrown
userName,String password)
throws SQLException: when the corresponding Driver class of the given database
is not registered with the DriverManager.

public static Driver Those drivers that understand the mentioned URL (present
getDriver(String url)
in the parameter of the method) are returned by this
method provided those drivers are mentioned in the
list of registered drivers.

pubic static int The duration of time a driver is allowed to wait in order to
getLoginTimeout() establish a connection with the database is returned
by this method.

pubic static void The method provides the time in seconds. sec mentioned
setLoginTimeout(int sec)
in the parameter is the maximum time that a driver is
allowed to wait in order to establish a connection
with the database. If 0 is passed in the parameter of this
method, the driver will have to wait infinitely while
trying to establish the connection with the database.

public static Connection A connection object is returned by this method after


getConnection(String URL,
creating a connection to the database present at the
Properties prop) throws
SQLException mentioned URL, which is the first parameter of this
method.
The second parameter, which is "prop", fetches the
authentication details of the database (username and
password.). Similar to the other variation of the
getConnection() method, this method also throws
the SQLException, when the corresponding Driver class
of the given database is not registered with the
DriverManager.

What are the differences between Statement and PreparedStatement


interface?
STATEMENT PREPARED STATEMENT
It is used to execute normal SQL It is used to execute dynamic SQL
queries. queries.
It is used when SQL query is to be It is used when SQL query is to be
executed only once. executed multiple times.
You can not pass parameters at You can pass parameters at runtime.
runtime.
It is base interface. It extends statement interface.

What are the differences between execute, executeQuery, and


executeUpdate?
executeQuery() executeUpdate() execute()

executeQuery() method executeUpdate() method execute() use for any SQL


used to retrieve some data used for update or modify statements.
from database. database.

It returns one ResultSet It returns an integer value It returns a boolean value.


object that contains rows Indicating number of rows TRUE indicates that query
and columns that that were inserted/ returned a Result Set object and
represented data requested updated/deleted by these FALSE indicate returned an int
by query. query. value or returned nothing.

This method is normally This method Is used This method can be used to
used to execute to execute non execute any type of SQL
SELECT queries. SELECT queries. statement.
DML as INSERT,
DELETE, UPDATE or
DDL as CREATE. DROP

Example: Example: Example:


ResultSet Ts= int i= Boolean b= stmt.execute(query);
stmt.executeQuery(query); stmt.executeUpdate(query)
;
WRAPPER CLASSES:

The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

Since J2SE 5.0, 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 vice-versa unboxing.

The eight classes of the java.lang package are known as wrapper classes in
Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class

Boolean Boolean

Char Character

Byte Byte

Short Short

Int Integer

Long Long

Float Float

Double Double

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int
to Integer, long to Long, float to Float, boolean to Boolean, double to Double,
and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we
do not need to use the intValue() method of wrapper classes to convert the
wrapper type into primitives.

Why is Java not a pure object oriented language?


Java is not 100% Object-oriented because it makes use of eight primitive data
types such as boolean, byte, char, int, float, double, long, short which are not
objects.
Nested Class:
When you define a class within another class, such classes are known as nested
classes.
Important points about nested class:
Nested class scope:
The scope of the nested class binds with its enclosing class.
The InnerClass doesn’t exist without the OuterClass and it totally depends
on OuterClass. You can’t access the InnerClass without using
the OuterClass.

Access class member:


The InnerClass can access the members of the OuterClass Wheather they
are private or not. A static nested class can access only the static member
of OuterClass. But the OuterClass can’t access any member of InnerClass.
Access modifier:
We can use any access modifier with a nested class. As we know we can’t use
a private or protected access modifier with a normal class. But nested allow
use to InnerClass class can be declared private, public, protected, or default.

Why Use Nested Classes?

Compelling reasons for using nested classes include the following:

 It is a way of logically grouping classes that are only used in one


place: If a class is useful to only one other class, then it is logical to
embed it in that class and keep the two together. Nesting such "helper
classes" makes their package more streamlined.
 It increases encapsulation: Consider two top-level classes, A and B,
where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can
be declared private and B can access them. In addition, B itself can be
hidden from the outside world.
 It can lead to more readable and maintainable code: Nesting small
classes within top-level classes places the code closer to where it is used.

Types of nested classes

static nested class:

A static class is a class that is created inside a class, is called a static nested
class in Java. It cannot access non-static data members and methods. It can be
accessed by outer class name.

o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members.

Syntax:

class outer

//statements

static class inner

//statements

}
}

Example:
class TestOuter1
{
static int data=30;
static class Inner
{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
Explanation:
In this example, you need to create the instance of static nested class because it
has instance method msg(). But you don't need to create the object of the Outer
class because the nested class is static and static properties, methods, or classes
can be accessed without an object.
Non-static nested class:
Member Inner class

A non-static class that is created inside a class but outside a method is


called member inner class. It is also known as a regular inner class. It can be
declared with access modifiers like public, default, private, and protected.

Syntax:
class outer
{
//methods
class inner
{
//statements
}
}
How to instantiate Member Inner class in Java?

An object or instance of a member's inner class always exists within an object of


its outer class. The new operator is used to create the object of member inner
class with slightly different syntax.

The general form of syntax to create an object of the member inner class is as
follows:

Syntax:

OuterClassReference.new MemberInnerClassConstructor();

Example 1:
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
void display()
{
Inner in=new Inner();
in.msg();
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
obj.display();
}
}
Output:
data is 30
Example 2:
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30

Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner


class. In case of anonymous inner classes, we declare and instantiate them at
the same time. Generally, they are used whenever you need to override the
method of a class or an interface.

Java Anonymous inner class can be created by two ways:

1. Class (may be abstract or concrete).


2. Interface

Syntax
AnonymousInner obj = new AnonymousInner()
{
public void my_method()
{
........
........
}
};
The following program shows how to override the method of a class using
anonymous inner class.
Example
//anonymous inner class using abstract class
package inner_classes;
abstract class Anonymous_Inner
{
abstract void mymethod(); //by default public
}
public class Pratical_4
{
public static void main(String[]args)
{
Anonymous_Inner ai=new Anonymous_Inner() {
@Override
void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
ai.mymethod();
}
}
Example:
//anonymous inner class using interface
package inner_classes;
interface Anonymous_Inner1
{
int x=100;
abstract void mymethod(); //by default public
}
public class Pratical_5
{
public static void main(String[]args)
{
Anonymous_Inner1 ai=new Anonymous_Inner1() {
@Override
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
ai.mymethod();
System.out.println("value of x:"+ai.x);
}
}

Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like
local variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where
the inner class is defined. The following program shows how to use a method-
local inner class.
Example
//method local_inner class
package inner_classes;
class Outer_Demo2 //outer class
{
void mymethod()// instance method of the outer class
{
int num=100;
class Inner_Demo2 // method-local inner class
{
public void printme()
{
System.out.println("This is inner class "+num);
}
}// end of inner class
Inner_Demo2 id=new Inner_Demo2();// Accessing the inner class
id.printme();
}
}
public class Pratical_3
{
public static void main(String[]args)
{
Outer_Demo2 od=new Outer_Demo2();
od.mymethod();
}
}

Rules for Java Local Inner class

o Can we access the non-final local variable inside the local inner class ?
1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since
JDK 1.8, it is possible to access the non-final local variable in local inner class.
Rule: Local variable can't be private, public or protected.

Java Serialization and Deserialization


Serialization is a process of converting an object into a sequence of bytes
which can be persisted to a disk or database or can be sent through streams. The
reverse process of creating object from sequence of bytes is
called deserialization.

A class must implement Serializable interface present in java.io package in


order to serialize its object successfully. Serializable is a marker interface that
adds serializable behaviour to the class implementing it.

Java provides Serializable API encapsulated under java.io package for


serializing and deserializing objects which include,

 java.io.serializable
 java.io.Externalizable
 ObjectInputStream
 ObjectOutputStream

Java Marker interface

Marker Interface is a special interface in Java without any field and method.
Marker interface is used to inform compiler that the class implementing it has
some special behaviour or meaning. Some example of Marker interface are,

 java.io.serializable
 java.lang.Cloneable
 java.rmi.Remote
 java.util.RandomAccess
All these interfaces does not have any method and field. They only add special
behavior to the classes implementing them. However marker interfaces have
been deprecated since Java 5, they were replaced by Annotations. Annotations
are used in place of Marker Interface that play the exact same role as marker
interfaces did before.

To implement serialization and deserialization, Java provides two classes


ObjectOutputStream and ObjectInputStream.

ObjectOutputStream class

The Object Output Stream class is used to write primitive data types and Output
Stream to Java objects. It is possible to write to streams only objects that
support the java.io.Serializable interface.

Constructor:

Constructor Description
public It creates an ObjectOutputStream that
ObjectOutputStream(OutputStream writes to the specified OutputStream.
out) throws IOException{}

Method Description

public final void writeObject(Object obj) It writes the specified object


throws IOException {} to the ObjectOutputStream.

It closes the current output


public void close() throws IOException {}
stream.

It flushes the current output


public void flush() throws IOException {}
stream.

Methods:
ObjectInputStream class

An Object Input Stream uses an Object Output Stream to deserialize objects and
primitive information/data written.

Constructor:

Constructor Description
public It creates an ObjectInputStream that reads
ObjectInputStream(IntputStream from the specified InputStream.
in) throws IOException{}

Methods

Method Description

public void close() throws


It closes ObjectInputStream.
IOException {}

public final Object readObject()


It reads an object from the input
throws IOException,
stream.
ClassNotFoundException{}

You might also like