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

Java Notes

Uploaded by

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

Java Notes

Uploaded by

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

Java Basics

What is Java?
Java is a most popular, class-based, object-oriented(oops), widely used and platform
independent language.
Write once and run everywhere
As of today’s world, java is widely used in every industry:
 Android Development
 Web Development
 Artificial Intelligence
 Cloud applications
 Software applications and many more
It was developed in 1995 by James Gosling at Sun Microsystem. And later acquired
by Oracle Corporation.

Implementation of a Java application program involves a following steps.


They include:
 Creating a program
 Compiling a program
 Running a program
Before all these we have to properly install the JDK (Java Development Kit) and
set the path properly in our system.

Before learning Java, we have to be familiar with some terms like JDK, JVM and JRE.
1. JVM:
This is generally referred as Java Virtual Machine.
There are always 3 phases of execution Writing, compile and running the program.
 Writing a program is done by us.
 Compile a program is done by Java Compiler (JAVAC), which is there in JDK. It
takes the program as input and give byte code (. Class) as output.
 In running stage JVM execute/compiles the byte code which is generated by the
compiler.

Every Operating System has a different JVM but the output they produce after the
execution of bytecode is the same across all the operating systems. This is why
Java is known as a platform-independent language.

made by ssp 1
2. JDK:
This is generally referred as Java Development Kit.
The name itself suggest that it has all the things inside it such as Java Compiler, JRE,
Java Debuggers, Java Docs etc.
For the program execution JDK must be installed in our OS.

3. JRE:
This generally stands for Java Runtime Environment.
JDK includes JRE. And to run a program we must need it as we cannot compile it.
JRE contains all the libraries that’s required to run a program.

Features of Java:
1. Platform Independent
2. Robust: Java language is robust which means reliable. It is developed in such a way
that it puts a lot of effort into checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy to detect by another
programming language. The main features of java that make it robust are garbage
collection, Exception Handling, and memory allocation.
3. Object- Oriented

made by ssp 2
4. Secure
5. Simple
6. Sandbox Execution: Java programs run in a separate space that allows user to
execute their applications without affecting the underlying system with help of a
bytecode verifier. Bytecode verifier also provides additional security as its role is to
check the code for any violation of access.

First Java Program:

