CORE JAVA
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.
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:
Architecture Neutral:
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:
Multithreading:
C++ vs Java
C++ Java
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.
Java vs Python
Java Python
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.
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:
o Loads code
o Verifies code
o Executes code
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.
JVM Architecture
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.
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:
For Example:
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:
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,
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:
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
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.
Converting lower data type into higher data type is called Implicit type casting.
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 are variables which are declared within a class but cannot
declared within a body of method, constructor or any block.
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 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:
Initialization variable:
class_name . static_variable=value;
Accessing static variable:
Class_name . static_variable;
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:
ESCAPE SEQUENCE:
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)
| 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 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 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)
~ 0101
________
1010 = 10 (In decimal)
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).
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;
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;
}
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.
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
}
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);
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:
while (true)
// statements
do
// statements
} while (true)
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.
CharSequence Interface
1. By string literal:
For Example:
String s="welcome";
Only one object is created in SCP area and s is pointing to that object.
SCP Area
welcome
s
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.
2. By new keyword
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".
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.
StringBuffer:
For Example:
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.
For Example:
StringBuilder s=new StringBuilder(“welcome”);
Constructor Description
Method Description
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 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.
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:
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:
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.
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 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).
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.
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.
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.
class Student
{
int rollno;
String name;
String city;
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.
Private Y N N N
Default Y Y N N
Protect Y Y Y N
ed
Public Y Y Y Y
METHOD:
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.
Output:
1. Non-Static/Instance Method:
Non-static method belongs to object of class.
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:
//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.
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.
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:
//method body;
CONSTRUCTOR:
Need of constructor:
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.
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.
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:
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
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
Output:
111 Karan
111 Karan
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
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.
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.
Note: In the same constructor block, we cannot use this() and super()
simultaneously.
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.
GARBAGE COLLECTOR:
3.Increases memory efficiency and decreases the chances for memory leak.
finalize() method
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:
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 are those which are developed by users in order to group
related classes, interfaces and sub packages.
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
There are two ways to access the package from outside the package.
1. import packagename.*;
2. import packagename.classname;
Subpackage:
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.
import packagename.subpackagename.*;
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.
Types of inheritance:
Single Inheritance:
When a sub class inherits one super another class, it is known as a single
inheritance.
Multilevel Inheritance:
For example: Grandson class inherits Son class which inherits Father class.
Hierarchical Inheritance:
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.
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.
final keyword:
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
final class
block.
static variable at the time of its the final variable at the time
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
only.
Types of polymorphism:
Compile-time-polymorphism:
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:
Runtime polymorphism:
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{}
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.
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.
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:
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.
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.
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.
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
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.
5.Any class which implements the interface must need to implement all the
abstract methods declared in 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
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.
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.
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
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:
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:
Process:
Multitasking:
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.
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:
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.
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
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
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
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.
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:
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
2) notify() method
It is used to give the notification for only one thread which is waiting for
particular object.
Syntax:
3) notifyAll() method
It is used to give the notification for all thread which is waiting for particular
object.
Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
EXCEPTION HANDLING:
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.
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:
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.
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.
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:
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.
throw exception;
Let's see the example of throw IOException.
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:
//method code
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Rule: If you are calling a method that declares an exception, you must either
caught or declare the exception.
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.
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.
What is Framework?
Framework is collection of pre-defined classes and interfaces.
What is the Collection framework in Java?
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.
Syntax:
Syntax:
Syntax:
Syntax:
Iterator traverses the elements in the forward direction only whereas ListIterator
traverses the elements into forward and backward direction.
Iterator ListIterator
The Iterator can be used in List, Set, ListIterator can be used in List only.
and Queue.
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.
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.
When we use comparable interface it Comparator does not affect original class as
affects original class. we create new class for it.
What is API
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
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
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.
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”);
Example:
Connection
conn=DriverManager.getConnection(“jdbc:mysql://localhost/dbname”,
“username”, “password”);
Example:
Statement st=conn.createStatement();
Example:
Example:
conn.close();
Connection Interface
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.
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
parameterized query.
Example:
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
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.
CallableStatement Interface
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?
Syntax:
Example:
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.
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.
Method Description
public String getTableName(int it returns the table name for the specified
index)throws SQLException
column index.
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:
Syntax:
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().
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.
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
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:
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.
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
//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
Syntax:
class outer
{
//methods
class inner
{
//statements
}
}
How to instantiate Member Inner class in Java?
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
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);
}
}
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();
}
}
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.io.serializable
java.io.Externalizable
ObjectInputStream
ObjectOutputStream
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.
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
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