CoreJAVA 20apr2022
CoreJAVA 20apr2022
CoreJAVA 20apr2022
Prepared by:
PANKAJ SIR ACADEMY CORE JAVA
Syntaxes: { }, ( ), ;
NEW (Keyword):
NEW Keyword Sends request to the class, & class creates Object. Once the Object is
created, NEW keyword will get Object’s address in a reference variable.
GARBAGE COLLECTOR:
Garbage Collector on regular basis keeps removing unused objects from RAM, thus avoiding
overflow of memory, this helps us manage memory efficiently.
NON-STATIC/INSTANCE VARIABLE:
These variables are created inside class but outside method without using “static”
keyword. Without creating object this variable cannot be accessed & hence we get error as
shown below:
STATIC VARIABLE:
These variables are created inside the class & outside method using “static” keyword,
these variables belong to class and can be accessed with class name. .i.e
The value of static variables can be changed as shown in the below Ex:
METHODS:
Methods can be Static or Non Static, If we write “static” in method then it belongs to
Object, If ”static” is not written then it is Non Static.
To call a non static method, we need to create an object then only we can call it. i.e:
1. Local Variable: These variables are created inside a method & should be used only within
created method. If used outside created method, then we’ll get an error as shown in the
example below.
Ex: 2
Correct Error
Correct
It is mandatory to initialize local variable before using it or else we get an error as shown
in the below example:
RAM
STACK HEAP
Program Objects
Execution
Example 1:
public class A {
STACK HEAP
public static void main(String[] args) { ----- START
A a1 = new A(); ------- 2 main {
object
System.out.println(a1); ------- 3
A a1 = new A();
SOP(a1); Unused object
} -------------------------------------------- STOP
}
Garbage
}
collection
Example 2:
public class A {
STACK HEAP
public static void main(String[] args) { ----- START
A a1 = new A(); ------- 2 main {
object
object
System.out.println(a1); ------- 4 }
SOP(a2);
Garbage
System.out.println(a2); ------- 5
collection
} -------------------------------------------- STOP
}
Notes prepared by _M$A_ : 8801114535. 13
PANKAJ SIR ACADEMY CORE JAVA
Example 3: (with non static variable)
public class A {
HEAP
int x = 10; //non static variable STACK
} Meta Space
public class A {
HEAP
int x = 10; //non static variable STACK
static int y = 20; //static variable int x = 10;
System.out.println(a1.x); ------- 3
}
Unused object
} Meta Space
public class A {
int x = 10; //non static variable
int y = 20; //non static variable HEAP
static int z = 100; //static variable STACK
public static void main(String[] args) { ----- START main {
A a1 = new A();
System.out.println(a1.x); ------- 3
SOP(A.z);
}
Unused object
} -------------------------------------------- STOP
} Meta Space
a1.test(); ------- 3
main {
A a1 = new A();
} -------------------------------------------- STOP
a1.test();
Unused object
}
System.out.println(100); ------- 4
} ------- 5
}
A.test(); ------- 2
main {
A.test();
} -------------------------------------------- STOP
}
Unused object
System.out.println(a1.x); ------- 4
} ------- 5
}
1. Static Variable (Contd..): These variables are global and can be used in any method with
ClassName, we can access static variables in 3 ways.
Memory Default
Data Type Value Range Value Type
Size Value
Byte 1 byte 0 -128 .. 127
Short 2 bytes 0 -32,768 .. 32,767
-2,147,483,648 .. Integer
Int 4 bytes 0 2,147,483,647
- Value
9,223,372,036,854,775,808
Long 8 bytes 0 ..
9,223,372,036,854,775,807
3.40282347 x 1038,
Float 4 bytes 0.0 1.40239846 x 10-45 Decimal
Double 8 bytes 0.0 Value
Char 2 bytes Empty Space Character
Boolean NA false True/False
String (Class) NA null
Var (Ver. 10 of
Dynamic
Java)
• Variable name should be in lowercase or start with lowercase, if it has two words, it
should be in camelCasing. 1st word start with lowercase & the rest start with uppercase.
Ex: int id;
int employeeId;
int yourIdCard;
Notes prepared by _M$A_ : 8801114535. 18
PANKAJ SIR ACADEMY CORE JAVA
• Variable name cannot start with number in Java.
Ex: int 2id; //Error
int id2: //Correct
Var type was introduced in version 10 of Java, it will not work with Java below V10.
A variable with the type ‘var’ can store any kind of value in it. It cannot be static or non static
variable, it can only be local variable & created inside method.
Example:
Var is not a keyword in Java & hence we can use it as variable name as well, Ex:
4. Reference Variable: In a reference variable we can store either object’s address or null.
The data type of variable name is ClassName.
Variable Assgn.
Data type Value Terminator
Name Operator
int x = 10 ;
char c = ‘a’ ;
1. Local Variable: These variables are created inside method & should be used only within the
created method. If used outside method the program will throw an error, see the below
example:
The default value for a static reference variable is ‘null’ as shown in below example:
1) void
2) return value
3) return
1. void method: if a method is void, then it can not return any value, hence the below
program throws an error:
Example #3:
Example #4:
Example #5:
Example #2: We cannot write anything after ‘return’, (unreachable code error):
Example: Multiple method arguments: the number of values, value’s data type and order should
match in method argument.
Example #2: multiple single data type values & single variable in method argument:
Example #1:
• Constructors are permanently void & can never return any value
CONSTRUCTOR OVERLOADING:
Here we create more than one constructor in same class provided they are different no.
of arguments & different type of arguments.
Never use void or data type (int, char float etc..) while creating a constructor, If you do that
then it is a method and not a constructor.
Example #1:
Example #2:
Example #3:
Default Constructors:
".java" file is compiled into ".class" file and ".class" file consist of byte code which we further run
".class" file to get the output.
If you are a developer, we install JDK which gives compiler and runtime environment.
If you are a customer, we install only JRE because we run only ".class" file. Whenever we create
an object, it has to mandatorily call constructor, if a constructor is not created explicitly by
developer, then during compilation automatically empty body constructor gets added in dot
".class" file. This is applicable only for no argument constructor and these constructors are called
as default constructors.
A.java A.class
When an object with argument is created and if matching constructor is missing in “.java” file
then it shows an error as shown in the below example:
“this” (keyword):
Obj Address
Example:
Example #3:
Example #5:
If we do not use “this” keyword inside non static method to access non static members then
during compile time “this” keyword gets appended automatically.
Example #6:
If there are multiple objects created then “This” keyword points to current object running in the
program.
Example #7:
While calling constructor from another constructor “this()” keyword should always be First
statement.
Example #1:
Example #2:
Inheritance: Here we inherit the members of parent class (super class) to child class with an
intension of re-using it. Example #1:
Example #2:
Parent 1 Parent 2
Class A
Class A Class B
Class B
Class C
Child
Class C Class D
Example:
Assignment
Watch YouTube Playlist by Pankaj Sir
Academy Chanel entitled
“Unary Operator in JAVA”
& Prepare notes.
Click below to watch on YouTube:
Click Here
In Java, the unary operator is an operator that can be used only with an operand. It is
used to represent the positive or negative value, increment/decrement the value by 1.
Unary Operator
Pre-Increment Post-Increment
Pre-Decrement Post- Decrement
• Post-Increment Examples
Example #1:
Example #2:
Example #3:
Example #4:
• Pre-Increment Examples
Example #1:
Example #2:
• Post-Decrement Examples
Example #1:
Example #2:
Packages in Java are nothing but folders created to store the programs in an organized
manner.
• A Package name cannot be a keyword.
• Don't give package name in UPPERCASE letters, encouraged to be given in
lowercase letters.
• If we want to use a class present in the same package then importing is not
required but if we are using a class that is present indifferent package then
importing that becomes mandatory.
Example:
When we create an object of “Class A” in “Class B” then they’re called as “Non-Sub Class”, when
we extend a class in same package then it’s called as “Sub-Class”.
It creates three folders (p1,p2,p3) & class will be saved in “p3” folder.
Without using “import” keyword, importing can be done with (packageName.ClassName), see
the below Example:
Packages resolves naming convention problem in JAVA, that is we can create more than one
class in the same project provided packages are different as shown in the below example:
• If we make variable/method default, then it can be accessed in same class, same package
but not in different packages.
Example: (default)
Example: (public)
If we make a constructor default, then it’s object can be created in same package but not
outside package. Example:
If we make a constructor public, then it’s object can be created in same package and in different
package as well. Example:
Assignment-2
Watch these YouTube Videos by
Pankaj Sir Academy Chanel.
Click to Watch:
IIB: Instance
Initialization Block
SIB: Static
Initialization Block
IIBs are executed when objects are created. No. of times we create the object, same no.
of times IIB will be called. IIBs are used to initialize all the instance (non static) variables in one
place, and that gives us better readability of the code.
Example #1: (No Output, because no object is created, IIB will not be called)
Example #3: (Object Created twice, no. of time we create object same no. of times IIB will be
called)
Example #4: (Creating one constructor with IIB & see which is called first)
Example #6:
Example #7:
Static Initialization Block (SIB) are created inside the class with the “static” keyword &
executed before main method, it runs only once, we need not create an object for SIB.
Example:
Example #2:
Example #3:
Example #5: (SIB can only initialize static variable, it cannot initialize non static variable)
Example: (To understand the flow between SIB, IIB, Constructor and Main)
If we create an object inside IIB, we’ll not get any error but then the program will halt abruptly. Example:
Polymorphism
If we develop the feature such that it can take more than one form depending upon the
situation.
Note: Polymorphism is applicable only on methods and not on variables.
There are two ways we can achieve polymorphism, they are:
i. Overriding
ii. Overloading
i. Overriding: here we inherit a method from the parent class and then we modify its logic
in the child class by once again creating a method in child class with same signature. Advantage
of overriding is, we can achieve modification of inherited method’s logic. Example:
Example #2:
Example #3:
Overriding method with arguments: in argument data type and number of arguments should
match, variableName can be anything. Example:
Example #2:
Example #3:
Encapsulation
Wrapping of data with the methods that operate on that data is called “Encapsulation”,
here we avoid direct access to the data by making that variable private. To operate on that
data, we create publicly defined “getters & setters”.
Example #1:
Example #2:
Example #3:
Example #2:
“final” (keyword):
If we make a variable final then its value once initialized then cannot be changed. Ex:
If we make static/non static variable final, then it is mandatory to initialize these variables, auto
initialization will not happen.
Every variable that is created in an interface, by default it is final and static. Ex:
Here we can create parent reference variable and store child class object’s address into
it and it is termed as “Class Upcasting”.
Advantage: Reference variable can store all child class object’s addresses.
Example #1: (Upcasting between Interface & Class)
Functional Interface: A functional interface can consist of exactly one incomplete method in it.
Annotation: “@FuctionalInterface”
Example:
(Ex: Error, Two complete Methods) (Ex: Correct, one Incomplete Method)
Lambda Expression: It reduces the lines of JAVA code, It can only be applied on Functional
Interface. In case of lambda expression, we don't need to create an object, implement or
Overriding, it does it all automatically. Here, we just write the implementation code. But the
drawback is, it makes the code less readable.
Example #1: (Without using Lambda Expression)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Example #3: (Method with single arguments, Without using Lambda Expression)
Example #3: (Method with single arguments, With Lambda Expression & One line code in it)
--------------------------------------------------------------------------------
“default” keyword: “default” keyword was introduced in JDK version 1.8 or JDK version 8. Using
“default’ keyword we can create complete methods inside an interface.
Note: A functional interface should consist exactly one incomplete method but can have any
number of complete methods in it. Example:
Example #2: (Using Lambda Expression with Incomplete & Complete methods in)
In an interface we can add main method and can run like a class as shown in the below example,
it was not possible in JAVA Version 7:
We can also develop complete static methods in an interface, incomplete and static is not
allowed. see the below Example:
Abstraction (Incompletion)
Q . What is Abstraction in JAVA?
A. Hiding of implementation details is called as “abstraction” & the way we achieve that in JAVA
is by using Interfaces and Abstract Class.
“abstract” keyword: It helps us to define incomplete methods & incomplete classes. To develop
incomplete methods in interface usage of “abstract” keyword is optional. Example:
Abstract Class: An abstract class can be 0-100% incomplete, it can consist of a constructor, it
can consist of static and non static members, we can create main method in an abstract class,
but object of abstract class cannot be created. Example:
Assignment -3
“super”
keyword
Notes prepared by _M$A_ : 8801114535. 73
PANKAJ SIR ACADEMY CORE JAVA
27/05/2022 (Friday)
“super” Keyword
Using “super” keyword w can access the members of parent class.
Example #1:
Example #2:
Using “super” keyword we can access static and non static members both. Example:
Using “super” keyword, we can call constructor of parent class but then we should use “super”
keyword in child class constructor and it should be very first statement. Example:
If we don’t keep “super” keyword inside child class constructor then compiler will
automatically place the “super” keyword, such that it can call only no args constructor of
parent class. Example:
If we don’t create child class constructor with argument, then compiler will automatically
place no args constructor with “super” keyword. Example:
If in the parent class there’s only constructors with argument then as a programmer we
should explicitly write “super” keyword in child class constructor. Example:
“super” keyword is not automatically kept when there are only constructors with arguments in
parent class, whereas super keyword will be placed automatically in all the child class
constructors when in the parent class there’s a constructor with no arguments. Example:
We cannot use “this” keyword and “super” keyword in the same constructor to call another
constructor as either of the statements becomes 2nd statement then we’ll get an error. Ex:
If child class constructor consist of “this” keyword then in that constructor “super” keyword
will not be automatically placed. Example:
Points to remember:
• When Inheriting from an abstract Class @Override & Complete.
• If there’s a non static member in abstract class, we can inherit & access that.
• If it is static we can directly access with class name.
EXCEPTION HANDLING
To handle exception in JAVA, we use Try Catch Block, if an exception occurs in try block,
then try block automatically creates an exception object & gives that object’s address to catch
block. Catch block will now suppress the exception and the further code from there will continue
to run.
Example:
Types of Exceptions
There are mainly 2 types of exceptions, RUNTIME EXCEPTION and COMPILE TIME EXCEPTION
CompileTime/Checked RunTime/UnChecked
Exception Exception
CompileTime/Checked Exception: These exceptions will occur at compile time (when “.JAVA”
file is compiled to “.CLASS” file). These exceptions cannot simply be ignored at the time of
compilation, the programmer should take care of (handle) these exceptions.
For example, if we use FileReader class in the program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception, see the below example:
Throwable
Error Exception
RunTime/UnChecked CompileTime/Checked
Exception Exception
ArithmeticException FileNotFoundException
ArrayIndexOutOfBoundException ClassNotFoundException
StringIndexOutOfBoundException ClonedNotSupportedException
ClassCastException
ArithmeticException: This class can handle ArithmeticExcpetion like dividing a number by zero.
Ex:
NullPointerException: When we access non static member with null reference variable we get
“NullPointerException” as shown in the below example:
We can also get result with just writing “Exception e” in catch block, Example:
Q. What’s the difference between using “Exception” class & “NumberFormatException” class
in catch block?
A. When we use NumberFormatException class in catch block, then it can handle only
NumberFormatException, but if we use Exception class in catch block, then it can handle all the
Exceptions that occur in try block.
Loops are used to repeat a block of code, for example, if we want to show a message
100 times, then rather than typing the same code 100 times, we can use a loop.
There are mainly 3 types of Loops:
1. For loop
2. While loop
3. Do-While loop
For Loop: In JAVA for loop is used to run a block of code for a certain number of times.
Example #1:
Example #2:
“break” Keyword
“break” Keyword is used to terminate the “loops” and “switch statements” in java. When
the break keyword is used within a loop, the loop is immediately terminated and the program
control goes to the next line of codes after the loop. Example:
Labelled Break: Break keyword will always exit “for block”, but with labelled break we can specify
which block to exit in the loop, “for block” or “if block”.
For block
If block
“Continue” Keyword
The “continue” keyword is used to end the current iteration (repetition) in a for loop (or
a while loop), and continues to the next iteration (repetition). Example:
If and Else Statements: The Java if statement tests the condition. It executes the “if block” if
condition is true, otherwise “else” block is executed. Example:
Else-if Statement: The Java if statement tests the “if block” condition, if it is false the control
goes to “Else-If block”, If it is true it prints it’s value, if not it prints “else block” value.
Note: we can have multiple Else-if statements. Example:
While Loop: The while loop is used to repeat a section of code n number of times until a specific
condition is met.
Do While Loop: Java do-while loop is called an exit control loop. Therefore, unlike while loop
and for loop, the do-while check the condition at the end of loop body. Example:
Example #2:
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings. Example:
The previous program cannot take two words, If your name is “Mike Tyson” it can only print
Mike, the next example shows how to take multiple word string values.
Example #2:
Example #3:
Java array is an object which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
A Java array variable can also be declared like other variables with [] after the data type.
Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
Represents
array
0
Array
int[] arr = new int[3]; Index Object
Of Array
1
Data Variable No. of
Type name elements
(Stores
Object
in array 2
Address)
Example #3: Let’s suppose there are 100s of elements in an array, instead of writing
“System.out.println(arr[#]);” 100 times we can use here “Loop”. Example:
Example #4: Instead of writing “i<3;” in loop condition we can write “i<arr.length;” it will
automatically take the length of array.
Example #5: in array If we don’t initialize the value, depending upon the data type it will print
default value, here int default value is “0”.
Example #8: (foreach loop prints array’s each value with just a single statement, it will run
automatically depending upon the size of an array’s elements), Advantage: We are not worried
about how many time loops will repeat.
Array Index 0 1 2 3 4 5 6
x 1 1 2 3 3 4 5
Temp 1 2 3 4 5 0 0
In the above example there’s a set of elements which is already sorted in ascending
order, we’re removing duplicate elements from that array.
Let’s suppose x=given array which have 7 elements (array index: 0 to 6), first create same
size of a temp array, comapre x array index 0 & 1 if the elements are different copy the element
in temp array here the element values are same so we’re not copying 1, then compare 1 & 2
here the the elements are different so we’re copying 1 into temp array, next compare 2 & 3,
value is different copy that into temp array, likewise all the elements should be done, & the left
over indexes in temp array should be filled with zeros.
See the below examples:
Example #1: (with error: ArrayIndexOutOfBoundsException):
Let’s correct it in below example & further copying the elemnt into temp array.
Example #2:
The last value of x array (which is 5) is not copied because there were no further elements to
compare with, so let’s copy the last element as it is into temp.
Notes prepared by _M$A_ : 8801114535. 95
PANKAJ SIR ACADEMY CORE JAVA
Example #3:
But as we know there were two duplicate elements so after removing them we got two default
int values in place of those elements, so let’s remove the zeros.
SWAPPING IN JAVA
Swapping two variables refers to mutually exchanging the values of the variables.
Generally, this is done with the data in memory. The simplest method to swap two variables is
to use a third temporary variable. Example:
Let’s take an example of bubble sorting order, here we’ll compare neighbouring values
& check if the 1st value is greater than 2nd, if true we’ll swap, if false, will keep as it is & compare
next values.
Round #1 Round #2 Round #3
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
23 32 14 38 7 23 14 32 7 38 23 14 7 32 38
23 32 14 38 7 14 23 32 7 38 14 23 7 32 38
23 14 32 38 7 23 14 32 7 38 14 7 23 32 38
23 14 32 38 7 23 14 7 32 38 14 7 23 32 38
23 14 32 7 38 23 14 7 32 38 14 7 23 32 38
Round #4
0 1 2 3 4
14 7 23 32 38
7 14 23 32 38
7 14 23 32 38
7 14 23 32 38
7 14 23 32 38
SizeOfArray-1=NoOfRounds.
Here it took 4 rounds to sort this array, If the array is of 100 size then it will take 99
rounds.
Here it ran only 1 round, we need to run it four times, for that purpose we’re using nested for
loop (for loop inside for loop) here.
2D – ARRAY
The Two Dimensional Array in Java programming language is nothing but an Array of
Arrays. In Java Two Dimensional Array, data stored in row and columns, and we can access the
record using both the row index and column index (like an Excel File).
0 1 2 3
0 (0,0) (0,1) (0,2) (0,3)
1 (1,0) (1,1) (1,2) (1,3)
2 (2,0) (2,1) (2,2) (2,3)
2 Square
Brackets
Column Index
Indicate
2D Array
Row Index
int[][] arr = int[3][4];
Variable No No
Name Of Of
Rows Columns
Example Output
package p1; 3
public class A { 4
public static void main(String[] args) {
int[][] arr = new int[3][4];
System.out.println(arr.length); //To check no. of rows
System.out.println(arr[0].length); //To check no. of columns
}
}
Example #2:
In Java, with the help of File Class, we can work with files. This File Class is inside the
java.io package. The File class can be used by creating an object of the class and then
specifying the name of the file.
Exists Method: It is non static method present in File Class, the return type of this method is
aboolean value. This method will check whether the file exists in the given path, if the file exists
it will true or else false. Example:
If we want to check the return type, we can also use the exists method like below example:
Create A New File Method: It is a non static method in file class, in the given path if the file is
not present, then only it will create a new file & return the boolean value as true, if file already
exists then it will not create a file neither override or replace the file & will return as false.
There’s nothing wrong here, still we get CompileTime/Checked Exception, in such situations
its’s a rule that we should mandatorily surround it with “try catch” block or else the program
will not run.
Delete Directory (Folder) Method: we use same method “f.delete()” for deleting file as well as
folder.
List Method: It’s a non static method present in File Class, it will get all the file/folder names
present in the given path & the return type of this method is String Array.
Let’s first check the Files and folders present in the path:
Example:
Length Method: It’s a non static method present in File Class, it counts the number of characters
in the given file including spaces.
First let’s check what’s present in test.text file: “Pankaj Sir Academy” (18 Characters)
Example:
Read Method: It’s a non static method present in FileReader Class, It is used to read and return
a single character in the form of an integer value that contains the character’s unicode value,
then integer value is converted to char. The FileReader Class doesn’t have legnth method, so
we use File Class to make the output dynamic.
Let’s read the data present in test.txt.
In the above example it read only “m” of “mike” in the integer form, to make it read all the
characters we print System.out.println = no. of characters present in file.
We cannot increase line of codes to print each character, so here we’re using for loop
To get the character values in a single line, let’s remove “ln” from System.out.println
Here in for loop condition (for (int i=0; i<4; i++) {) we gave i<4, because mike has 4
characters & we want the for loop to run till 3 which is less than 4. But we cannot keep giving
the condition based upon the character length, & FileReader Class cannot count the length, to
automate this we’ll use File Class to count the length of the characters. Example:
Example:
There’s an another way to to read the text file by making char array, example:
It wrote the “Mike” once again without overriding the file, due to the “true” written after path.
Now we’re writing the “false” after path, Example:
It wrote 97’s coreesponding char value “a” after “Mike”, so always write anything (int, char,
boolean etc..) in double quotes “” (String value) to write into the text files.
Task Assignment
Watch recorded lectures from
Pankaj Sir Academy App
Buffered Reader:
• It improves file reading performance
• It has an exclusive readLine() method that reads the content line by line.
File Content:
Example:
Example #2:
Buffered Writer:
• It improves file writing performance
• It has an exclusive newLine() method that writes the content in new line.
Example:
Output:
Output:
All the objects we create in java are stored in RAM (Heap Memory) which is a temporary
memory, to store it permanently in .ser file we use Serialization and De-Serialization.
In serialization we convert the object in zeros and ones and then store the object state
in permanantly in file.
In de-serialization we read binaries from the file and reconstruct the object back.
Example:
OutPut:
DE-SERIALIZATION
Q. What is ObjectClass in JAVA?
A. The super most class in JAVA is called as ObjectClass in JAVA.
Example:
“transient” (keyword):
During Serialization “transient” keyword when applied on a variable, it will skip writing into the
object.
Example:
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 save, update, delete and fetch data from the database.
There are lot of database softwares, but most popular ones are:
Example#1: (we’re creating one Registration table in MySQL to store the data)
create my_db
use my_db
create table Registration
(
Name varchar(45),
City varchar(45),
Email varchar(128),
MobileNumber varchar(10)
)
select * from Registration
-- * means select all the columns in the table, we can also give column name
insert into Registration values('Sayyed', 'Hyderabad', '672msa@gmail.com', '1234567890')
-- I ran it twice, so it saved the data twice in the Registration table
insert into Registration values('Mike', 'Chennai', 'mike@gmail.com', '0123456789')
insert into Registration values('Michael', 'Tamil Nadu', 'michael@gmail.com', '1111111111')
insert into Registration values('Banty Bablu', 'Kerala', 'banty@gmail.com', '2222222222')
Result Grid:
Name City Email MobileNumber
Sayyed Hyderabad 672msa@gmail.com 1234567890
Sayyed Hyderabad 672msa@gmail.com 1234567890
Mike Chennai mike@gmail.com 0123456789
Michael Tamil Nadu michael@gmail.com 1111111111
Banty Bablu Kerala banty@gmail.com 2222222222
After extracting the .zip file we’re copying the “mysql-connector-java-8.0.29.jar” file into our
JAVA Project.
Create a new folder in JAVA Project named “lib” & paste the “mysql-connector-java-8.0.29.jar”
into that folder.
After pasting configure the .jar file to the Java project, to do that go to:
JAVAProject>Properties>Java Build Path>Libraries>Add JARs>Select “mysql-connector-java-
8.0.29.jar”.
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
We can delete record based on Name, City, Email, MobileNumber, here we’re using deletion
based on Email, because Email and Mobile Numbers are always unique, but if we delete based
on Name, City there might be multiple entries with the Name/City, all will be deleted.
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class A {
public static void main(String[] args) {
try {
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
Task Assignment
CRUD OPERATIONS
As a developer every application involves CRUD Operations.
Q. What is CRUD Operations?
A. The abbreviation CRUD stands for Create, Read, Update, and Delete in computer
programming.
In MySQL we use “executeUpdate()” method to Create, Update and Delete the data in database,
and “executeQuery()” method to read the data from the database.
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
Here it handled only ArithmeticException exception, whichever may come first it will handle
that exception and stops & will not run further codes.
----------------------------------------------------------------------------------------------------------------------------------------
Here it handled only NullPointerException, because it came first & did not run any further code
of blocks.
----------------------------------------------------------------------------------------------------------------------------------------
FINALLY BLOCK
----------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
Q. Can we write only Try and Finally & skip catch block?
A. Yes, We can write it.
Example #3:
Here exception is happening, but if catch block is missing, exception is not handled so line#9
will not run but finally block continues to run.
Task Assignment
//Open Connection
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);
//Close connection
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
System.out.println("This result is from finally block");
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/my_db
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at p1.D.main(D.java:12)
This result is from finally block
Exception in thread "main" java.lang.NullPointerException
at p1.D.main(D.java:27)
----------------------------------------------------------------------------------------------------------------------------------------
Task Assignment