class Demo {

public static void main (String args [] ) {

System.out.println(“Hello, World...!”);

Class: class keyword is used to declare classes in Java.

Public: It is an access specifier. It means it is visible to all.

Static: It is a keyword used to make a function static and to execute a static function we
don’t need to create an object of the class. That’s why main() method is called by JVM
without creating object of main method.

Void: It is a return type; it means it will return nothing.

Main: It is a most important method in java program. It is the method which is get
executed and we have to define everything (i.e., Objects, Classes, Etc) inside it.

A program that does not have any main method it causes a compile time error.

String args []: This is used to signify that the user may opt to enter parameters to the
Java Program at command line. We can use both String[] args or String args[]. Java
compiler would accept both forms.

System.out.println: This is used to print output on the console.

How to Take User Input in JAVA:

import java.util.*;

made by ssp 3
class Demo{
public static void main (String args[]){

int a;

//we have to take user input


Scanner sc = new Scanner(System.in);
a = sc.nextInt();
System.out.println( a );
}
}

Import java.util.*: it means all the class in util package can be imported.

Scanner: Scanner is a class used to take input from user.

System.in: This is the standard input stream that is used to read characters from
the keyboard or any other standard input device.

System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.

Keywords in Java:

They are reserved words and cannot be used as an identifier, function names, class
names, etc in a programming language.

Example: abstract, Boolean, break, case, class, catch, char, Enum, extends,
final, finally, import, for, if, implements, new , public and many more.

Identifier in Java:

All the variables must be defined with a unique name and that unique name is known as
identifier.

Example: int secondsPerMinute = 60; //good way of declare the identifier

int m = 60; // bad way of coding

Variables in Java:

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


System.out.println(myNum);

made by ssp 4
Operators in Java:

Operators are the basics building blocks in java used to perform various calculations.

Types:
 Arithmetic [ +, -, /, *, %]
 Unary [!, -, ~, ++, -- ]
 Assignment [ =, +=, -=, %=, /=]
 Relational [ ==, <=, >=, >, <]
 Logical [ &&, ||, !, True, False]
 Ternary [ cond ? x : y]
 Bitwise [ $, |, ^, ~]
 Shift [ Signed - >>, <<, unsigned - >>>, <<<]

Examples:
Arithmetic operation
public class arithmeticOperators {
public static void main(String[] args) {

int a = 5;
int b = 10;

//1. Addition
System.out.println("a + b = "+ (a+b));
//2. Substraction
System.out.println("a - b = "+ (a-b));
//3. multiplication
System.out.println("a * b = "+ (a*b));
//4. Divide
System.out.println("a / b = "+ (a/b));
//5. modulous
System.out.println("a % b = "+ (a%b));
}
}
output:
a + b = 15
a - b = -5
a * b = 50
a / b = 0
a % b = 5

Unary operator:
public class unaryOperators {
public static void main(String[] args) {
int a = 5;
int b = 0;

made by ssp 5
//1. Not operator ( ! )
System.out.print("Not Operator: ");
if(!(a>b)){
b = a;
System.out.println(b);
}else{
System.out.println("Zero");
}

//2. minus (-)


System.out.print("minus Operator: ");
b = -(a);
System.out.println(b);

//3. Bitwise Complement ( ~ )


/* a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
*/
System.out.print("Bitwise Complement: ");
int bitwise = ~(a);
System.out.println(bitwise);

//4. Increment (++)


System.out.print("Increment");
System.out.println("a: "+ a);
b = a++;
System.out.println("b after a++: "+ b);
System.out.println("a after a++ "+ a);
b = ++a;
System.out.println("b after ++a: "+ b);

//4. Decrement (--)


System.out.print("Decrement");
System.out.println("a: "+ a);
b = a--;
System.out.println("b after a--: "+ b);
System.out.println("a after a--: "+ a);
b = --a;
System.out.println("b after --a: "+ b);
}
}

Output:
Not Operator: Zero
minus Operator: -5
Bitwise Complement: -6

made by ssp 6
Increment: 5
b after a++: 5
a after a++ 6
b after ++a: 7
Decrement: 7
b after a--: 7
a after a--: 6
b after --a: 5

made by ssp 7
Java OOP’s Concept:
 OOPs refers to Object Oriented Programming, that refers to languages that use objects as
a primary source to implements what happens inside the programme.
 The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
 The oops deals with the real-world entities like inheritance, polymorphism, Data Hiding etc.

Access Modifier:
There are 4types of access modifier in java:
1. Public: Accessible in all classes.
2. Protected: Accessible within the package in which it is defined and, in its subclass,
(es) (including subclasses declared outside the package).
3. Private: Accessible only within the class in which it is declared.
4. Default: Accessible within the same package.

Private Protected Public Default


Same Class Yes Yes Yes Yes
Same Package Subclass No Yes Yes Yes
Same Package No Yes Yes Yes
Non-subclass
Different package No Yes Yes No
subclass
Different package non- No No Yes No
subclass

 Class: It is defined as a group of objects sharing common properties.


 Sub Class: Also known as a derived or extended class, this class inherits the features
from another class. Also along with the inherited fields and methods, the class
generated from the class can add fields and methods of its own.
 Super Class: The superclass represents the class whose features are inherited by a
sub-class.
 Reusability: The technique of reusability allows the user to create a class (a new one)
having the fields or methods of an already existing class. It allows reusing the code.

Oops Concepts are as follows:


 Class.
 Objects

made by ssp 8
 Methods and Methods Passing
 Pillars of OOPs:
a. Abstraction.
b. Encapsulation.
c. Inheritance.
d. Polymorphism: - 1. Compile-time Polymorphism,
2. Run-time Polymorphism

Class:
 It is a user-defined blueprint or prototype from which objects are created.
 Using classes, we can create multiple objects with same behaviour instead of
writing their code multiple times.
 Syntax: class person {
String name;
int age;
}

Objects:
 An object is a basic unit of OOP that represent the real-life entity.
 Syntax: person p = new person();
 Example of class and object:

public class classes_objects {


public static void main (String[] args) {
person p = new person(); //objects creation
//properties can be accessed through(.)operator
p.age = 24;
p.name = "Sai";

person p1 = new person();


p1.name = "Swarup";
p1.age = 25;
System.out.println(p.age+" "+p.name);
System.out.println(p1.age+" "+p1.name);
//accessing through object
p1.walk();
p1.walk(12);
p.eat();
}
}

class person{ //class creation


String name;
int age;

//methods or Behaviour
void walk(){
System.out.println( name +" is walking.");
}
void walk(int steps){
System.out.println( name +" is walking "+ steps+" steps");
}

made by ssp 9
void eat(){
System.out.println( name +" is eating.");
}
}
Methods:
 The behaviour of an object is the method.
 Example: The fuel indicator indicates the amount of fuel left in the car.

Pillars of OOP’s:

1. Polymorphism:
 Here poly means “MANY” and morphism means “FORMS”.
 It means the functions behave same operations but accepting different arguments.
 Its is of 2 types:

1) Method Overriding (or) run-time Polymorphism:


 Here methods of parent class are over ridden in subclass.
 Method name is same but performing different actions.
 Method overriding says the child class has the same method as declared in
the parent class. It means if the child class provides the specific implementation
of the method that has been provided by one of its parent classes, then it is
known as method overriding.
 Eg:

class parentClass{ //parent class


void method1(){
System.out.println("Hi I am method 1 of parent class");
}
}
class childClass extends parentClass{
//@override
void method1(){
System.out.println("hello I am method 1 of child class");
}
}
public class runTimePolymorphism{
public static void main(String[] args) {
parentClass pc = new childClass(); //creating object of
parentClass and instantiate the childClass
//here subclass override the value of parentClass.
pc.method1(); //output: hello I am method 1 of child class
}
}

2) Method Overloading (or) Compile-time Polymorphism:

made by ssp 10
 Here methods name is same but accepting different
arguments/signature.
 At compile-time, java knows which method to call by checking the method
signatures.
 Method Overloading says you can have more than one function with the same
name in one class having a different prototype.
 Eg:

class ctp {
public static int add(int x, int y) { //method Name: add ||
signature: int int
return x + y;
}

public static int add(float x, float y) { //method Name: add ||


signature: float float
return (int) (x + y);
}

public static int add(double x, int y) { //method Name: add ||


signature: double int
return (int) (x + y);
}
}
public class compileTimePolymorphism {
public static void main(String[] args) {
ctp a = new ctp();
int INT = ctp.add(10,20);
int DINT = ctp.add(20.5d, 15);
int FLOAT = ctp.add(50.5f, 50f);
System.out.println("int int: "+ INT);
System.out.println("double int: "+ DINT);
System.out.println("float float: "+ FLOAT);
}
}

2. Abstraction:
 Data Abstraction is a process of hiding the personal/ important data and showing
only the functional part of the program to the outside world.
 It can be achieved either by abstract class or interface.
 Abstract class : is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
 Abstract Method : can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).

Eg:

made by ssp 11
package basics;
abstract class abc{
abstract void method1(); //is a restricted class that cannot be used
to create objects.
public void method2(){
System.out.println("parent class");
}
}

class subClass extends abc{

@Override
void method1() {
System.out.println("abstract method override");
}
}
public class abstractClass {
public static void main(String[] args) {
subClass sc = new subClass();
sc.method1();
sc.method2();
}
}

3. Inheritance:
Accruing the properties of parent class. (or) in simple word inheritance in java
is a oops concept which allow one class to inherits the properties of another class. And
this can be achieve through “EXTEND” keyword.

For eg:

class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal class
dog.bark(); // Unique to Dog class
}
}

made by ssp 12
Types of Inheritance:
1. Single level Inheritance.
2. Multi-level Inheritance.
3. Multiple Inheritance.
4. Hierarchical Inheritance
5. Hybrid Inheritance

4. Encapsulation:

Encapsulation means biding up the data members and member function (Methods) in
a single-units.
(or)
Encapsulation is defined as the wrapping up of data under a single unit.
Eg:

class Person {
private String name;
private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }


}

public class Main {


public static void main(String[] args)
{
Person person = new Person();
person.setName("John");

made by ssp 13
person.setAge(30);

System.out.println("Name: " + person.getName());


System.out.println("Age: " + person.getAge());
}
}

Data-Structure’s & Algorithms


Array:
 Collection of similar data types.
 Array in java is a group of like-typed variable referred by a common name.
 By default, the value of integer array is Zero.
 Array in Java are dynamically allocated.
 Arrays are stored in a contiguous manner.
 In java Array behaves as an object and it is a Non-Primitive Data Type.
 The direct Subclass of Array Type is Object.

 One – Dimensional Arrays:

Syntax:

type[] var-name; (or) type var-name[];

example:
1. int[] arr; // integer array
2. byte arr[]; //byte array
3. short a[]; //Short array
4. boolean boolArr[]; //Boolean Array
5. long longArray[]; //Long Array
6. float floatArray[]; // Float array
7. double doubleArray[];
8. char charArray[];

Instantiating an Array:
When we declared an array, only a reference of an array is created.
So, to create or give memory to it we have use new keyword to that:
Syntax: var-name = new type[size];

made by ssp 14
Here, “length” keyword used to determine the length/size of the array.
“type” specifies the type of data binding (int, short, char…etc).
“size” defines the number of elements in the array.

Ex:
int[] arr;
arr = new int[arr.length];
(or)
int[] newArr = new int[20];

Note:
The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference
types).

Code:
public class one_D_Array {
public static void main(String[] args) {

int a[] = {8,4,6,8};


//suppose we have to print the element 3
System.out.println("Element 3 is: "+ a[2]);
//suppose we have to print the element 1
System.out.println("Element 1 is: "+ a[0]);

// but we have to print multiple elements so sout method is not


// suitable for its..
//so, let's use for loop or for each loop to do so
//using for loop
for (int i=0; i<a.length; i++){
System.out.print(a[i] + " ");
}

// for each loop


System.out.println();
System.out.println("Foreach Loop");
for (int i: a) {
System.out.print(i + " ");
// System.out.print(a[i] + " ");
}
}
}

Multi-Dimensional Array

made by ssp 15
 Multidimensional arrays are arrays of arrays with each element of the
array holding the reference of other arrays. These are also known as Jagged
Arrays. A multidimensional array is created by appending one set of square
brackets ([]) per dimension.

 Syntax:
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];

 ex:
int [][] arr= new int[3][3];

Code:
public class jaggedArray3D {
public static void main(String[] args) {

int nums[][] = new int[3][]; // if inside array is not fixed (or)


// we can say that column is not fixed is known as jagged array

nums[0] = new int[3];


nums[1] = new int[4];
nums[2] = new int[2];

//to print this


for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
nums[i][j] = (int) (Math.random() * 10);
System.out.print(nums[i][j] + " ");
}
}

//using for each loop


System.out.println();
System.out.println("=====================");
for (int n[] : nums) { //n = parent array
for (int m : n) {
System.out.print(m + " "); // m = child array which print
elements
}
System.out.println();
}

made by ssp 16
System.out.println("3D ARRAY");
int num[][][] = new int[3][4][5];
}
}

String
 String in java define as a sequence/array of characters.
 In Java, Object’s of String are immutable which means a constant and can’t be
changed once created.
 Creating a string:
1. String Literal
String s = ”Sai”;
2. Using new Keyword
String s = new String(“Sai”);
 Creating a Char Array:
o char cArray[] = {‘A’, ‘B’, ‘H’, ‘I’};
 Initialization:
//first method
String[] arr0=new String[]{"Apple","Banana","Orange"};

//second method
String[] arr1={"Apple","Banana","Orange"};

//third method
String[] arr2=new String[3];
arr2[0]="Apple";
arr2[1]="Banana";
arr2[2]="Orange";
 Example codes:
=======================Methods of String===============================

public class stringClass {


public static void main(String[] args) {
/*
String :- A bunch of character's and it is a class
Example: Sai
to declare this:
String name = "Sai";
*/
// suppose we have created obj of String
String name = new String("Sai");
System.out.println("Hello "+ name);
System.out.println("UpperCase: "+name.toUpperCase());
System.out.println("lowerCase: "+name.toLowerCase());
System.out.println("Concate: "+name.concat(" Swarup"));
System.out.println("CharAt 2nd Postion: "+name.charAt(2));
}
}

========================== Mutable String =============================


public class multableString {
public static void main(String[] args) {
//we can change the value after declaration also

made by ssp 17
// StringBuffer
StringBuffer sb = new StringBuffer("Sai");
System.out.println("Capacity of String: "+sb.capacity());
System.out.println("Length of String: "+sb.length());
System.out.println("Append String: "+ sb.append(" Swarup"));
System.out.println("Inster String: "+ sb.insert(0,"Java "));
}
}
================================ Immutable String =============================

public class ImmutableString {


public static void main(String[] args) {
// immutable means if the variable is declared we cannot change
// its value
String name = "sai"; // in stack constant with a address
// suppose sai --> 101
name = name + " swarup"; // here it create a new spcae in memory
// for sai swarup --> 102
System.out.println(name); // name --> 102

String s1 = "Dog"; // s1 --> Dog <--- s2


String s2 = "Dog";
System.out.println(s1 == s2); // true
}
}

Abstract class in java:

 A class which declare with an abstract keyword.


 It has both abstract and non-abstract method (methods with body).
 It needs to be subclassed by another class to use its properties.

Notes:
 An Instance of abstract class cannot be created.
 Constructor are allowed.
 We can have abstract class without any abstract method.
 We can define static methods in an abstract class
 If a class contains at least one abstract method then compulsory should declare
a class as abstract
 If the Child class is unable to provide implementation to all abstract methods of
the Parent class, then we should declare that Child class as abstract so that
the next level Child class should provide implementation to the remaining abstract
method

Example:

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

// Abstraction performed using extends


class Employee extends Sunstar {

@override

made by ssp 18
void printInfo() {
String name = "avinash";
int age = 21;
float salary = 222.2F;
System.out.println(name);
System.out.println(age);
System.out.println(salary);

// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}

Output:
avinash
21
222.20

Interface class in java:


 A class which declares with an Interface keyword.
 The interface in java is a mechanism to achieve abstraction and Multiple
inheritance.
 It contains only abstract methods not the method body.
 In simple word it is a blueprint of the behaviour.
 It doesn’t have constructors
 It is also used to achieve loose coupling.

Example:

// Java program to demonstrate working of


// interface
import java.io.*;
// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

made by ssp 19
// Implementing the capabilities of
// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}

Java Functional Interface:

 A functional interface is an interface who takes only one Abstract Method. It is


applicable till java 7.

 From Java SE 8 onwards, with lambda Expression can be used to represent the
instance of functional Interface.

 Functional interfaces are used and executed by representing the interface with
an annotation called @FunctionalInterface.

 It is also known as SAM Interface [Single Abstract method Interface]

Example:
@FunctionalInterface
interface A{
// void show(); // we don't need to declare it abstract by-
default it is an abstract method
void show(int i);
}
//we know that we cannot create obj of interface class
//so, we have to make a subclass which extends the interface
class or else
class B implements A{

@Override
public void show(int i) {
System.out.println("this is override method "+ i);
}
}
//we have to use the lambda Expression
// we can use lambda expression with only functional interface

public class Demo {


public static void main(String[] args) {

made by ssp 20
A obj1 = new B();
obj1.show(4);

//by overriding it here its


A obj2 = new A() {
@Override
public void show(int i) {
System.out.println("Hi I am interface of A "+ i);
}
};
obj2.show(5);

//by using lambda method


A obj3 = i -> System.out.println("Hi I am Lambda
Expression "+ i);
obj3.show(6);
}

Lambda Expression:
 It works only with functional interface.
 In Java, Lambda expressions basically express instances of functional interfaces (An
interface with a single abstract method is called a functional interface).

CODE:

package org.lambdaExp;

@FunctionalInterface
interface A{
void show(int i);
}
@FunctionalInterface
interface b{
int add(int i, int j);
}
public class Demo {
public static void main(String[] args) {
A obj = i -> System.out.println("Hi LAMBDA there " +
i);
obj.show(5);

b obj1 = (i, j) -> i+j;


int res = obj1.add(5, 10);
System.out.println(res);
}
}
made by ssp 21
Exception Handling:

 Exception in java is an unwanted event which occurs during the runtime of


the program., that disturb the normal flow of the program.
 Exception can be caught and handled by the program during the runtime.
 Parent class of Exception is: Throwable
 Child class is: Exception
 Code for Try-Catch Block:
package multipleCatchBlock;

public class AppMultiCatch {


public static void main(String[] args) {
int x;
try{
x = 10/0;
System.out.println("statement not executed");
} catch (ArithmeticException e){
System.out.println("Arithmetic Exception
occurred");
} catch(Exception e){
e.printStackTrace();
System.out.println("Inside exception block");
}
}
}

output:
Arithmetic Exception occurred

Finally Block:

 Finally, block is a block which always get executed no matter the program
throws exception or not.
 Remember that finally block always be place after the catch Block.
 Code for Finally Block:
package multipleCatchBlock;

public class finallyBlock {


public static void main(String[] args) {
int j = 10;
int k = 0;
try{
int z = j/k;
}catch(Exception E){
E.printStackTrace();

made by ssp 22
System.out.println("Error in try block: "+ E);
}finally{
System.out.println("system process
completed...");
}
}
}

//finally block always get executed ...

output:
Error in try block: java.lang.ArithmeticException: / by zero
system process completed...

Throw and Throws:

 Throws are used to suppress the error if the user doesn’t want to specify the try
and catch block. Note that this doesn’t handle the error only suppresses it.
 The keyword “throw” is used to throw an exception from any method or static
block, while the keyword “throws”, used in a method declaration, indicates what
exception can be thrown with this method. They are not interchangeable.
 Code for throw and throws:

package ThrowandThrows;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class demo {


public static void main(String[] args) {
try{
someMessage();
ThrowKeyword();
}catch (FileNotFoundException f){
System.out.println("catch block of file not
found...");
}catch (Exception e){
System.out.println("catch block of throw ...");
}

public static void someMessage() throws


FileNotFoundException {
FileReader f = new FileReader("file.txt");
System.out.println("message to main....");
}

made by ssp 23
public static void ThrowKeyword() throws Exception {
System.out.println("throw keywords");
throw new FileNotFoundException();
}
}

output:
catch block of file not found...

Threads:
 Threads are the small units that’s works on multi-purpose.
 Multiple threads run at same time in a code.
This is known as Multithreading.
 A thread is a smallest unit to work with. (Individual task)
 They can run parallelly.
 Multiple threads can share resources.

made by ssp 24
JDBC [Java Data Base Connectivity]:

 JDBC is nothing but an advance java concept used to connect the relational DB with
Java.
 The classes and interface of JDBC are present in the java.sql package.
 JDBC is a Java API used to execute the SQL Query.
 It supports Multi-tier architecture.

Steps to Perform JDBC Operation


1. Import Packages => Import java.sql.*;
2. Load Driver and Register Driver =>

/* load and register -> this part is not required */

Class.forName("org.postgresql.Driver");

3. Create connection =>

/* Create Connection */
Connection con = DriverManager.getConnection(url, uname, pass);
System.out.println("Connected...");

4. Create Statement =>

/* Create Statements[Create Operation]*/


Statement st = con.createStatement(); //request

5. Execute Statement

String sql = "select * from employee";


/* Execute Statement */
ResultSet rs = st.executeQuery(sql); //response

//fetch all the data [ READ OPERATION ]


while (rs.next()){
int ID = rs.getInt(1);
String name = rs.getString("ename");
int marks = rs.getInt(3);
System.out.println("ID - "+ ID +","+ " Name - "+ name +","+ "

made by ssp 25
Marks - "+ marks);
}

6. Close Connections

/* Close */
con.close();
System.out.println("Disconnected....");
CRUD OPERATION

CRUD Stands for Create Read Update Delete.

package crudOperation;
import java.sql.*;

public class crud {


public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost:5432/demoDB";
String uname = "postgres";
String pass = "Saiswarup2001";

/* UPDATE SQL Query */


String sql = "update employee set ename='Max' where id = 5";
/* Insert SQL Query */
String isql = "insert into employee values (4, 'Sonu', 50)";
/* Delete SQL Query */
String dsql = "delete from employee where id = 5";

/* Create Connection */
Connection con = DriverManager.getConnection(url,uname,pass);
System.out.println("Connected...");

/* Create Statements */
Statement st = con.createStatement(); //request

/* Execute Statement to insert*/


st.execute(dsql);

con.close();
}
}

made by ssp 26

You might also like