[go: up one dir, main page]

0% found this document useful (0 votes)
52 views161 pages

B2-Sep-18 Notes

The document outlines a comprehensive Java training program led by Dilip Singh, an experienced Java developer with over 12 years in the field. It covers various aspects of Java programming, including core concepts, frameworks, software application types, and the software development life cycle. The training emphasizes practical skills, placement assistance, and the importance of understanding both core and advanced Java for real-world application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views161 pages

B2-Sep-18 Notes

The document outlines a comprehensive Java training program led by Dilip Singh, an experienced Java developer with over 12 years in the field. It covers various aspects of Java programming, including core concepts, frameworks, software application types, and the software development life cycle. The training emphasizes practical skills, placement assistance, and the importance of understanding both core and advanced Java for real-world application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 161

Java Training

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

About Me :
=========
Dilip Singh
MNC , Asc Manager , 12+ Year
Java Developer

Beckend Developer

Skill :
Java , Spring, Spring Boot , & Micro Service App

Real Time Training :

Theory :

Real Time :

Requirement : Analysis -> Solution -> Coding -> Testing ->


Live

Training : Accenture 2018-19 :


4 Years , Spring Boot & Micro Services

Java Training:
=============

Why Only Java ?


Where Java involving?
Job Opprtunities

To create S/w App -> Java , python, .net ...

Why we need s/w app?

Contact : +91 8125262702

Placements :

100% placemnts -> 100% fraud

Hire Talent , -> Interview ->

100% placemnt assitance -> Mock Intervies -> Profile ->


100% Knowledge -> Industry ->

-> SDLC(S/W Development Life Cycle) : JAVA Developer : FSD

->

Programming Lang :
------------------

Java :

-> Basics, Fundamentals, Concepts of Lang.


How to write proramming
What are the rules & Regulations , have to follow while writing
programms
What concepts are being used at what time

-> Can we Create S/W -> Yes

-> Challenges , Errors , Manuall Logic

-> App Devlopement : Time : 2 Years

Framework:
----------
Struts
Spring
Spring Boot -> Right Now
Quarkus
Micronut

python : Django
.net : asp .net
js : RJS , AJS

java + html + css + js -> 2 Yrs : 2m $

java+Spring Boot +html + css + js_ RJS -> 6-9 Months : 1M $

Biryani :
Swiggy : 1 day : 10 < orders

0 -> High Level


HW + Patiency ->

HTML, CSS,JS, RJS, JAVA, Spring Boot, Micro Services, SQL

Mon- Saturday

Java Programming Lang:


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

Core Java :
----------

Open Source : Free For all

1995 -05-15-2025

write once, run anywhere (WORA) : Platform Independent

Java :
-> Core Java : JSE : Java Standard Edition
-> Advanced Java : JEE : J2E : Java Enterprise Edition

JSE : Java Standard Edition :


====-------------------------

Core Java :
Baiscs and Fundamental of Programming lang
Rules & Regulations

OOPS :
Errors / Exceptions Handling
Collections
Java 8 Fetures

Child Hood : English


Alphabets -> Words -> Sentences -> Passages -> Letetr Writings
Formulas

-> By Using only Core Java , can we create a Real S?W app or not ? No

Java Enterprise Edition: Adv. Java


Stand ALone -> 90% Web Applications

-> How to a S/W web app


-> JDBC, Servelrts, JSP , HTML , CSS

-> By Using only ADV Java , can we create a Real S?W app or not ? Yes :

2 years

6-9 Months : SB , RJS

-> Tyeps of S/W applications


-> Java S/W Impl
-> Advantages
Platform Independent : WORA
-> Writing a Java Program
->

+91 8125262702

-> Core Java :


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

What is an Operating System?

What is a Language?

What is a Programming Language?

Language :
English, Telugu , Hindi ...

What is a Programming Language?

S/W Applications :
Editors, Phostoshop, Paint , Sublime text etc..., Zoom

How many types of S/W->

What type of Applications we weil develop more ?

types of S/W Apps:


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

1. Standalone Applications
2. Web Applications

3. Mobile Applications

Standalone Applications:
------------------------
Desktop Apps -> Alone to That specific Computer, Installation in
Other Compter is required always.

Ex : Pdf , paint, calculator , photoshop.. , Games

Web Applications:
---------------
Internet 100% , Browser

Instagram.com , google.com, gamil.com, youtube.com ,


facebook.com, etc..

Netbanking ,

standalone / Web Applications

-> What type of applications? web

12 Years : 100% web

-> Human Problems ->

-> Our CommonSense : Observation of Real Life Scenarios

-> PL Leraning

-> Scietinst

Mobile Applications:
--------------------
App -> FE ->

-> Advnatges of JAVA PL :


===========================
Paltform Independent / WORA : Made is More Popular :
Compiler / Interpreter

JDK JRE JVM

+91 8125262702

Java Installation
First Program
Steps :
Terminology : Concepts

-> Java Installtion :


====================
Command Prompt
> java -version
Message :
'java' is not recognized as an internal or external command,

let's installation :
Downalod Java S/W:

Which Version : LTS (Long Term Support) Version


java 8
java 11
java 17
java 21

java 17 : windows:

https://download.oracle.com/java/17/archive/jdk-17.0.11_windows-
x64_bin.exe

double click -> next - next -> Close

C:\Users\Dilip Singh>java -version


java version "17.0.11" 2024-04-16 LTS
=========================================================

JDK : Java Development Kit

Java Compiler
JRE : Java Runtime Environment
JVM : Java Virtual Machine

Let's Start First program :

-> Name :
FirstProgram

Rules & Regulations:

-> FIle extension shoule be always .java

Java File Location :

D:\Classes\B2-Sep-18\programs

Compiling Java Program : javac <FileName.java>

D:\Classes\B2-Sep-18\programs>javac FirstProgram.java

D:\Classes\B2-Sep-18\programs>javac FirstProgram.java

D:\Classes\B2-Sep-18\programs>
D:\Classes\B2-Sep-18\programs>
D:\Classes\B2-Sep-18\programs>
D:\Classes\B2-Sep-18\programs>
Exectuing : java <ClassNAme>

D:\Classes\B2-Sep-18\programs>java FirstProgram
Welcome to JAva World.
This is My first Program

-> Understand what is JDk


-> Install JDK / Java
->

Compilation & Execution Details:


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

-> Write a Program


-> Print My Name : Dilip Singh

<FileName.extension>

Step 1 : Create a Java File


File Name :
-> File Name should Not Contain any Spaces.
Extension : java (Always lower case)

Ex : Product.java : Valid
ProductDetails.java : Valid
Product Details.java : Invalid Java File Name

Rule : Java is Case Senstive Language

ProductDetails.Java : Valid / Invalid : Invalid

Productdetails

-> Lower case character is different from upper case character


Ex : d -> not equals to D

-> File Name should be class Name

Java File : MyInformation.java

Baisc Commands :
Windows :
linux OS : Commands

Java Compiler :
=====-------------

Validates logic w.r.to Rules and Regulation of JPL , Developer written


logic or not

-> If any things not follwed, considered as Error

-> Java Compiler will provide us Errors


-> Fix all those Errors which are reported by Compiler

-> Once Compiler Identified 0 errors, then only Compiler will create one
more file called as .class file.

-> In this case file Name will be Class Name pf the Program/File Name.

Java Program Execution :


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

-> Developer : .java file

-> Compiler -> .class file

-> Execution : .class -> Output

Why .class created?


what is content inside .class?

-> .class file content will be called as byte code.

-> Java RE will use always .class for executing program.

If I deleted .class file, what will happen?

Execution can't be done


Erro : Class Not Found

-> I have .java & .class files, now I deleted .java file, Program will be executed
or not?

yes executed. bcoz .class is existed

-> If we are making any chnage in source code (.java file). we should re-compile
the source code , then a new .class file will created again.

Then only we can see latest code chnages effected in OP.

Contact: +91 8125262702


Advantages :
==============

-> Java is Platform Independent Language :


WORA : Write Once Run AnyWhere

Platfrom Dependent : C

-> Object Oriented Programming Lang :

What Object?

-> OOP Principles


-> Inheritence
Child class vs Parent class
-> Child class can access Parent class Properties .

-> A is Child of B
-> B is Child of C
A and C ? A is father is B , B's father is C

Grand Child/Son : A -> is accessing B and C Properties

-> Abstratction
-> Polymorphism
-> Encapsulation

-> Multi Threading

Java Concpets : How to Programs:

Programming :

Class in Java :

-> Create a Jav file : Student.java


-> What is logic we have write in side java file?

-> In Java language, We will write logic always by using a concpet called as Class/
Classes.

-> We have to create a class first.

What is class?

-> Class is a prototype for creating an Object.


-> Class will have an Implementation/details to create an Object.
-> without class can we create an Object? No

-> By using one class, we are going to create Objects.

Object Oriented programing lang: / Run time/ Excectuion -> Object Driven

class & Object :

by using Object , we will start executing/driving logic execution flow.

what is Object in Real Time?

Phone , Car , Laptop, Human .... Stone ...

Student Class -> How many Object Can I create for Student ? Many

1 class -> Many Objects

-> How to define a class?

keywords of Java lang.

-> tHose words are reserved by Java lang for a specific functionlaity or a
specfic reason.

Diff -> Diff Key words .

Car ->

Syntax: Template :
-----------------------
Java Case Sensitive :

{ } -> Curly Braces

public class <ClassName> { Starting of Class


Implementation

// logic
// 3000 lines

} -> Ending Curly braces

<...> : Means We can replace with User/Developer Defined Value

Ex :
public class Student{
// Logic
}

Rule : -> Class Name Should Be like File Name.

Who will create Object?

Depend on Requirement : Developer, we will only write logic for Object


Creation

Rule : Writing main() method:


======

public static void main(String[] args){


//
}

=> JAva will use always main method() as an entry to start execution of loigc

=> If no main method , we written :

=> are we getting any comile time error ? No


=> Program compilation is success? Yes

=> When we execute, then JAVA/JRE/JVM is always looking for main method :

if existed : Logic Excution will start


if not existed, Error like below.

D:\Classes\B2-Sep-18\programs>java Student
Error: Main method not found in class Student, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Object Creation in Java :


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

Synatx : <ClassName> <objectName> = new <ClassName>();

-> Execution Flow :


Java execution: line by line.

Assignment:
=> Write a java class: And Print Information of your Details

PL : Make your hands dirty.. Practice ..

Unserstand -> Read -> Do more Practical


100 Reading examples = Practcing 1 example

Object :
========
Which is having an existence in this world is called Object.

Class -> Logic -> State and Behaviour of an Object

Then -> Object -> Start Executing loigc

-> Every Object is having an Identity, State & Behaviour.

Variables In Java:
==================

What is Variable?
-> Variable is reference of memroy location where the Real value
stored.
-> Variable is a container which holds real value.

Syntax :
======

With Out Value


<data-type> <variable-name>;
With Default Value
<data-type> <variable-name> = <value>;

Ex : int a;
int age = 30;
int mobile;

...

..

Data Types IN Java:


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

What is Data Type?

Data + Type =>


Data Type is represeting what kind of data we are going to store
in a variable.

What type of Data

Set of Data Types:


Define always a data type when you are creating a variable.

Example :
int a = 10;
String name = "Dilip";

2 types:

1. Primitive data Types


2. Non-Primitive Data Types

Varibale Names :
---------------

-> varibale Names shoud not contain any space.


-> Varibale names are developer choice.

-> Before Using a varible , we should declare/create it first.

() -> parenthisi braces


{} => curly
[] -> Array Braces

1. Primitive data Types :


========================
8 data types:

-> basic data types in Java PL


-> to manipulate data in Programing
-> in lower case always

1. byte
2. short
3. int
4. long
5. float
6. double
7. char
8. boolean

-> Why we have to choose specifc data type , if not what will happen?
-> violating rules -> Break the rules -> Errors

Below 4 primitive data types allows only plain numeric values

1,2,3,4,5,8389493849,12345678,87654321
89.99 : Invalid
1. byte
2. short
3. int
4. long

-> HWy Java Given 4 data types for plain numerci value?
-> For Internal Memory Managment

byte 1 byte Stores whole numbers from -128 to 127


short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

PrimitiveDataTypes.java:8: error: integer number too large


long mobileNumber = 999999l; 'l' : small l character

int 4
long 8 byte

Application : Memory ~ Performance


logic : App -> next 20 years : Millions

5. float - 4 Bytes
6. double

-> Whenevr we want to store floating/decimal values , then wec an


choose either float / double.

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal


digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15
decimal digits

7. char

Character : A B a x
AB is not a charcter.

-> we to dela with individula characters data, then we have to use


"char"
data type.

char gender = 'M';

Rule : Assign value inside single quotes

Y
N
char passed = 'Y';

gender : M

8. boolean

-> to deal with value of true and false

are you prcticed? true / false => true false


a varible is taking data like true or false, then we can take data type
of boolean

* boolean variable will accept always a value either true or false;

boolean areYouLiseting = true; Valid


boolean areYouLiseting = True; In Valid

boolean areYouLiseting = false; Valid


boolean areYouLiseting = FALSE; InValid

why I am giving ";" where to provide ";" :


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

-> Every statement/instrction inside a block should be ended with ; always.

-> Opening/closing block should not be ended with ;

-> What is block?


block : group
block is a collection of instructions.

-> Block is represented by { }


-> inside block , we will write logic as instructions.

public class PrimitiveDataTypes{

public static void main(String[] args){

byte temp1 = 35;


int temp2 = 35;
short year = 2024;
long mobileNumber = 9999555l;

boolean areYouLiseting = false;


System.out.println(areYouLiseting);

if(conditions){
// logic : instructions
}

try{

}
catch(){
// lines : ended with ;
}
}

public void add(){


int a = 10;
int b = 30;
int c = a+b;
}

Work : buy an apple phone 16 pro

-> trnsfer 15000o


-> apple stor
-> black
-> pay amount
-> phone
-> handover

2. Non-Primitive Data Types :


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

-> Except 8 primitive data types , evrything is non-primitive data Types.

String : class
Arrays
Classes
Interfaces
Annotations
Enum
etc.

-> Every Java class is a Data Type.


Student
PrimitiveDataTypes
etc...
-> String is also a class, but it is pre-defined class.

1. pre-defined Data Types


2. user Defined Data Types

pre-defined v/s user(developer) defined:


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

Pre Defined / Built In :


------------------------
The Data Types(Classes, interfaces, Annotations, enum...) which
are already created/implemneted and avilable in Java Languge is called as Pre
Defined.

Who implemented String class: Java Lang Team

Student is Pre-Defined class? No

100's of pre defined classes/ interfaces .....

Spring Boot , Pre Defined classes

USer/Developer- Defined:
========================

The Data Types(Classes, interfcaes, Annotations, enum...) which


are created/implemneted by developers as per project req those are called as User
Defined.

String class is user Defined ? No : reason : Java Lang Team impl

Student is User-Defined class? Yes : Dilip


FirstProgram

How to see code of pre-defined classs?

-> Every Object Name is a varible name

Object Creation in Java :


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

<objectName> : User Choice

Synatx : <ClassName> <objectName> = new <ClassName>();

Student dilip = new Student();

What is String ?

Dilip
dilip@gmail.com
dilip123
Dilip@7!9293
#$%^&

Types of Varibale :
------------------

300+ : 12 years
Practical : 10 questions : 5 : 2 : 2
10 : 6 : Quetsions : Not Select

6 : Numeric
char : single char
boolean : tru /false

100;
int a = 100;
short b = 100;

** literals **
How to Store Alphabet Values/ Alpha Numeric Values/ Alpha Numeric Symbols
Values

Values :
Dilip Singh
Java
dilip123
Java21
dilip111@gmail.com

String Data Type: is class


by using String , we can store any values.

Store Alphabet Values/ Alpha Numeric Values/ Alpha Numeric


Symbols Values

Rule : In Java, string Data Type values hsould be enclosed in between " "
always.

String name = "Dilip";


String name2 = Java; In Valid : Compile Time Error
String email = "dilipit123@gmail.com";
String website = "https://www.google.com";

String is lot of importance

Disuccs : TBD :

String : VV IMP :
String Memroy Managment
String Constant Pool
String is immutable
String Value assigned in two ways
-> literal way
-> Constructors
String name = "Dilip";
String name = new String("Dilip"); //

99% -> With out String data Type variable, you will not have a real time.

how to define a varibale in Java?


datatype var = value;
datatype var;

Types of Variables:
===================

Classfied variables into 3 tyeps.

1. Static/Class Variables
2. Non-Static/Instance Variables
3. local variables
1. Static/Class Variables:
=============================

-> Whenever we defined a variable inside a class and out side of


methods
with a key word "static" are called as Static Variables.

-> We can define "n" number of static varibles.

Syntax: static <data-type> <var-name> = <value>;


static <data-type> <var-name>;

public class <ClassName>{

static int age; // valid


static String collgeName;

main(){

static String name = "Dilip"; // No :


Invalid
age = 10;

method1(){

method2(){

}
}

2. Non-Static/Instance Variables:
=================================
-> Whenever we defined a variable inside a class and out side of
methods
those are all called as Non-Static/Instance Variables.

Syntax: <data-type> <var-name> = <value>;


<data-type> <var-name>;

public class <ClassName>{

int age;
String collgeName;

main(){

method1(){
}

method2(){

}
}

3. local variables:
====================
-> Whenever a variable is declred/defined/created inside a
method called as local varibale.
-> Whenever a variable is declred/defined/created inside
a block (Construcors, if blocks, try blocks, finally, catch....) called as local
varibale.

Syntax: <data-type> <var-name> = <value>;


<data-type> <var-name>;

public class <ClassName>{

int age; // Non-Static


static myname = "DIlip"; // static
varibale
main(){

int year = 2024; // local Varibales


String name;
if(){
String gender;
}
}

method1(){
String email;
}

method2(){
boolean areYouOkay;
}
}

-> Where to define what type of varibale? static vs non-static vs local


-> if we are not following, the actual concept of each variable type, what
will be the disadvantages.

Defined -> Creation of Varibale First time

USing/Utilizing

Req :
=====
College : ABC College
Established : 2011
Principal Name = Dilip Singh
Collect All Students Information
Stident Id
Full Name
Mobile
Gender
Year OF DOB
total
avg marks

Static vs non-Static

class -> Many

-> In Java, When We created instance(non-static) varibales

-> Whenever We creates an Object for the class, for every Object,
instance varibales are allocated with their respective sizes and values.

-> Instance varibales are initilized with default values whenever we


created an object if those varibales does not have any value.

CollegeStudentsData s1 = new CollegeStudentsData();

CollegeStudentsData s2 = new CollegeStudentsData();

CollegeStudentsData s3 = new CollegeStudentsData();

-> Whenever we created an Object, that will be created always inside Heap
Memory

byte/short/int/long -> Numeric -> 0


double/float -> 0.0
boolean -> false
Non-Primitive : String, Student , Integer
ArrayList etc... -> null

instance = Object

instance Id/Name = Object name/ID

How many instances Created?


How to change value of Instance variable?

Syntax: objectName.varName = value;

101, Maneesh, M, 1111111, 600, 70.88 etc..


102, Dinesh, M, 3333333, 500, 60.90 etc..
103, Veena, F, 45566566, 700, 80.99 etc...
..
..
110 ...............................

Default values are replaced.

-> If data of varibale is common across all objects, then please


define those varibales as static varibales.

-> If data of varibales is different across all objects, then


please define those varibales as non-static/instance/Object varibales.

int -> 5 instance varibale


int -> 2 static varibales

10 created Objects

How much memory is allocated :

10 * (5 * 4) Bytes =
10 * (2 * 4) Bytes =

10 * (5 * 4) Bytes
(2 * 4) Bytes =

0 Objects :
-> 2 * 4 Bytes

Req :

Product Information from Apple Company

Company Name
Company Emp Count
Company CEO
Product Name
Product Price
Product launchingYear

Many Objects/Products

How to choose stattic vs non-static?

Static : Company Name : Apple


Static : Company Emp Count :
Static : Company CEO

Product Serial Numbers : Non-Static


Product Name :
Product Price
Product launchingYear

Dynamic Person :

He/she will take based on situation

Static : Fixed

Calculaor:

WAP , take 2 values and print result of


addition, substraction, mul, div.

-> Local Varibales we will define to to store temparoy


information as part code logic impl.

let a =40 , b=20?


result of a/b

let result = 0;
result = a/b;
result = 40/20;
result = 2;

80% -> Current Topic


<------------------- back
revision -> practice
70% -> Current topics
30% -> Already topic Complted

90% > non-static / static ?


Object Oriented PL

Accesbility of Varibales From Methods :


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

Static / Non-Static Varibales:

class {

static int a;
double a;

}
No : Varibale names should be unique, duplicates varibale names are not allowed.

-> We can access static variables directly where ever we want in any type of
method.

-> We can access non-static variables directly only from non-static methods but not
from static methods.

-> If we want to access non-static varibales from static methods, we should use
always instance reference/ Object Name.

TBD:

Methods :
Tyeps Of MEthods
1. Static methods
2. Non-Static Methods

Different tyeps of varibales accessing from Diffrent types of methods:

Static varibales -> NS methods


Non Static varibales -> NS methods

Static varibales -> Static methods


Non Static varibales -> Static methods

Methods In Java?
----------------

What is Method?
---------------

C/CPP : Functions -> Java : Methods


-> Method is set of instructions to achive a
functionlity/task/activity.

Ex:
Please calculte EMI Value for loan amount.

Identify Formula

EMI = P x R x (1+R)^N / [(1+R) ^N-1]

P = 100000
I : 11
60 MOnths

Result EMI : 27749

3 I/P Values :

O/P : 1 value

Please take 2 values and come up with Airthmatic


operations

add
sub
mul
div

addition :
a=10
b=30
result = a+b= 10+30 = 40
Sub:
a= 20
b= 10
result = a-b = 20-10 =10
div
.............
mul
..............

-> Methods may have i/p values and o/p values.

1. Methods will take i/p values and produces result


2. Methods will take i/p values and produces no result
3. Methods will not take i/p values and produces result
4. Methods will not take i/p values and not produces
result

-> In a single java class , we can write n no.of methods

Types of Methods :
----------------
1. Static Methods
2. Non Static Methods

How to write Methods in Java:


-----------------------------
Ruels and Regulations:
---------------------

1. Static Methods :

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

Syntax :
--------

<access-specifier/modifier> static <return-value-data-type>


<method-name>( 0 or more Arguments){

//Logic
// Set of instructions
// 1 line to 100 lines

<return statement> /<No Return Statement> <value>;


}

Ex:
public static void addition(){

//logic
}

-> Variable Names Rules applicable for Method Names


-> Developer we can use any method Names
-> () -> Paranthisi Braces

Access Specifiers:

public
private
protected
default

Planning to Buy a mobile :


you don't have mobile

Cash -> After Noon : Iphone 16 Pro

Action Item : Frined

i/p: cash
-> Visit Apple Store
-> Findout 16 pro
-> black color
-> Pay the amount

o/p: result : returing phone to you.

1. Methods will take i/p values and produces result


2. Methods will take i/p values and produces no result
3. Methods will not take i/p values and produces result
4. Methods will not take i/p values and not produces
result

2. You are attending Wedding Party


-> Return gift

-> No I/P -> instructions > Return a gift

Ex:
public void addition(){

//logic
}

void : this is a key word, given by Java lang.


=====
-> void is used to declare method is not returing back any result after
execution of logic.

return : this is a key word, given by Java lang.


=====

-> return is used always inside methods, to return a value back to the
caller method.

-> when method signature is having void , can we return any real value
inside method logic?
No

<return-type> : <return statement>


void -> No Retrun statement
int -> return along with only intger type value
String -> return along with only String type values

1. Get Mobile nUmber always : int /long

2. Get Course Name : Value : String

3. Print All IOnforamtion of Course : void


-> Any method can call any other methods

-> In A method return statement should be used as last


satement.

Method Arguments/Parameteres:
--------------------------------

Method Arguments are being used to pass values to that method.

-> Create a method , and that method should take 2 values and that
method should return addition result value

// 0 arguments

<access-specifier/modifier> static <return-value-data-type>


<method-name>( ){

//Logic
// Set of instructions
// 1 line to 100 lines

<return statement> /<No Return Statement> <value>;


}

-> // 0 > arguments

<access-specifier/modifier> static <return-value-data-type>


<method-name>(<data-type> <arg/var-name>, <data-type> <arg/var-name> ......){

//Logic
// Set of instructions
// 1 line to 100 lines

<return statement> /<No Return Statement> <value>;


}

D:\Classes\B2-Sep-18\programs>javac MethodArgumentsDemoOne.java
MethodArgumentsDemoOne.java:6: error: method addition in class
MethodArgumentsDemoOne cannot be applied to given types;
int result = addition();
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
MethodArgumentsDemoOne.java:9: error: method addition in class
MethodArgumentsDemoOne cannot be applied to given types;
result = addition();
D:\Classes\B2-Sep-18\programs>

Req :

Write a method which should print given name value always.

What is return type of method? No return : void


How many method args are requied? 1 method arg : String

public static void printName(String name){

System.out.println(name);

Req : write a method which should print email and age of a person

What is return type of method? No return : void


How many method args are requied? 2 method args : String, int

public static void printEmailAndAge(String email, int age){

System.out.println(email);
System.out.println(age);
}

Rule :
-----
When a method having an arguments, then caller should pass always all
argument values.

When a method having an arguments, then caller should pass always all
argument values aling with argument type of order.
2. Non Static Methods :

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

Non-Static Methods :
-------------------

A method is not delcared with static keyword, it will be called as non-static


method.

Syntax :
--------

<access-specifier/modifier> <return-type> <method-name>( 0


or more Arguments){

//Logic
// Set of instructions
// 1 line to 100 lines

<return statement> /<No Return Statement>;


}

static variable vs non-static

static int a = 10; -> Behaviour -> Completely Diff from : Method ARea/Class Area :
singel copy

int a = 10; : On eVery Object Creation : 1000 Objects : 1000 copies

-> > 90% , we will always non-static varibales and non-static methods

-> Object OP

Rules :
------

-> Write methods which takes 2 i/p integer values and return result of
addition, subtraction, div, mul;

D:\Classes\B2-Sep-18\programs>javac NonStaticMethodsDemo.java
NonStaticMethodsDemo.java:7: error: non-static method addition(int,int) cannot be
referenced from a static context
int result = addition(10,20);
^
1 error

D:\Classes\B2-Sep-18\programs>

-> In Java , we can't call/access non-static methods from the static methods
directly. We have to access always by using an Object/Instance of that class.

objename.method(arg-values);

-> Same rule applicable for varibales also.


In Java , we can't call/access non-static variables from the static methods
directly. We have to access always by using an Object/Instance of that class.

-> static content of a class, we can access directly from either non-static methods
as well as static methods.

-> Non-static methods can be accesible directly from non-static methods.

Calling From : Called One

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

From Static Method accessing Non-Static method : object required

Static Method accessing Static methods : No Need


of Object
Non-Static Method accessing Static method : No
Need of Object
Non-Static Method accessing Non-Static method : No Need of
Object

Variables also same behaviour:


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

From Static Method accessing Non-Static varibales : object


required
Static Method accessing Static varibales : No
Need of Object
Non-Static Method accessing Static varibales : No
Need of Object
Non-Static Method accessing Non-Static varibales : No Need of
Object

public class StaticNonStaticVaribales{

static String collgeName = "ABC College";


int collgeCount = 300;
public static void main(String[] y){
System.out.println(collgeName);
System.out.println(collgeCount);
}
public void printCollegeData(){
System.out.println(collgeName);
System.out.println(collgeCount);
}
public static String getCollegeName(){
return collgeName;
}
}

-> call : objename.variablename;

Assignment :
===============
non-static : addition(double,long)
static sub(int a, int b);

main() -> addition -> sub();

Assignment :
===========

Write a Prog, Which should print your Details

-> varibales

-> Create Static Method , where it should take i/p of Static content
-> Non-Static Method : Take non-variables

15 ex : Don't worry about quantity

20 Prog:

2 Prog : Quality of practice

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

Accessing Methods/Varibales from Different Classes:


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

1. From Static Method accessing Non-Static method of other class


: Create an Object for that other class and by using that
ref. we will call the method (object required)

objeName.methodName(arg-values);
2. From Static Method accessing Static method of other class
: Create an Object for that other class and by using that
ref. we will call the method (object required)

-> Static methods are called by using class Name.

ClassName.MethodName(arg-value);

3. From Non-Static Method accessing Other class Static method


:
-> No Need of Object
-> Static methods are called by using class Name.
ClassName.MethodName(arg-value);

4. Non-Static Method accessing Non-Static method of other class :

-> Create an Object for that other class and by using that
ref. we will call the method (object required)

-> objeName.methodName(arg-values);

Summary :

If it is static method , ClassName.methodName(values);


If it is non-static method , objectName.methodName(values);

Accessing Variables in b/w classes:


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

A{
int a = 10;
static int b = 30;

B{
// access A class a, b varibales

Summary :

If it is static variable , ClassName.varibaleName


If it is non-static variable , objectName.varibaleName(values);

Comments in Java:
===============

-> Comment is all about description what we are writing in side a program.
-> COmments are helpfull to improve readability of a logic
-> Comments are always ignored by Java Compiler.

Single line comments :

// is used to write comments in a line


// single line
// second line

Multi line comments :


/*
line1
line2
,,,,
*/

public class Calculator{


public static void main(String[] args){

// Creating an Object for the class Calculator


Calculator c = new Calculator();

//Calling addition of Calculaotr calss by using reference


int result = c.addition(20,80);
System.out.println(result);

// Callign static varibale by using class Name


result = Calculator.mul(5,20);
System.out.println(result);
}
public int addition(int a, int b){
System.out.println("This is Addition From Calculator Class");
return a+b;
}
public static int mul(int a, int b){
System.out.println("This is mul From Calculator Class");
return a*b;
}

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

public class Calculator{


public static void main(String[] args){

Calculator c = new Calculator();


int result = c.addition(20,80);
System.out.println(result);
result = Calculator.mul(5,20);
System.out.println(result);
}
public int addition(int a, int b){
System.out.println("This is Addition From Calculator Class");
return a+b;
}
public static int mul(int a, int b){
System.out.println("This is mul From Calculator Class");
return a*b;
}

Question:
==========

Can we access local varibales of class from another class or not?

-> Local varibale scope is until that block only.

A{
static
non-static
m1(){

int a =20;
... 40 lines of logic
}

m3(){
can I access "a" varibale from m1() method?
}

B {

m2(){

a varibale of A class?
}

No : Local varibale scope is until that block only.

Assignment : Take baove Question as a program and note down the error and know the
answer.
-> With in the class, in b/w different methods
-> Out side of the class

-> Pre Defined Methods v/s User Defined Methods


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

Pre Defined/built in : Which are already presented in lang it self


User Defined : Impl by Developer

-> Pre Defined Class ? String

what about the content of String class?


varibale & methods : by Java Team

-> Methods which are already defined by lang are called as pre defined
methods.

Calculator : User Defined : methods add, sub. mul.... User defined Methods

String Class:
=================
String :
toUpperCase()
toLowerCase()

How many methods avaibale in String class ?

40- 50 methods

API documentation:
=================
API : Application Programming Interface

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

For String varibales , we can assign/initilize values 2 ways:

1. literal way of initilization

String name = "Dilip";

2. By using instance creation : new


ClassName objName = new ClassName();

String name = new String("Dilip");

// Constructors

TBD: String Class


-> Usage
-> Memory Management
-> SCP

Assignment :
-----------

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

Method Summary:
String name = "Java Language";

char c = name.charAt(3);

a : actuall
v : expected

In Java language , index always starts from 0

0 -> 1st
1 -> 2nd

Human : index always starts from 1

String name = "Java Language";

char c = name.charAt(4);

String concat(String str)


Concatenates the specified string to the end of this string.

attaching / joining:

String firstName = "Dilip";


String secondName = "Singh";

0/p : Dilip singh

String fullName = firstName.concat(secondName);

=> In String type, "+" is used as concatnation operator

int a = 10;
int b = 30;
int c = a + b;
c value ? 40

String firstName = "Dilip";


String secondName = "Singh";

String fullName = firstName+secondName; // + behaing as concat()


method
fullName value? DilipSingh

Interview Question:
------------------

int a = 10;
int b = 20;
Sop(a+b);
String result = "Addition of : ";
SOP(a+b+result);

SOP(result+a+b);

contains()
Dilip -> ab : no
Abcd -> ab : No
abcd -> ab : yes

indexOf(int ch)
Dilip -> l -> 2

String replace(char oldChar, char newChar)

Dilip -> replace -> i with e

String name = "Dilip Singh";


name= name.replace('i','e');

SOP(name) ; Delep Sengh

Real Time Application :

Day to Day Activities

FE <-> BE <- Logic -> DB

abcd123x -> coverting to Upper Case -> ABCD123X

abcd123x -> Value Should be stored in DB always upper case;

dilip123xyz -> Write your own method

-> d -> D
i -> I
// Logic

DILIP123XYZ
2 -3 hours

Java Lang Team : Methods : Access that method : 1 min

Integer :
String value to intrger :

String "1234" -> int 1234

Integer.parseInt("1234"); -> int 1234

https://docs.oracle.com/en/java/javase/17/docs/api/index.html
https://devdocs.io/openjdk~17-package-java-lang/

key words in java:


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

Reserved few words for different activities and functionlities.

to create java class :


class <ClassName>{

int age = 30;


data type : int is reseerved word:

int Student{

// Inavlid
}

End of Core Java :


50 Key words : Diff Concepts

char -> Single Character

double ->

-> Key words can't used as class Names, variable names, method names etc..
-> That Means. every keyword will have it's own functionlity. In such
scenarios only we ahve to utilize / use keywords respectively.

int char = 10; // Invalid

int Char = 200;


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

public class Test{

public void long(){

}
==========================

IDE : Integrated Development Environment:


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

Editor to write Java Programs/ Java Applications

-> writing Java Prog: Note Pad


-> Compilation : Command Prompt: javac ...
-> Execution : Command Prompt: java ...

RealTime Projects:
-----------------
100% difficult

We will use always IDE's

IDE , this will enables easy way of developemnt, testing and debugging
environment.
IDE will enables all activites in GUI mode.

IDE is n/b a software.

Eclipse IDE (Open Source), IntelliJ IDEA (Free + Paid)

Download eclipse:
================

https://www.eclipse.org/downloads/packages/release/2024-09/r/eclipse-ide-
enterprise-java-and-web-developers

https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/
release/2024-09/R/eclipse-jee-2024-09-R-win32-x86_64.zip&mirror_id=1273

IntelliJ : https://www.jetbrains.com/idea/download/download-thanks.html?
platform=windows&code=IIC

zip file
-> extract

-> Examples , till today you are done, practice Again in IDE also.

-> click on eclipse.exe

Workspace Path:
================

Workspace : This folder will contains all your java projects / code

How to write java program in eclipse:


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

-> we can't write individual program directly.


-> We have to create a project first.

File -> new -> Project -> Java Project


-> enter project name
-> select java version java 21
-> un select create Module incase it got selected.
-> finish

Open Perspective -> Yes

-> expand project > src :

Source Code :
-> right click on src
new -> class
Enter class Name :

bin : binary data : ready to execute

Compilation : No : IDE is taking care


. class : in side bin folder in that project.

Execution :
=============
Right click on java file : Run As -> Java Application

packages in java :
------------------

package is n/b a folder/directory, which contains java files.

Creating Package :

-> when we care a class inside a package, we should use package keyword.

-> package statement should be always 1st line of the program, it should be
out of class definition.

Created 2 java files in same package:


No issuess while you are calling methods each other

Created 2 java files in diff package:


issuess while you are calling methods each other

Error:
AddditionOfValues cannot be resolved to a type

import :
======
import statement;

import statement will represent from which package you are using the other
class in current class.
Rule:-> import statements aredefined out side the class only and make sure
after package statement.

syntax :
import packagename.ClassName;

pkg: englishmovies;
Class1.Java
Class2.java
Class3.java

No need of import , all are in same package,

diff pkg: englishmovies;


Class1.Java
Class2.java
pkg: hindimovies;
Class3.java

Class3 -> access -> Class 2 : import


englishmovies.Class2;
Class1 -> Class2 -> No Import: Same packge

diff b/w import & package?

-> 100% Real time Project conatins always packages.

Pre-Defined packages : already impl & Provided by Java Lang.


User-Defined packages : Impl by Developer in that application/project
default package in java :

package : Contains always

Classes, Interfaces , Annotations, Enmus etc...

-> a class will laways maintained as part of package.

Pre Defined Class : String

String is belongs to which package?

many packages:
String belongs : package : java.lang

java.lang : Contains many classes and interfaces.


API documentation

java.io
java.lang
java.sql
java.util
java.time

Package java.lang
Provides classes that are fundamental to the design of the Java
programming language.

java.lang.String : Absoulte CLalss path

java.io.File

Java Lang made java.lang as a defult package.

what is default ?

No Need speicfically mention about it.

one and only pkg java.lang as default packge.


When we are accessing any class/interfaces from java.lang
packages no need to specify import satement.

-> Other tha java.lang content , we have to use always import statement
with package information.

what is . symbol?

-> sub packages

How to write better packages names:


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

Movies
Hindi
English
Spanish

D:\Movies\English\action
D:\Movies\Hindi
D:\Movies\Spanish

Swiggy :

customers
resrtaunts
food information
cart
payment
delivery boy
delivery
complaints

swiggy
Signup.java
======================================
swiggy<f>
customer<folader>
Signup.java
resrtaunts<folader>
Signup.java

swiggy/customer/Signup.java
swiggy/resrtaunts/Signup.java

windows : Sub folders

packages :
swiggy.customer.Signup.java
swiggy.resrtaunts.Signup.java

package names :

swiggy.customer.payment
swiggy.payment
swiggy.delivery
swiggy.delivery.boys
swiggy.payment.upi

swiggy
customer
payment
payment
upi
delivery
boys

-> If we want to see information of Pre Defined classes ,


in Eclipse : Ctrl+Shift+T : pre Defined Class Name

How to write valid package names ?

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

1. Step : For which business (Client) creating the


project

infosys : swiggy : client

Domain: https://www.swiggy.com/

-> package name starts always with domain name : swiggy.com


-> we have to make sure domain name is swapped.

swiggy.com
pkf :
com.swiggy
swiggy :
project:
src :
com.swiggy

-> RT , package name always starts with domain name

com.swiggy.customer.payment
com.swiggy.payment
com.swiggy.delivery
com.swiggy.delivery.boys
com.swiggy.payment.upi

instagram.com
com.instagram.<modulename>.<functionlity>

Naming Convnetions in Java:


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

Guidelines of Names

Rule: Not follwoing , then things will not work.

Guide Lines :
Better way,

Guidelines/standards to follw while provding Names in Java


Program:
---------------------------------------------------------

Class Names : Student, Productinformation ....


Variable Names : age, year, NoOFStudents, etc...
Method Names : add, getCollegeInfo.....
package names : com.swiggy, com.instagramm..
project Names : swiggy......

-> standards people will across world.

Class Names :
-------------

Rule : -> Class Name should not Contain Spaces

StudentInformation : Valid
Student Information : In Valid

Person : Class Name :

student.java
Student.java
STUDENT.java
StUDenT.java

is there any invalid Class Name, compile time?


Class Names :
----------------
-> Every Word First Character should be in Upper Case ,
remaining in lower case.

Student
StudentInformation
STUDENTMarks
Productdetails
ProductInfo
product
student
calculator
ORDERINFORMATION

public class student{

}
public class Student{

-> Variable Names & Method Names:


=================================
-> For variables and method names, we will use camel Case.

camel case :
===========
First Word should in lower case, second word onwards First
Character should be in Upper Case , remaining in lower case.

age
CollegeName : collegeName
Name : name
Year : year
CompanyName : companyName
GENDER
emailID
FIRSTName
conatctEmailID : conatctEmailId

method names :
charAt
toUpperCase
toLowerCase
getCollgeInformation()
makePayment(long creditCardNumber, int cvv, int
expYear)

packge Names :
=============
-> names always in lower case
-> every word is separted by .

com.swiggy.customer.payment : valid
com.swiggy.customer.Payment : No Compilation Error ,
No standards

project names:
==============

-> keep in lower case


-> every word is separted by -

swiggyapp
swiggy-app
mypractice
my-practice

Operators:
=============

AN Operator is used to do an Operation.


-> Adddition ,S ub
-> Comparision
-> incrent ment

10,20 : Add =>

10 + 20 = 30

10,20 : Operands

1. Assignment Operator
2. Arithmetic Operators
3. Unary Operator
4. Equlaity & Realtion Operators
5. Conditional Operators
6. Ternary Operator
7. Bitwise Operators

assogn value 10 to a , a = 10;

1. Assignment Operator
===========================
= : Assigning values

2. Arithmetic Operators:
========================

5 operators

+ : addition
- : subtraction
* : Multiplication
/ : Divison
% : Remainder

21 divided by 4
Quotient : 5
Remainder : 1

3. Unary Operator
===================

Unary : Single Value

+ : Positive Number
- : Negative value
++ : Increment Operator
-- : Decrement Operator
! : not Operator

write a positive Number : 1000, +1000


Specifically we will not use positive symbol
write a negative Number : -23377

++ : Increment Operator
==========================
whenver we applied ++ on a varibale belongs to Numric, then
that variable value is incremented by 1 and new value will be reassgined back to
same varible.

++a => a = a +1;

-- : Decrement Operator
==========================
whenver we applied -- on a varibale belongs to Numric, then
that variable value is decremented by 1 and new value will be reassgined back to
varible.

--a => a = a-1;

unary operator as prefix / suffix :


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

prefix : ++variableName

Execution :
if it is prefix , then immmediatley value will be
incremented and then assigne back to same varibale , aftegr that only the next
action will be performed in which case we used that unary operator.

int x = 100;

int y = ++x; // 101

suffix : variableName++
===================

Execution :
if it is suffix, the actual value of variable istake
into consideration for that activity and then after executing that activity, then
only the value will be incremented and assged back to same variable.

int x = 100;

int y = x++;

! : Not Operator
==========================================

! operator is used always along with boolean value.

true/false

! operator will be used to inverse the boolean value.

!true = false
!false = true;

boolean areYouMale = true;


areYouMale = !areYouMale;

SOP(areYouMale); //
SOP(!areYouMale); //

Graduations Student Data :

CSE
EEE
CE
ECE
MLE
AIE

1000 Studets

Req : Get All Students iformation who are not


belongs to EEE

s1 : CSE
student.branch != EEE
selected

Equlaity & Realtional Operators :


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

These operators will determine operands are equal , min ,max.

1. == : Double Equals
2. != : Not Equals
3. > : Greather Than
4. >= : Greater Than or equals to
5. < : Less Than
6. <= : Lesser Than or equals to
a= 10;
b=9:
a > b ? true
10 > 9 ? ture

b>a ? false

Note : The result of above 6 operators is always a boolean value.


result always is either true or false

== : Equals or not
====================

operand1 == operand2
-> Operand1 is equals or not
if it is equal, then returns true
if it is not equal, then returns false.

!= : Equals or not
====================

operand1 != operand2
-> Operand1 is not equals or not
if it is not equal, then returns true
if it is equal, then returns false.

int a = 100;
int b = 200;

boolean isSame = a != b; // true / false

3. > greater than


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

my age > my cusion

35
30
35 > 30 : true

35
40
35 > 40 : false

-> LHS operand is greater than RHS operand, then result is : true
otherwise false.

LHS operand is lesser than RHS operand, then result is : false

30 > 30
==> 30 is greater than 30 : in valid : false
==> 30 is lees than 30 : in Valid : false
-> No value is greather than or lesser than it self.

4. >= greater than or equals


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

-> LHS operand is greater than RHS operand, then result is : true

as well as

LHS operand is equuals to RHS operand, then result is :


true

-> LHS operand is lesser than RHS operand, then result is : false

a = 99;
b = 99;

a > b : f
b > a : f
a >= b : t
b >= a : t

5. < lesser than


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

10 < 20

-> LHS operand is lesser than RHS operand, then result is : true
otherwise false.

LHS operand is greater than RHS operand, then result is : false


40 < 30 : false

-> No value is greather than or lesser than it self.

6. <= lesser than or equals to :


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

-> LHS operand is lesser than RHS operand, then result is : true

as well as

LHS operand is equuals to RHS operand, then result is :


true

-> LHS operand is greather than RHS operand, then result is : false
! 2000 <= 1900 ->

10 mins :

a = 10
b = 10

10 - 15 : Mins : Individually:
progrmming :

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

-> First -> Analysis :

Question 1 :

int x = 5;
x = x++ + ++x;
System.out.println(x);

Question 2 :
int x = 10;
int y = x++ + 5;
System.out.println(y);

Question 3 :
int x = 10;
int y = ++x + x++;
System.out.println("x: " + x);
System.out.println("y: " + y);

Question 4 :

int a = 5;
int b = a++ + --a + ++a - a--;
System.out.println("a: " + a);
System.out.println("b: " + b);

Question 5 :
int x = 7;
int y = x-- + --x;
System.out.println(y);

Question 6 :
int x = 2;
int y = ++x + x++ + --x;
System.out.println(y);

Question 7 :
int x = 5;
x = x++ + ++x + x++;
System.out.println(x);

Question 8:
int i = 4;
int j = --i + i-- + i++;
System.out.println(j);
=================================

Logical/Conditional Operators :
=============================

Condition :
if you are doing it now, then I will do that

1. Logical-AND / Conditional-AND : &&


2. Logical-OR / Conditional-OR : ||

-> Conditional Operators are used to join multiple conditions and


making result out of it.

-> conclusion/result of all conditions.

statement:

People who got 70% , they are eligible:

statement 1:
People who got more than 70% and female persons, they are
eligible:

statement 2:
People who got more than 70% or persons are female, they are
eligible:

Dilip 90% M -> stmt 1 : NE


Dilip 90% M -> stmt 2 : E

Gowthami : 66% F -> stmt 1 : NE


Gowthami : 66% F -> stmt 2 : E

Suresh 55 M > stmt1 : NE


Suresh 55 M > stmt2 : NE

AND -> All Conditions should be satisified : true otherwise :


false
OR -> Either Of the Condtion is satisfied : true , all not
satisfied : false.

AND Operator : &&


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

&& operator is used to join mutiple conditions:

condition1 && condition2

both LHS , RHS conditions are true , result is true otherwise


false:
problem statement 1:
People who got more than 70% and female persons, they are
eligible:

percentage > 70 && gender = Female


90 > 70 && Male ==Female : false
true && false : false

88 > 70 && FEMALE == FEMALE


true && true : true

OR Operator : ||
------------------

|| operator is used to join mutiple conditions:

condition1 || condition2

=> either LHS or RHS conditions are true or both are ture , result is
true

=> either LHS or RHS conditions are not true (both are false) result is
false

problem statement :
People who got more than 70% or persons are female, they are
eligible:

percentage > 70 || gender = Female


90 > 70 || Male ==Female : true
true || false : true

88 > 70 || FEMALE == FEMALE


true || true : true

66 > 70 || MALE == FEMALE


false || false : false

-> to make one condition , equlity / relational operator


-> to join many conditions : Conditional operators
-> the result of conditional operators statements is always
boolean data type .

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

?: Ternary (shorthand for if-then-else statement):


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

?: => Ternary Operator

This Operator defines conditions and when condition is true


returns the result and when condition is false in such case also it will return
result.

syntax :
=========

< condition> ? <result on true> : <result on false>;

< condition/s > ? <result to be returned - on true> : <result to


be returned - on false>

Example :

int a = 60;
int b = 80;

int result = a > b ? b : a;

String result = a < b ? a : b;

Example :

//People who got more than 70% and female persons, they are eligible:

// A : F : 60 -> Not Eligible


// B : F : 71 : Eligible
// C : M : 90 : Not Eligible

Result Data type : String

String result = percentage > 70 && gender == 'F' ? "Eligible" : "Not Eligible" ;

// A : F : 60

60 > 70 && F=F


B : F , 71
71 > 70 && F=F
true && true
true

=> Asgginment :
===============

Please convert yesterday conditional operator


examples to Ternary operator.

instanceof operator:
---------------------
After the topic : Super Class / Sub Class

" instanceof" : Compares an object to a specified type

=> When we want to know an Object/instance belongs to exactly which class.

College c = new College();


Student s = new Student();

s instanceof Student => true


c instanceof College => true

Parent p = new Child();


p instanceof Child => true
p instanceof Parent => false

Bitwise Operatros : TBD


===================
Create OS , Compilires

~ Unary bitwise complement


<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

https://www.rapidtables.com/convert/number/decimal-to-binary.html?x=999

Equlity & Relational Operators : -> Making individual COnditions


Conditional/Logical Operators: -> Joining the conditions and then evaluating

Control Flow Statements:


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

Java Compiler/executor takes flow top - bottom


To control that execution flow based on conditions results , then
java provided Control Flow statements.

-> Control statements are going to decide wheather logic should be executed or
not.

1. Decision/Selection Making Statements


2. Looping/Iteration Statements
3. Branching/Jumping Statements

1. Decision/Selection Making Statements :


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

Decision -> based calcultion make satements.

=> These statements will decide which logic should be executed and not
executed based on condition results.

number%2 == 0
if LHS result is 0 and then overal statement result
is true
this is a Even number
if not LHS result is 0 and then overal statement
result is false
this is a Odd number
1. if statements
2. if - else statements
.....if else if....
3. nested if / if else statements
4. switch statement

1. if statement:
-----------------
if ... condition

not given bike -> false -> not giving party

given bike -> true -> giving party

synatx :
================

if : key word

if(condition/s){ // if block starting

// logic -> this logic is going to execute when


condtion result is true

} // if block ending

=> if block

=> { } : block

=> When conditions result is true , then if block logic will be


executed otherwise if result is false, then if block will not be executed and
executor will move to next line of if block.

2. if - else statements:
==========================

if : key word
else : keyword

if(condition/s){ // if block starting

// logic -> this logic is going to execute when


condtion result is true

} // if block ending /

else{ // else block starting

// logic : condition result is false , this logic will be


executed

} // end of else block


=> When conditions result is true , then if block logic will be
executed otherwise conditions result is false, then if block will not be executed
and executor will move to else block and else block will be executed.

-> if condition is true if block otherwise else block.

3. if..else.if.. : if else ladder


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

-> Wehen we are joining more than one if...else.. blocks togeather is
called if else if ladder.

synatx:
========

if(condition/s){ // if block starting

// logic -> this logic is going to execute when


condtion result is true

} // if block ending /

else if(conditions){ // else block starting

// logic : condition result is false , this logic will be


executed

} else if(condtions){

} else{
// default
// All above if block conditions are false
}

Req :
=====

Loans :
-----------

Dilip Loan : 100000


cibilScore : 740

Xyz : 666 : 200000

CIBIL score :

500 < Loan rejected

501 - 600 : Process , Verify : Income, Company Details, Address

601 - 700 : process , Verify : Income


701- 750 : process : Checking limit

> 751 : Approved for amount

-> At very condition result level , we are having a different logic

5. nested if statement;
-----------------------

an if statement logic/block conatins another if statement that is


called as nested if satement :

syntax :
---------
if(conditions){
//logic
if(condition){

}else if(){

}else{
if(){

}else{

}
}

}else if(conditions){
//logic
if(conditions){

}else{

}
}else{

thougt process :
===============

Assignmetns :
--------------

goals:
if(success){

}{
// Job
// foreign
//
}
Offers :
billingValue = 5000;

billingValue > 2000 to 4999


5%
deduct 5% from bill : print final
maount : 2850
billingValue >= 5000 to 9999
10%
deduct 10% from bill : print final maount
: 4500

->

<5k
5k -10k : 1000 of
10-15 : 1500

=============
eduction :

if(pecrcentage > 75)

75-60

50-50
=============
Offers : Billing Price Range and discount:
====================================
<5000 : 0%
5000 - 8000 10%
7000 -700
6300

8000-16000 : 15 %
10000-1500
8500
16000 > 20%

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

switch statement:
----------------

This is an alternative for if else if ladder statemetns.

switch statement is used to write specific logic for specific values.

Time Table :
------------

SUN ->

MON - SUN

MON -> Study, Walk


TUE -> Study, Visit
WED
THU
FRI
SAT
SUN -> WALK, MOVIE, DINNER

TUE ->
MON->

String weekDayName ="TUE";

-> if(weekDayName == "SUN"){

// Sunday Activites
}else if(weekDayName == "MON"){
// Monday : logic
}else if(weekDayName == "TUE"){
// Tues
}else if(weekDayName == "WED"){
// Wed
}else if(weekDayName == "THU"){
// Thu
}else if(weekDayName == "FRI"){
// Frida
}else if(weekDayName == "SAT"){
// Satu
}else{
// in valid: week day
}

int result = val1 + val2; // expression -> Value

Syntax:
-------

switch
case
break
default

switch(expresion/value){

case <value1> :
// logic
case <value2> :
// logic
case <value3> :
// logic
case <value4> :
// logic

case : Block
swithc statement conatins logic always in form wiriting case blocks.

-> Whenevr case value is matched with switch value, then that specific case logic
executed. and then rest of the should be ignored.

-> we can pass values of ant data type.


String
int
double
char

-> whatver data type value is defined at swithc level, same data type values should
be defined at case level.

-> case values should not be duplicate.

-> whenever we defined cases in switch, please make sure breaking the logic
execution.

-> break : This is a keyword.


=========

break will represents, exiting the logic exectuion from that block.

syntax:
break;

-> break key word, we can use in another concepts also not only on switch

-> every "case" should end with break satement.


-> last line of the case should be always break.

default block:
==============

in switch statement, we can define default block byusinf default


key word.

synatx:
default:
//logic

-> default block will be executed always whne no there no mtach with case
values.

-> switch satement -> 100% if else if

-> if else if -> switch

Assignment :
=------------

Req :
Create Calculator Application ,

ADD
SUB
MUL
DIV
REM

take 2 values always.

You have to pass which Operation should be done on two values always.

int a = 10;
int b = 30;

=> if else if.. / switch / both?

String operationType = "SUB";

switch(operationType){

case "ADD":
sop("Addition of 2 vakues ")
int result a+b;
sop(result);
break;

Req :
======

Grades :
> 90 -> A
80-90 -> B
80-70 -> C
70-60 -> D
< 60 -> F

i/p:
percenatge value : 1 - 100

switch / if else if / both?

Dilip : 77 -> C
xyz : 44 -> F

1-100
switch : wrong choice : 100 cases
100 cases :
case 1
case 2
case

if else if
if(90>)
A
else if(80> <90){
B
}

Sub Req:
========

Define a method for printing benefits of every grade.

i/p : grade

A -> 50% fee Off


God Medal
B -> 20% feee off
silver
C -> gift

D -> certifciate

F -> WARNING :

switch. if else if
-------------------

switch :

with integer values


with char data type
with double/float type.

2. Looping/Iteration Statements:
=================================

Loops in Java :
===============

what is a loop?

Lopping : Statements are executed recursively/repeatedly until a specific


condition is complted.

1. for
2. while
3. do.. while

Arrays :

for each
1. for loop :
-------------

for used for iterating logic execution until a specific condition is reached.

syntax:
for .. Key wkord :

for(starting point/initilization ; condition evalution ;


increment/decrement operation){ // starting point of for loop logic

//loigc

} // endpoint point of for loop logic

3 parts :
-> Starting Point

initilization
condition check -> true -> enter intside for loop: body exucted -
> increment/decrement section
condition check -> true : body exucted -> increment/decrement
section
condition check -> true : body exucted -> increment/decrement
section
condition check -> true : body exucted -> increment/decrement
section
condition check -> true : body exucted -> increment/decrement
section
condition check -> true : body exucted -> increment/decrement
section

condition check -> false -> exit/leave the for loop

Assignment :
===========

Req :

-> A person should complete 20 rounds of Running Track .


On very single round compltion, person should say
"Hi"

Req :

Students :
100 students : student ids : 100 - 200
print student id's :

Req :
Print 5 division values under the range of 333 to 999
reminder = 0
335
340
345
...
995

white paper :

Problem: requirements :

do the analysi on that problem :


for : compiler/jVM
make : formula / solution

-> Java Progrma:

2.while loop:
-------------

logic executed repeatdely until a condition is broken.

while -> key word

synatx:
------

while(condition){ // starting of while loop

// logic : Repeatdely

} // end of while loop

Req :
print values from 1 to 10:

Starting : 1
Ending Value 10
Increment way

// initilization value varibale

while(condition : initilization value varibale ){ // starting of


while loop

// logic : Repeatdely

// last line level : increment/decrement operation on


varibale
} // end of while loop

Assignment with while loop:


===========================
Req :

-> A person should complete 20 rounds of Running Track .


On very single round compltion, person should say
"Hi"

Req :

Students :
100 students : student ids : 100 - 200
print student id's :

Req :
Print 5 division values under the range of 333 to 999
reminder = 0
335
340
345
...
995

Req :
print prime numbers in between 1-1000
Req :
print odd numbers from 500 - 200

Req:
print 11 divisible values in b/w 333 to 4000

loop: for
operator : %
Operartor : ==

11 % 333,334,335....

condition : 11 % value == 0
print
if condition :
if value 11 reminder 0
print value

for(333 ; val <=4000; val++){


if( 11 % value == 0 )
sop(val)
}

EMI = [P x R x (1+R) ^N]/[(1+R) ^N-1]

-> analysis -> Practice :

3. do-while:
------------

Similar to while loop functionality..

do : key word
synatx:
------

do{ // starting
of d0- while loop

// logic : Repeatdely

} while(condition); // end of do-while loop

====================================
while
do-while

do : Performing an action

Diff :
while:
while loop will be exuted after condition evaluation everytime.
appy condition first:
true : execute logic
false : leave the loop

do-while :

first do : execute loop logic/body after that apply


condition

now condition : result : true : execute loop

false: leave the loop

Req :

Data : Value -> Apply some loigc -> result value -> condition

now same process is repeted again and agin based on result value and
and some condition on that.

while : logic should be executed after condition check only

do-while: logic should be executed before condition check only

Note:
======
Usage of loops is reduced from java 8 version onwards .

Arrays
Collection : List Set

Stream Api : -> loops in RT is reduced


for loop

while ->

for-each

do-while

3.Branching/jumping Statements:
------------------------------

We can transfer control of program execution unconditionally from one


point to another point.

1. break : Leave the loop

s1
s2
s3
break;
s4
s5
2. continue : Don't leave the loop, skip that iteration and move to next
value.

s1
s2
s3
continue;
s4
s5

3. return
================

return: to return a value and as well we are apssing control back to caller.

class {

m1(){
sop("line1");
int value = m2();
sip(value);
}

public int m2(){

return 10;
}
}

How many return satements we can write in a method?


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

User Dynamic Input:


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

add(){
int value1 = 10;
int value2 = 20;

return value1+value2;
}

1st : 30
2nd : 30
3rd : 30
100 : 30
Java Executor , will not ask any data from the user.

100, 300

add(){
int value1 = 100;
int value2 = 300;

return value1+value2;
}

1st : 400

-> Whenever Executing the prgram, we can enter data dynamically

Yes,

add(){
int value1;
int value2;

return value1+value2;
}

In this cae, I would like to enter different diffeent values everytime when
executing program.

1st : Executing :
12
34
-> 46
2nd time :
66
34
-> 100

Dynamic Input By User on every execution


Pre Defined Claases
1. Scanner
2. BufferReader

By these 2 classes , we can tkae input data while program execution in progres.

1. Scanner class:
------------------
By using this calss, we can make sure getting input data from keyboard/user while
Java logic execution is in progress.

ctrl+space-> Ecplise will show Intelligence

int -> nextInt()


String -> next();

double,
char
float
boolean

Today onwards :

-> Don't define Data directly inside logic


int a;
int b;

-> Take data Always from Keyboard dynamically

if data Type and values are not matching : methods used from Scanner class:

Exception in thread "main" java.util.InputMismatchException


at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at com.dilipit.dynmic.input.MyBioData.main(MyBioData.java:16)

Assignemnt:
===========

/*
• Define a Bank Application and it should have below functionalities.

• Define a method for Customer Checking Balance by providing account number and
it should print Available Balance and return Available Balance.

• Define a method for withdrawing amount for an Account Number

 Method should take value of how much amount being withdrawn.


 Make sure before withdrawing amount please check available
balance
 If Available Balance is more than or equal to Withdrawn Amount
then deduct amount from Available Balance and update Available Balance.
 Print message as Withdrawn Success along with updated Available
Balance and return Available Balance.

 If Available Balance is less than Withdrawn Amount then Print


message as Withdrawn is failed due to Insufficient Funds along with current
Available Balance and return Available Balance.

• Define a method for Depositing Amount for an Account Number


 It should take how much amount being deposited.
 Print message as Deposit Success along with updated Available
Balance and return Available Balance.

*/

Constructors:
-------------
Most Important : Involved in Everyday Programing w.r.to RTP

what is Constructor?
-------------------

Constructor v/s Desctructor

-> Constructing/creating an instance/Objects

-> How Constructors are involving in Object Creation


vice versa , How Object Creation is invloving Constructors.

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

A Class

A a = new A();

-> A constructor similar/looks like methods


-> Constrcutors are special type of methods

-> method:
----------
Group of statements to do some task.
public <return-type> <method-name>(parameters){
// Logic

//return statement;
}
===============================================

Definition:
===========
1. A constructor name should always be the Class Name.

class Employee{

Constructor Name : Employee

2. Constructors don't not have any return type.

3. Constructors are going take 0 or more parameters simliar to Methods.

4. Constrcuctors are defined always inside class and out side of methods.

Synatx :
<access-specifier> <Class-name>(0 or parameters){

// Logic

Examples:
============
public Employee(){
//Logic
}

public Employee(String name, String age){


//Logic
}

Behaviour:
---------

4. Constructors are executed only once while an Object is created for that
class.

We can't call Constructors externally whenever we want to execute.

Question :
If I want to execute constructor one more time, what we have to do?

public class BankApplication {

//constructor
public BankApplication() {
// Logic
System.out.println("This is Constructor of BankApplication");
}

public static void main(String[] args) {

System.out.println("This is main method.. executing now... ");


//creation of Object
BankApplication app = new BankApplication();

-> While creating an Object, JVM verifies any Constructor defined or not. If
defined that will be executed immediatley.

Question:
----------

is it possible to execute a constructor without creating Object?

-> No

Java devided Constructors in 2 types:


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

1. Default Constructor/ 0 Param Constructors


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

-> When a constructor don't have any parameters defined that will be called
as Default constructor of class.

Example:
=============
public class BankApplication {

public BankApplication() {
// Logic
System.out.println("This is Constructor of
BankApplication");
}
}

Question:
--------
-> In a class, How Many Default constructor's we can define?

> 1 : provding Deif Constructor with Diff Names , No

either 0 or 1 :

public class BankApplication {

public BankApplication() {
// Logic
System.out.println("This is Constructor of
BankApplication");
}

public BankApplication() {
// Logic
System.out.println("This is Constructor of
BankApplication");
}
}

BankApplication app = new BankApplication();

Compiler Error:

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

IMP:
---

-> In a class, as a Developer if we are not added any type (either


default/parameterized) of constructor, then java compiler will add a default
constructor with empty body inside logic while generating .class file.

-> For Every Object Creation, a construcotr is awlays Executed.

2. Parameterized Constructor.
============================

-> A Constructor is defined with 1 or more than 1 parameters are called as


Parameterized Constructors.

public class Employee{

// Deafult Constructor
public Employee(){

// Parameterized Constructor
public Employee(int id){

Question:
--------
-> In a class, How Many Parametrized constructor's we can define?

more than one , Rule :

Constructor Overloading :
--------=------------
There should be a difference in parameters section w.r.to
no of parameters and data types of parameters.

public Employee(){
//Logic

public Employee(int id){ // 1 parameter


//Logic

public Employee(String name){ // 1 parameter


//Logic

public Employee(long mobile){ // 1 parameter

//Logic
}

public Employee(int id, String name, double salary){ // 3 params


//Logic
}

Execution:
---------

-> When we create Object, then COnstructors executed.

-> when we want to execute parameterized constructors , then we have to pass


arugument values to those parameters while creating an Object.

Employee e2 = new Employee("Dilip");

public class Employee {

public Employee(int id) {


System.out.println("This is 1 int param Constructor, id : "+id);
}

public Employee(String name) {


System.out.println("This is 1 String param Constructor, name :
"+name);
}

public static void main(String[] args) {


Employee e1 = new Employee();
Employee e2 = new Employee("Dilip");
Employee e3 = new Employee(1000);
}
}
-> if parameterized constructors are defined in a class and defaulconstructor is
not implemented in such case compiler will not add any constructor.

At What scenarios we have to define Constructors over the methods?


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

-> When we have to initilize the data for non-static/instance variables while
creating Object, then we will write constructors.

-> By the time Object is created, if we want to initilize data/values to variables


then we will define constructors.

-> Req demanding whenver an Object created immediately some logic has to executed ,
then we will write constructors with that logic.

on Object creation-Constructor
after Object creation, Methods

Assigment:
==========

-> Bio Data : pass values via Constructors

BiodData(String name, long mobile)


BiodData(String name, long mobile, int age)
BiodData()

Arrays:
======

This is common topic in every PL.

Array : A set of values.

price = 99.99
99.99,88.88,77.66 ..... : Set of : More than one value : Arrays

Array: Arraay is a reference of group of values.

if I have more than value/group of values ?


How to refer those group of values ?

Arrays :

varibale : single value

Defining Arrays:
-----------------

In java, Arrays are declared by using [] (Square Braces)

2 types Arrays :
1. Array literals:

synatx :
datatype[] arrayName/variableName = {value1,value2,value3..};

ex:
int[] numbers = {1,4,7,8,9};
double[] prices = {99.99,88.88,99, 44,56};
String[] names ={"iphone16", "iphone16 pro",
"iphone16promax" };

2. Array initilization

syntax:
------

datatype[] array-name = new datatype[array-size];

we are defining an array with size means , hte max nummber


values you are goign to store inside that array.

int[] ages = new int[5]; // create an array with size of 5

PUTTING VALUES INSIDE Array:

by using index number , we will store / retrive values of an


arrays.

what is index:
---------------

Books : page number : index


which topic available in which page

2000 pages :

1,2,3,.....

Students : id's : index : 1,2,,3,4,5,,,,,

index is a sequence of numbers.

in human life index starts from 1


in java, index starts always from 0

index :
0,1,2,3,4....

index vs position

-> Every time when we create Arrays of any datatype, internally java will allocate
index values.

-> When we create an Array, java will allocate memory in sequnce manner

setting/putting value : arrayname[index-number] = value;


getting/ reading values : varibaleName = arrayName[index-number];

double[] prices = {99.99,88.88,99, 44,56};

double val = prices[2];

setting value :
prices[1] = 33.44;

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:


Index 10 out of bounds for length 10
at com.dilip.it.arrays.ArraysDemo.main(ArraysDemo.java:29)

array length: size of an array :

-> java provided a pre-defined varibale called as "length" as part of Arrays


concaept.

-> length varibale provides always Array Size.

-> int sizeofArray = arrayName.length;

Arrays Size is 99 -> last index of array : 98

Assignment :
------------
Take a String Arrays :

double :

char[] alphabets = {'A','B','C'};

boolean[] values = {true,false,true,true,false};

Friend Names : 10 Names

String[] names ={"iphone16", "iphone16 pro", "iphone16promax" , .. };

- > try to get last perosn name


-> try to get first person name
-> print all person names
-> print all names in reverse direction
-> print alternative names

-> sum of array values : {73434,324,35,45656,57,58,67,89,789,97,789789}


-> identify max value from an arrays : 789789
-> identify min value from an arrays : 35
-> average of array values
-> Identify Dulipcate value from AN Array : 10,30,10,44,99,30,22,66,44
Duplicate Values : 10,30,44

-> Arithmatic
-> Relational
-> Logical
-> Loops
-> Conditions

-> 1 value :
> 1 value

Collections:

for, while,do.while...

Assignment :
=============
-> take an array
-> please iterate value of an array and print by using
while ,
do..while

for-each / enhanced for loop :


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

this is an enhanced loop on regular for loop.

synatx:
-------
for(<datatype of Values of An Array> <varibaleName> : <array>){
//logic : varibaleName
}

for | fro-each

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

Req :
All values : for , for each

any Criteria WRT Array index postions apart from all :

20 values : first 5 values : : 0 -4 index -> for only

-> what we can do with for-each , we can do with for


-> what we can do with for , we can't do all with for-each

Array Initlization :
-----------------------

syntax:
------
datatype[] array-name = new datatype[array-size];

-> when array is created with size intilization , then immediatley default
values are stored.

Non-Primitive -> null


Primitive : 0, 0.0, false

-Assignment:
-----------

Reapeat all above exanples with Array initilization way.

-> Array Size is : 10 : 232,33,4344,3,43,4,54,54,5,65476

1. Get first 3 values : 232,33,4344


2. Get last 3 values : 54,5,65476
3. Get 3 big values : : 65476, 4344, 232
4. Get 3 small values : : 3,4,5

=> Non-primitive :
===================

Student[20] Objects -> 20 student Objects


Employee
Product Objects : Array

Class -> Pre Defined or User Defined Classes

Array : literal / initilization

literal : datatype[] name = {val1, val2,....};

ProductDetails[] products = {.......};

-> when we created an Array with Non-Primitive Data Types , then we can store
respective datatype/class Objects inside an Array.

-> Non-Primitive Data Type Array,

in such case Array index maintain references of Objects but not a copy of Objects.

Dilip : Address : Location


Suresh :

address :

Arrays With Methods Operations :


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

1. Array as Return type of method


-----------------------------------
we can define methods with return type Arrays.

public String[] getNames() {

String[] names = {"Dilip


Singh","Shyam","Suresh","Dinesh","Haseena"};

return names;
}

calling : String[] names = obj.getNames();

Assignment:
===========
1. Define a method with Return type int, double, long ... char..

2. Create an Array with an Student


varibales : id, name, marks, gender : char

and create 10 Student Objects and put those in an


array

-> print all studens information avilable in an Array

via loops

2. passing Arrays to Method Arguments:


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

Assignment :

make Arrays Method Operations with String, int, char, double...


-> Method Return Type
-> Method Arguments

===

-> Array Size , Dynamically increase/decrease not possible.

-> store only hetrogenious data

Student -> Student[]


Employee

-> interview is more difficult than real work.

->

====================================
why main method is having String[] args
public static void main(String[] args) {
//logic
}

-> If I changes Stirng array to other Array , what will happen?

-> COmpilation , Success


-> Execution -> JVM will check always for static main method along with
String[] array type.

Error: Main method not found in class Student, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Command Line Arguments:


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

by using command line args, we can pass values to String[] of main method.

int -> Dilip


String -> "2646" -> int ,"Dilip"

path > java <ClassName> val1 val2 val3 ....

Eclipse :
------------

Run As-> Configuration -> Arguments -> Program Arguments


val1 val2 ......

Wrapper Classes :
-----------------
Java Object Oriented Programming : 100% Object Oriented Solutions

non-static variables /methods -> Create Object for the class -> Call the methods

Creation Of Object
driving the logic execution via Object

String name = new String();

String is class -> Object for Stting class.


name = "DIlip";
name.lenght();
// all the String class Object name : ->

8 primitive data Types :


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

int age = 30;

in some specific secnarios , we have to consider 8 primitive data type values


also as Objects , how it is possible?

int, doublr. float,char.. ..are classes ? No


No class -> No Object.

Still primitive data also asn Objects oriented Solutions.

Collection Framework: <Generics>

int[] val ={1,3,4};

100% with Objects

to represent primitve content and their operations also in Object Oriented , Java
Provided Wrapper Classes.

-> for every primitive data type, java provided a associated Class and those are
all called as Wrapper Classes.

-> 8 primitve -> 8 Wrapper Classes

primitive -> Wrapper Class


===========================
byte -> Byte
short -> Short
int -> Integer
long -> Long

double -> Double


float -> Float

boolean -> Boolean


char -> Character

-> these classes implemented under java.lang.

What is deprecated in api/Pl?


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

Auto Boxing and Un Boxing in java:


------------------------------------
Auto Boxing :
------------

Java is allwoing assigining primitive data type values to associated Wrapper


calsses refrences directly.

-> convertion from primitive to Wrapper is automatically happening.

-> primitive -> Wrapper : Auto Boxing

int a = 10;
int b = a;
Integer c = b; // Auto boxing
int d = c; // Un boxing

primitives and wrapper data ->

static blocks and instance blocks in java :


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

static blocks:
--------------
static block will be executed when jvm loading .class file into memory for
execution, then this block will be executed automatically.

synatx:
=======

class Xyz{
static{
//logic

}
}

Xyz.class -> loading -> static block executed once.

Xyz{

//
static m1(){
//logic : values :

-> we can dfine more than static block


-> static blocks executed before main method itself.

-> Question:
is it poosible to execute a method before maon method it self?
-> call that method from static block.
2. instance block :
=================
syntax:

//Logic

-> non-static blocks are not executed while loading class into memory.

-> non-static blocks are executed while creating an Object for that class.

-> define more than one

-> call can conatin static & not-static blocks

Constructor : -> while Object Creation

Question:
==========
instance block /constructor ? which one will execute 1st?

-> instance block executed at first then constructor

what is probability of executing static block? 100%

=> advantage non-static blocks?

execute logic before an object creation every time.

-> logic every time once -> static


-> logic evry time on Object creation -> non-static

B.static A. constructor C. non-static block

class Student{

OOPs Principles:
---------------

Object Oriented Programming :


Object Oriented solutions

Class -> Object Class -> Access Functionlity by using Objects.

class Student{

static int id =100;

public void printStudentinfo(){

// logic
}

-> Another Class -> do we really need an Object of class Student? Yes

4 principles :
--------------

1. Inheritence

2. Abstraction

3. Polymorphism

4. Encapsulation

1. Inheritence:
-----------------

Inheritence is re-usability of logic.

One Object can access methods/properties of another Object directly.

Extending one class functionality with other class functionalities.

A{
int year = 2024;

m1(){

}
}

B{
m2{
// m1 of A
Create an Object of A
a.m1();
sop(a.year);
}

How to enable Inheritence relation in b/w classes:


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

by using a keyword called "extends" , we cam make inheritence relation b/w classes.

syntax:
=======

-> B access A properties


-> B should maintain relationship with A

public class A{

// 5 methods : 5 functionalities
}

public class B extends A{


// A class 5 methods wiht out Objects

// 5 new add

-> B is inheriting properties of A

A -> Super/Parent/Base class : better use super class


B -> Sub/Child/Derived class : better use sub class

syntax :
-------
class <Super/Parent/Base>{

class <Sub/Child/Derived> extends <Super/Parent/Base>{

-> Parent properties from Child Class

1000 classes

class : 20-30 methods

1 methods : 200 lines

Types of Inheritece :
-----------------
1. single level inheritence
2. multi level inheritence
3. Hierarchical Inheritence
4. Multiple Inheritence

Note :
====== Please check parent can access Child properties or not directly? No

Child can access Parent but not Parent can access child.

Question : is it possible Child class can access Parent class variables directly or
not?

Yes, we can access as usal.

child can access variables + methods of parent.

1. single level inheritence


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

-> we weill defeine inheritance in b/w two classes.

2. Multi level inheritence


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

-> we weill defeine inheritance in b/w more than 2 classes.

3. Hierarchical Inheritence
=============================

-> From one base class, when we are deriving many classes is called as Hierarchical
inheritence .

-> From one super class, when we are extending many sub classes is called as
Hierarchical inheritence .

4. Multiple Inheritence
------------------------

in Java, Multiple Inheritence is not allowed with classes but allowed with
interfaces.

-> a child is having more than one Parent class is called Multiple Inheritence.

Req :
---

Payments :
net banking
debit card
credit card
upi

PaymentOne{

netBanking

PaymentTwo {

net Banking + Debit Card


}

PaymentThree{

net Banking + Debit Card + credit card


}

PaymentFour{

net Banking + Debit Card + credit card + upi payment


}

Implementation :
================
class PaymentOne{

netbanking(){}
}

class PaymentTwo extends PaymentOne{

debitcard(){

class PaymentThree extends PaymentTwo{

creditCard(){

class PaymentFour extends PaymentThree{

upi(){

}
}

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

Define rules -> maintancne of logic

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

XYZ -> 3 payemnts : PaymentThree

ABC -> 1 payment : Net Banking -> PaymentOne :

MNC -> 4 payments : 1 class PaymentFour : upi, cc,dc, nb

Arrays :

String[] friendNumbers = new String[10];

//

9th chnaged mobile number 123 to 456


friendNumbers[8] = 456;

//printing all friends number

456

Abstraction :
=============

Hiding implementation and showing features/functionlities.

An Abstraction can be achieved in 2 ways.

1. Interfaces : 100%
======================

2. Abstract Classes : 0-100%


===============================
1. Interfaces :
==============

what is an Interface?

An interface represented as a blueprint/template for a class implementation.

-> An Interface will define set of rules to implement a class.

1. How to create an Interface:

2. Form the interface how we are implementing the class.

1. How to create an Interface:


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

-> An interface is created by using a keyword called as "interface"

-> An interface is created similarly liek a class.

public class <class-name>{

//methods with logic

public interface <interface-name>{

//methods without logic

// methods with logic

-> an interface is created as separte java file

InterfaceName.java file -> InterfaceName.class

Example :

public interface LoanInformation {


String getLoanType();
}

=> Let's implement a class from the above interface

=> to implement a class from interface, java provided a keyword called as


"implements".

Synatx:

public class <ClassName> implements <InterfaceName>{


}

Error : The type ICICILoanapplication must implement the inherited abstract method
LoanInformation.getLoanType()

The type ICICILoanapplication must implement the inherited abstract method


LoanInformation.getBankName()

abstract key word:


----------------
abstract method:
----------------

when we defined a method signature but not logic that means those methods are not
concrete methods (methods without body/logic)

-> By Default a non-concrete-method in an interface is always abstract method.

syntax :
======

<access-specifier/modifier> abstract <return-type> <method-name>(0 or more agrs);

abstract classes

-> By Default an abstrct method in an interface is always public method.

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

1. From an Interfacce, How many Classes can we implement?

-> Any number classes

2. How many interfaces can we implement by using a class at a time?

more than one

public class <className> implements Interface1, Interface2 ...{ // allowed

}
Inheritence in b/w classess:

public class <className> extends Class1, Class2{ // Not allwoed

=> Rule : provding impl for all abstract method of all interfaces in the class.

3. if class don't want to provide an impl for an abstract method of an interface?

comile time error

interface : 3 methods
class : impl for 2 method only : Compile Error : 1 method is pending

TBD : then mark class as abstract class.


abstract methods
abstract classes

4. an Interface can conatain varibales or not?

Yes we can define :


// TBD :

by default varibale is static and final.


TBD : final keywrod
final varibales
final methods
final classes

static varibale :
----------------

Wec an access via ClassName


ClassName.StaticVaribaleNAme;

Interface :

InterfaceName.varibaleNAme;

public interface InterfaceOne {

// variables

static final String name = "Dilip IT";

//static final String contactEmail = "dilipit@gmail.com";


String contactEmail = "dilipit@gmail.com";
}

class One implemetns InterfaceOne{


// direct access
}

class Two{

// I wan to Access InterfaceONe Varibale : Yes we can do


InterfaceONe.name;
}

Note : In interfaces there is no concept of instance/non-static varibales

final variable :
=================

final is a keyword.

-> by using final keyword, we cn define


1. final varibales
2. final methods
3. final classes

what is final varibale


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

Class:

when we declared a varibale with final keyword in a class, final varibale.

class CompanyInformation{

final String companyNAme = "Xyz technologies";

what is functionality final varibale.

final : thing s will not change here after

-> final varibale : when requirement demanding a varibale value should not change
once it is initilized, in such case we will mark that varibale with final key word;

-> final varibale value should be initilized while declaring;

=-====================================================

-> Varibale declaration with out value in Interface is allwoed or not? No

Ans ; it's a final varibale.


final varibale value should be initilized while declaring;

public interface InterfaceOne {

// variables

String companyName = "Dilip IT";


String contactNumber; // compile time error

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

Inheritence with Interfaces :


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

Class :

class A{

}
class B extends A{

Interfaces :
============
Single Level:
=============

interface A{

interface B extends A {

Multi Level:
============

interface A{

interface B extends A {
}
interface C extends B {

3. Hierarcal Inheritance;
------------------------

1 parent with many child

interface A{

inrerface B extends A {

inrerface C extends A {

4. Multiple Inheritence:
=======================

one child with many parents

not supperted with classes

supperted with interfaces

class A extends X,Y

class A implements X,Y

interface A extends X,Y

Which is correct?

Abstract method & Abstract Classes:


==================================
Abstract method :
================

Interface :

-> When we define a method inside an interface with only signature , then that
method is called as abstract method i.e. by default that method is abstract method.

public interface BaseModelCar {

String carName = "Skoda Kushaq";

String carPower(); // abstract method

String carFeatures(); // abstract method

static void car...(){ // not a abstract method

Abstract method :
-----------------

When we define a method signature without logic in side a class or an interface ,


then we can call that method as a abstract method.

class A{

String carFeatures();
}

Class :
------

Rule :
When we define a method signature without logic in side a class then we can call
that method as a abstract method and we have to mark that method with a keyword
called as abstract keyword always.

abstract method : method with signature but no body/ method without logic.

class A{

String carFeatures();
}
====================
interface A{

String carFeatures();
}

.class : compilation

interface A{

public abstract String carFeatures();

Error :
The abstract method carSecurityFeatures in type SkodaKushak can only be defined by
an abstract class

-> when we define any single abstract method inside a class, the moment we have to
make class also as a absract class.

Abstract Classes:
-----------------

when ae are added/making a class with keyword abstract then that class is called as

abstract class.

-> In which scenarios we are making a class an abstract class?

-> How many abstract methods can we define inside a class ? More than one

Cannot instantiate the type SkodaKushak

-> cannot create Object :

-> creating an Object For an abstract class is not allowed.

why not allowing creating an Object?


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

why we are adding abstract method inside a class rather than in interfaces?
----------------------------------------------------------------------------

We can make abstract class in 2 scenarios:


----------------------------------------
1. when we defined a method as abstract in a class, then 100% we have to make
class also as an abstract.

2. When we don't want to allow creating an Object for a class, then also we can
make that class as abstract class.

i.e. to make class as an abstract class no need have abstract method in a


class mandatory.
======================= example ========
class App extends BankApplication{

public abstract class BankApplication {

public long accountNumber = 1234567;


public long currentBalance = 1000;

public static void main(String[] args) {

App a = new App();


a.checkBalance(1234567);
// creating Object

/*BankApplication bank = new BankApplication();


bank.checkBalance(bank.accountNumber);
bank.withdrawAmount(bank.accountNumber, 100);
bank.depositAmount(bank.accountNumber, 200);*/
}

// Method Implementation : Check Balance


public long checkBalance(long accountNumber) {
System.out.println("Available Balance for Account : " + accountNumber + "
is : " + currentBalance);
return currentBalance;
}

// Method Implementation : With Drawing Amount


// accountNumber, withdrawnAmount : Called as Parameters
public long withdrawAmount(long accountNumber, int withdrawnAmount) {

//long availableBalance = checkBalance(accountNumber);


if (currentBalance >= withdrawnAmount) {
currentBalance = currentBalance - withdrawnAmount;
System.out.println("Withdrawn Success, Updated Balance is :
"+currentBalance);
}else {
System.out.println("Withdrawn Failed, Insufficient Funds. Available
Balance : "+currentBalance);
}
return currentBalance;
}

// Method Implementation : Depositing Amount


public long depositAmount(long accountNumber, int depositAmount) {
currentBalance = currentBalance + depositAmount;
System.out.println("Deposit is Success, New Balance is :
"+currentBalance);
return currentBalance;
}

}
============

Note :
// final variables & static : naming convention :

Evry word in UPPER CASE and every word separted by _

bankName -> BANK_NAME


piValue -> PI_VALUE
contactEmailId -> CONTACT_EMAIL_ID

Polymorphism:
--------------

Polymorphism we have two ways/concepts

1. Method Overloading
2. Method Overriding

Method Overloading :
------------------

Overloading :

Method Overloading is a concept of creating many methods in same class with same
method name but different signatures.

-> more than one method with same name but different types of parameters including
number of parameters.

-> method name + method parameters

-> method parameters (if no.of paramas are different w.r.to same method name : OL
Valid )

-> method parameters (if no.of paramas are same w.r.to same method name : Now
Compiler will check order of the data types and checks some diffrence in the data
types : OL : valid )

-> Note: In Method Overlaoding don't involve return type of method.


class Calcualtor{
public int sum(int a, int b){

-> Note: In Method Overlaoding don't involve return type of method.

case 1:
-----------
int sum(int x, int y)
double sumb(int a, int b)

MOL : No , Compile Error

case 2 :
-------
int sum(int x, int y)
int sum(double a, int b)
int sum(double a, int b, int x)
int sum(int a, int b, double x)

MOL: Yes , When no.of parameters are same , then it will check order of data types
different or not.

case 3 :
-------

int sum(double a, int b, int x)


double sum(double x, int y, int z)

MOL: No ,

When no.of parameters are same , then it will check order of data types different
or not.

=> We are achiving Method Overaloading with iun the class or by using a single
class.

Execution:
---------

-> in a class, we can overlaod more than one method


Method Overriding?
------------------

Overriding : When are taking one more time same exaclty which is already existed.

Method Overrding :
-------------------

-> Method Overriding : Same method signature including method parameters also.

in a single class , is it possible? No

-> Method overrding is always happenes in between 2 classes and those should be in
inheritence relationship.

inheritence :
---------------
class A{
int mone(int a, int b){

}
}

class B extends A {

double mone(int a, int b){ //oVerrided

mone(int a, int b, int c){ // Not Overrided


//logic
}

wihtout inheritence :
---------------
class A{
int mone(int a, int b){

}
}

class B {
double mone(int a, int b){

}
}

-> Method Overrding is awlays happens in between Super and Sub CLass. It involves 2
classes min.
N number of.

Parent : 1 method -> CHild : only One

-> Child can access parent methods

-> Use Case : Inheritence + Method Ovrrding

ChildClass childCLassObj = new ChildClass();


childCLassObj.method..(..);

Java checks method..(..) impl avilable in child class or not.


if avilable, then child class methos is executed.
If not avilable, then Parent class method executed.

-> How many methods can we override ?


many method of parent in child level.

-> Question : why overrding to do?

PArent :
bought a bike
Child
Use :
use parent bike

-> Abstraction, Ploymorphism -> Inheritence

final, this, super...

final methods :
---------------

final varibale: value should not changed once it is initilized , then create final
varibales.

final method:
=============
when we made methods are final, Those methods not allowed to override by child
classes.
---syntax:

<access-specifier> final <returntype> <methodname>(....){

A{

final m1(int a){ // final method

m2(){

}
final m3(){

B extends A{

m1(int a){ // Compile error

m2(){

}
m3(){ // Compile error

final class:
------------
final varibales, methods, classes.

Syntax :
======

public final class <ClassName>{

=> When we make a class as final class, that means that class not allowed to be
inherited.

=> Preventing inheritence of class : mark that class final


final class A{

B extends A { // Compile Error

// no overdding

Question:

what is the diffrence between final class and abstract class?

Complated : final keyword:

this & super :


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

keywords:

These keywords are representing reference of instances.

this keyword:
-------------

this -> Current class Instance/Object

A a = new A();

a -> reference
this -> reference of current Object being used by JVM.

-> We can use this keyword in a class in diffrent scenarios.

1. this keyword used refer instance variables


2. this keyword used refer methods
3. this keyword used as a method argument
4. this keyword used for calling constructors
5. this keyword used as a constructor argument

-> to use this keyword, inheritence is not required always.

1. this keyword used reference instance variables:


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

Constructor body level


Method Body Level
2. this keyword used refer methods :
==============================

this -> No point of super class


super -> No point of current class

3. this keyword used as a method argument


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

4. this keyword used for calling constructors


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

calling another construcror from current constructor.

*** RULE : Calling constructor should be 1st line of constrcutor body. Oherwise we
will get compile time error.

n/b we can call at a time only one constructor.

constructor chaining.

only one constructor shlould be called and calling should happen from 1st line

5. this keyword used as a constructor argument


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

public class ProductOne {

public ProductOne() {
System.out.println("This is Produc One ... ");
ProductTwo pTwo = new ProductTwo(this);
System.out.println(pTwo);
}

public static void main(String[] args) {


ProductOne pOne = new ProductOne();
System.out.println(pOne);
}
}
super:
-----

-> to use super keyword, inheritence is required always.

This keyword always represents content of super class from sub class.

-> super keyword is used always from sub class.

-> to use super keyword along with methods and varibales, those methods and
varibales should be presented in super class otherwise we will get compile time
error.

Req: Calling same class constructor

Req : Can we call super class constructor from child class is possible or not?
Yes. super

varibales, methods, construcors

A{

A(){

}
A(int a){

sop(a);
this();
}
}
1. super keyword used refer instance variables
2. super keyword used refer methods
calling super class methods from sub class.
3. super keyword used for calling constructors
calling super class constructors from sub class constructors.

******

When Constructor calling another Constructor , then that should happne from first
line of Constrcutor body.

*******

classA{
A(int a){

}
}

class B extends A{
B(){
super(10);
this(1000);
}
B(int x){

1. Compliation Success 2. Complitaion Error

There is by default constructor if we not written any const

Never look for immediate output Successfully.

Errors ->

Polymorphism:

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

OOP principle:

Poly -> Many

morphism -> Formations

One Object is making differnt actions in different scenarios.

2 types :

1. Compiletime/static/early-binding Polymorphism
Method Overloading

2. Runtime/Dynamic/late-binding Polymorphism

Method Overrding

1. Compiletime/static Polymorphism

Method Overloading : a class contains same method name with diff


params

int add(int a, int b){

}
double add(int x, double y){

2. Runtime/Dynamic Polymorphism
===================================

Method Overrding :

w/o Overrding : NO Polymorphism

inheritence : super / sub class

In Java ,
1. a Super class reference can hold/refer it's sub class instances.
2. An Interface can refer it's implemented classes instances.

1. a Super class reference can hold/refer it's sub class instances/Object.

PaymentApplication : Super Class

Sub CLass:

CreditCardPaymentApplication
NetBankingPaymentApplication
UpiPaymentApplication

CreditCardPaymentApplication obj = new CreditCardPaymentApplication();

PaymentApplication payment = new CreditCardPaymentApplication();


PaymentApplication payment = new NetBankingPaymentApplication();
PaymentApplication payment = new UpiPaymentApplication();
vice versa :

referring parent object by child not possible.


CreditCardPaymentApplication payment = new PaymentApplication(); //
Error

CreditCardPaymentApplication app = new


NetBankingPaymentApplication(); // Error

Use Case 1: Not Overddien Method & Method is From Child Class
===========
CreditCardPaymentApplication#creditCardPayment() :

PaymentApplication payment = new CreditCardPaymentApplication();

payment.makePayment("CC",9999);
payment.creditCardPayment();

Result : Compile Time Error

Use Case 2: Not Overddien Method & Method is From Parent Class
===========
PaymentApplication#getPaymentType() :

PaymentApplication payment = new CreditCardPaymentApplication();

payment.makePayment("CC",9999);
payment.getPaymentType();

Result : Compile SUccess & Execute Success.

Note:
-----

When we are using super class referring sub class object concept, the method
should be presented in Parent class.

-> If method existed in Child also , child class method executed.


-> If method not existed in Class , Parent class method executed.

question : HOw can I call creditCardPayment() ?

The refer CreditCardPaymentApplication class instance with same type.

CreditCardPaymentApplication cc = new CreditCardPaymentApplication();

//
cc.creditCardPayment();
cc.getPaymentType();

Check in child class if avilbale then execute if not avilable then check in
parent and avilable execute it . Even not vailbale in Parent then Error.

// call child and parent class methods with out any issues

Req :

Define classes and make sure methods are executed if they are presented in
parent class other wise don't allow.

Req :

Define classes and make sure methods are executed if they are presented in
child or parent class.

What is contract b/w super and sub class if we want to achive dynamic polymorphism?

Encapuslation:

Access Specifiers/Modifiers:
----------------------------

Access : Accessibility

Specifiers : Specifying :

1. public
2. private
3. protected

4. default : if we are not defined any of public , private or protected then that
will become default that means we don't have a specific word default in access
specifiers.

class , varibales, methods, constrcutors, ......

private int id;

diff class : The field Student.id is not visible


The method getPassword() from the type Student
is not visible

public class Student {

private int id = 199; // with in the class


public String name = "Dilip"; // with in the class and outisde of class.
}

public classes , methods

private varibales , methods , constructors

4. Encapsulation :
-----------------

Encapsulation is binding variables and methods of a class.

Data Binding

No access to varibales directly, provide access via method

Req : At any cost don't allow any other class/Object modifying student id value.

POJO class : One of the example for Encapsulation


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

POJO class is a kind of Design pattern.

Design pattern : Represents a solution or a template for a solution

Design pattern provides steps to achive a common problem/Or a better solution in RT


application.

POJO Class : NO RT
100s of POJO classes

POJO class being used in different scenarios to achive different functionalities

1. DTO
2. VO
3. Entity CLass
4. Request Body
5. Response Body

POJO : Plain Old Java Object

-> Every class is not a POJO class.

1. Make sure class conatins only variables , methods whcih are associated to
variables , constructors.

2.as part of POJO classes, we should not write methods which are having logic
/impl of a requirement.

3. POJO classes are best examples of Encapsulation.

Rules :
1. Define private varibales

Setter & Getter Methods :

Setter Method : a method for setting value into variable.

Getter Method : a method for getting value from variable.

Rules/Syntax Setter and Getter Methods :


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

// variable name : int id;

setter method:
==============

1. method should be public


2. return type should be void.
3. use a word set and followed by Varibale Name a: Method Name
4. this method will a single parameter which is exaclty same type of varibale.
5. define a line which is assigning arg value to instance varibale.

public void setId(int id){


this.id = id;
}

Naming Convention of Methods: Camel Case : Similar Variables :

getter method:
==============

1. method should be public


2. return type should be similar or exaclty same type of varibale.
3. use a word get and followed by Varibale Name : Method Name
4. this method don't have any method arg/parameters. (0 method args)
5. define a line which is returing value of instance varibale.

public int getId(){


return this.id;
}

Lombok library

Assignment:
==========

1. Create 10 Products(Product POJO class) and store in an Array.


2. Pass that array to other methods and from there print all product Objects
information

3. Pojo class : Added constructors (2 : default , all params )


4. add toString() : Override & implement it.
5. equals & hashcode

Object Class :
--------------

Pre-Defined class : Object

Object it self a class now.

Major feature of this class is :

Object class is a global super class for every class defined/implemented in java
lang.

java.lang : default package :

Class Object is the root of the class hierarchy. Every class has Object as a
superclass. All objects, including arrays, implement the methods of this class.

clone() :

copy of an Object : clone()

Abc a = new Abc();


a.clone();

toString() : Returns a string representation of the object.

using reference of an object, toString() of Object class is


executed.

Employee e2 = new Employee();


System.out.println(e2); // toString() of Object class

O/p: com.dilipit.Employee@2f92e0f4

Question : can we override toString() in our class class.

System.out.println(e2);

Yes : child -> parent


Employee -> Object

com.dilipit.Employee@372f7a8d
com.dilipit.Employee@372f7a8d
com.dilipit.Employee@372f7a8d
com.dilipit.Employee@2f92e0f4
com.dilipit.Employee@2f92e0f4

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

Employee Details : Id 0 , Name : null


Employee Details : Id 0 , Name : null
Employee Details : Id 0 , Name : null
Employee Details : Id 0 , Name : null
Employee Details : Id 0 , Name : null

reference : ClassName@hadcode
-> reference : Print Data Of Object. : Overrdie toString() method

contract : equals & hashcode of Object class:


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

boolean equals(Object obj)

int hashCode()

boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

used for comparing Objects. not comparing the memory locations

it's all about comparing content of Objects.

A super class can refer sub class Object


Identifying duplciate Objects:
-------------------------------
equals(Object obj) : e4 -> Employee

getClass() : method gives us class name of Object.

In a class, When we override equals() method ,we have to override hashcode() also.

if content is same then those objects should be pointed to same location.

-1157744794
-1157921609
-1157744794

Type Casting :
=============

Data Type :

Casting : COnverting:

Type Casting is a process converting one data type to another data type.

i/p : 18.99 -> double -> converted to integer -> 18

primitive data types

Non_primitives : String, Student,Product , Exception , ArrayList.....

primitive data types


---------------------
2 types casting available:

Auto Boxing :

int -> Integer


Integer -> int

Type Casting :

1. Implicit Casting / Widening Casting

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

-> int a = 100;

a : 32-bit memory
long b = a; //

b : 64-bit memory

small data Type -> larger data type

byte -> short -> int -> long-> float -> double

2. Explicit Casting / Narrowing Casting


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

double -> float -> long-> int -> short -> byte

larger data Type -> smaller data type

Syntax : (targetType) value;

-> loss of data -> truncated

88.99 : 88

int -> short

Non_primitives : References:
------------------------------

1. Up Casting (implicit)
Smaller reference -> Larger Reference :

2. Down Casting (explicit)


larger reference -> small Reference :

Inheritence : Child vs Parent : Sub vs Super class

-> Parent referring child class :


method should be presented in parent class..

child also -> Child


not in Child -> Parent

Syntax : (targetType) value;

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

static methods and default methods in side interfaces : java 8 version :


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

Before 7 , In INterfaces we can define only abstract methods.


No Concept of defining method with body until 7.

public interface Car{

public void carInfo();

}
from java 8, onwards

along with abstracgt methods, we can add static methods and default methods in
interfaces

static methods and default methods : methods with logic

static methods : class


Non-Static vs static methods
static methods are part of class -> call static methods with Class
Name.

w.r.to Interfaces : static methods : similar to Classes.


static methods are part of interfaces -> call static methods with
Interface Name.
InterfaceName.staticMethodName();

NOTE : default methods are not avilable in classes.

Agenda Behind introducing impl methods in Interfaces?


What was the real difference b/w interface and abstract class.

interface (100% only non-impl method) & abstract class( non-impl method & impl
methods ) : until java 7

interface (non-impl method & impl methods ) & abstract class( non-impl method &
impl methods ) : from java 8

default methods:
-------------------
a default method in interface is having logic.

-> a default method in interface, when we will define is , accessible by instance


of impl class as well as allowing overrding in impl classes.

-> a default methos is defined with keyword default i.e. in method signature we
ahve to add default.

interface A{
default void info(){
//logic
}
}

class B implements A{
B b= new B();
b.info();

static methods:
-------------------
a static method in interface is having logic.

-> a static method in interface, when we will define is , that logic is accisble
commonly by all classes without creating an instance of impl classes.

InterfaceName.staticMethod();

-> a static method is defined with keyword static i.e. in method signature we have
to add static.

interface A{
static void info(){
//logic
}
}

class B implements A{

A.info();

Class C{
// access A static methods but not default method of A

-> we can add 0-n no.of static & default methods in a interface.

-> Common/Shared logic in b/w impl classes.

-> Backward Compatability.

-> When logic should be avilable to any class irrespective of impl classes :
static method.

-> When logic should be avilable to impl class of that respective interface :
default method.

-> Evry impl class can override default methods of an interface.

Req :
provide guidelines of a loan.
guidelines are common at every place.

static method of Interface :

from impl class : Interface Name


from non-impl class : Interface Name

default method of Interface :

from impl class : directly


from non-impl class :
not accisble by default.
By using an impl class instance , we can access default methods.

Req :
add logic for calculating EMI for a loan.
-> bank may follow thier own processing fees.
10 impl classes :
5 classes : usee as it is
5 classes : based on thier LOGIC

=> overrding default method. : HDFC Bankk aould like to provide own logic

Overview :

Strong in basics : static vs non-static


Inheritence :
Method Overrding : POlymorphism.

Exception Handling :

Collections : Stream API

100% Inheritence / Method Overring / Overloading : Polymorphism / Abstaraction :


Interfaces & abstract classes.

Debugging : Java Applications With Debugging


----------------------------------------------
Debug :

Bug : Error : Issue : problem : Defect

Process of identifying the bug and it's root cause/ details as well process making
solution / fix this issue.

Java Application : Web Application : Spring Boot Application et....

analyse the source code : why and where the issues are happening at run time
level.

Experience :

Developer taking control of JVM flow.

Executing : Applications

2 modes :

IDE : Eclipse, InjtelliJ

1. Run Mode
2. Debug Mode

Started : Application in Debugging Mode :

Break points:

Break : Gap, pause the flow, Stop

Breakpoint : applying a puase at a specific line of code while JVM


execution flow is happening.

How to apply Break point :

Whatver line, you would like to pause JVM execution flow, there go to
that line , on top of line number do double click.

Note : Break points not applicable in RUN mode.

Step Into : entering into more deep

Step Over :

Step Return :
Annotations:
============

Meta Data : Data about Data

Annotation : Metadata

Annotation : Tag of Metadata.

Java :

Classes / interfaces
Methods
Fields

-> need some extra information about above content.

Class A{
one(){

}
}
class B extends A{
//method overrding
one(){

}
}

@Override : please define this annotation when you are doing method overrding and
it should not be violated at any time.

-> add at overrding method level.

Syntax :

Annotations names started with @ always

@<annotation-name>

Buit-in/Pre defined Annotation:


===============================
@Override

User-Defined annotations:
-------------------------

Create Annotation :
=================

-> annotations are created by a keyword interface. @interface

public @interface AnnotationName{

Ex :

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

Usage in logic => @Override

-> Provding Retention Policy : @Retention


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

Configure as , That annotation should be used at source level,


compile -time level, runtime level.

Source Level
Compile Time level
Runtime level

=> How long annotation should be retained.

Indicates how long annotations with the annotated interface are to be


retained. If no Retention annotation is present on an annotation interface
declaration, the retention policy defaults to RetentionPolicy.CLASS.

A Retention meta-annotation has effect only if the meta-annotated interface is used


directly for annotation. It has no effect if the meta-annotated interface is used
as a member interface in another annotation interface.

RetentionPolicy

CLASS : * Annotations are to be recorded in the class file by the


compiler
* but need not be retained by the VM at run time. This is the default
* behavior.

SOURCE,

* Annotations are to be discarded by the compiler.

RUNTIME
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.

-> Providing Target : @Target


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

Configure that annotation used at what level.


Class, varibale, methods

Target.CLass -> We can use use this annotation only at


class level.
uf we are trying to use any other place ,
Compile time error.

=> No Target : we can use annotation at any level.

ElementType : enum

Java 8 version :
----------------

Functional Interfaces:
=======================

Interface : abstract( 0 or more ) + static ( 0 or more ) + default ( 0 or


more ) methods

Functional Interfaces : abstract( only 1 should be ) + static ( 0 or more ) +


default ( 0 or more ) methods

FI that exactly have only one/single abstract method.


RULE : it should not be 0 or not more than one method also.

SAM(single abstract method) interfaces

is this FI ?
public interface CalcOperation {

Ans : No

is this FI ?

public interface CalcOperation {


int add(int a, int b);
int sub(int a, int b);
}
Ans : No

is this FI ?

public interface CalcOperation {


int add(int a, int b);

// static & default methods


}

Ans : Yes

=> When we defined SAM as per FI, to make sure that interface is always as a FI
java provided an annotation called as @FunctionalInterface

@FunctionalInterface : ensure interface conatins always only 1 abstract method.

package : java.lang.FunctionalInterface

interface -> write a impl class (provide impl for all abstract methods)

Functional Programming
Declarative Programming -> Achive
Imperative Programming

Lambda Expressions:
=================

FI impl we have to make via Lambda epressions rathethen a regula impl class
approach.

Lambda exp. is always an implmentation of FI.

NO FI (SAM Interface) -> NO Lambda eXp.

Lambda expressions don't required a separate class for implementing an abstract


method of FI.

Lambda expressions are implemented in side a block/method wherever we want.

Lambda Expressions are passed as a method argument also.

Lambda Expressions always an implementation of SAM of an interface.

public interface CalcOperation {


int add(int a, int b);

// static & default methods


}

@FunctionalInterface
public interface CalcOperation {
int add(int a, int b);

// static & default methods


}

How to write/impl Lambda Epressions:


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

Synatx :

<FunctionalInterfaceName> <lambda-expression-name> =
(method parameters) -> {

//logic
};

// how to execute / call lambda expressions

lambda-expression-name.sam-name(arguments);

Ways :
======

Q : Where we have to define Lambda Expressins ?

We can define wherever, we want

1. Writing Data Types of Method arguments As part of LE is an Optional.

2.

FI:

Abc{

void operation(int a);

a ->{};

LE with Objects :
Exception Handling in java
===========================

Excpetion : a person or thing that is excluded from a general statement or does not
follow a rule.

Handling : Taking into Control.

Compile Time Error : Something we are breaking the rule.

Excpetion : unwanted event, which occurs during the program execution.

-> Exceptions are always generated from logic(developer) -> Handleing

Exception vs Error

Error Handling is possible or not? No, Developer.

Can we call Error handling and Excectpion Handling, both are same ? No
bith are diff.

Error : An error is not-recoverable scenarios.

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

-> Error are always generated due to infrastructure but not from logic.

-> Exception Handling

What is an Exception?
---------------------

Exception Stack Trace :

NullPointerException:
-------------------------
If any Reference variable is assigned with null in memory level and by using that
rerference varibale if we are making any operations(calling methods/varibales ett..
of that class), Java will create an Exception and called as NullPointerException.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke


"com.dilipit.exception.handling.Student.studentInfo()" because "s" is null
at
com.dilipit.exception.handling.NullPointerExceptionDemo.main(NullPointerExceptionDe
mo.java:23)

How we are getting an Exception , Exceptions are created/genearted

Handling

which class is called as an Exception class?


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

-> If any class is a child of Throwable class, called as Exception class.

Student : No
Testing : No
ExceptionDemo : No

NullPointerException : Yes
ArithMaticException : yes
IndexOutOfBoundsException : Yes

public class Student extends Exception => Yes : Student is a child of Throwable

java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException

java.lang.NullPointerException

What is an Exception

What is an Exception class

How to explore Exception classes

NullPointerException & many Other Exceptions in diff. scenarios

Exceptin CLass -> Runtime vs Compile-time


Types of Exceptions:
---------------------
1. Compile Time / Checked Exceptions

-> An Exception class is a child class of Exception class but not


derived from RuntimeException class is called Compile Time Exception.

2. Runtime / Un Checked Exceptions

-> An Exception class is a child class of Exception class and derived from
RuntimeException class is called Runtime Exception.

Runtime Exceptions / Compiletime Exception

Handling Exceptions:
--------------------

avoiding an exception : Not a handling exception

Handling Exception : when exception occures , what has to be done.

Compile / Runtime Exception : Handling an Excpetion process is same.

1. try
2. catch
3. finally

4. throws
5. throw

1. try
2. catch
3. finally

-> try :
-------

1. try represeting a code block.


synatx :
try{
// Business logic
}

2. usually, as part of try block, we will keep the logic which may cuase an
exception.
int a = 10;
int b = 90;
String name = "Dilip";
int c = a+b;
int d a-b;
double x = a/b;

3. a try block should be associated either catch block/finally block or both;

catch block:
============

1. catch block should be used always with try block i.e. we can't
define individual blocks.

2. catch block is used to define logic, when an exception occured from


the try block logic : handling that exception like catching that exception and
exception recovery logic.

3. catch block is executed only when excpetion comes/created from the


logic of try block.

syntax:

try{
// logic
}
catch(TypeOFException ex){
// logic of handling exception
}

Types Of Exception :

java.lang.ArithmeticException
NullPointerException
IndexOutOfBoundsException
FileNotFOundException
ClassNotFOundException
MethodNotFoundException
RuntimeException
SQlException
etc..

-> catch block always takes an argument of Exception


Type/classes.

Student -> Arg of catch block : No

Student extends Exception -> Arg of catch block : Yes


-> if any exception occures in try block, immediatley JVM reaches catch blocks i.e.
from the try block rest of the logic not executed by JVM.

-> After finding catch blcok, jVM executes it and JVM moves to rest of the logic
defined after catch block.

-> When JVM checking for catch block whenever exception occures, same Exception
type of arugument or it will check for parent type.

-> If JVm found same type arugement catch block, that will be executed.
-> If JVm found parent type arugement catch block, that will be executed.
-> If JVm not found same and parent type arugement catch block, then JVm
terminates execution flow and rest of the logic not executed.

-> we can write more than one catch block for a try block.

-> eventhough many catch blocks avilable, at a time one catch block is executed
which is associated to an Exception occured from try block logic.

-> No possiblity of executing 2 or more catch blocks at a time.

-> when an exception occured from try block, JVM moves to catch block section and
found associated catch block and executed but JVM will not come back to try block
again.

Exception classes Hierarchy of catch blocks:


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

try{
//Logic 1
}catch(Exception ex) {
// Logic 2
}catch(StringIndexOutOfBoundsException e) {
// Logic 3
}catch(ArrayIndexOutOfBoundsException e) {
// Logic 4
}

-> Exception -> check catch blocks : specific or else parent.

Unreachable catch block for ArithmeticException. It is already handled by the catch


block for Exception

-> when we defined many ctach blocks, we have to make sure child -> parent
hierarchy.
try{
//Logic 1
}catch(StringIndexOutOfBoundsException e) {
// Logic 3
}catch(ArrayIndexOutOfBoundsException e) {
// Logic 4
}catch(Exception ex) {
// Logic 2
}

case :

try{
//Logic 1
}
catch(StringIndexOutOfBoundsException e) {
// Logic 3
}
catch(ArrayIndexOutOfBoundsException e) {
// Logic 4
}
catch(RuntimeException e) {
// Logic 5
}
catch(Exception ex) {
// Logic 2
}

Qu : Logic 1 : got FileNotFoundException


O/p:
1. Logic 4
2. Logic 2
3. Logic 5
4. Compile Time Error

finally blocks:
---------------

finally : keyword :

syntax :

finally{
//logic
}

-> finally block is defined always with try block.

-> finally block is defined always after try block.

-> at a time only one finally block we can define along with try block.

-> finally block is executed always, either exception occurred or not. (100%
executed every time)
try{
// Logic : Exception
}finally {
// Logic : Executed
}

try{
// Logic : No Exception
}finally {
// Logic : Executed
}
->finally block is used to define cleanup activities like
1. closing connections, Stream
2. releasing resources
etc..

-> Based on Req, Which logic should executed always irrespective of Exceptions,
thet should be written in fianlly block.

try-catch-finally : Use Cases : INterview FAQ's


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

-> we can write try-catch-finally blocks where-ever we want as prt of logic impl.

-> nested try-catch-finally blocks is allowed.

-> can we arite more than one finally block? No , Allowed either 0 or 1 finally
block.

-> can we write only finally along with try ? Yes

-> try-catch (Finally or not )

->

try-catch-finally: Done
-----------------

throws key word:


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

In Java, the throws keyword is used in a method declaration to specify that the
method can throw one or more exceptions. This is part of Java's exception handling
mechanism. It indicates to the caller of the method that they must handle or
propagate the specified exceptions.

-> throws keyword is used along with method signature after method argruments
section

syntax :
public <return type> methodName(Arg...) throws ExceptionType {

-> if same method may produce more than one Exception, caller has to handle all
exception.

-> throwing more than one exception is poosible or not?

public <return type> methodName(Arg...) throws ExceptionType, ExceptionType {

-> thorws keyword , we have to thorw always Compile Time/Checked Exceptions..

propagate :

-> Handling an exception

-> propagate/propagation:
------------------------

What is Propagation in Exception Handling?

throw :
-------

throw keyword is used to throw/creating an exception intentionally/explicitly.

-> when we throw Runtime Exception, Compiler not showing/forcing any error to
handle exception.

-> when we throw Checked Exception, Compiler showing an error to handle exception.

declare same exception at method level.

User Defined Exception / Custom Defined Exception Classes :


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

Yes, We can do. But we have to follwo few rules to make sure class as Exception
class.

1.An exception type must be a subclass of Throwable


2. Define a String argument constructor.
3. call super class constructor from the exception class constructor
4. we can define any no. of constrcuctors. , so that we can use those while
thorwing an exception.
Abc extends Exception{

Yes : Abc -> Exception -> Throwable

public class InvalidValueExcpetion extends Exception { //

Checked/UnChecked : Checked

-> when we throw Checked Exception, Compiler showing an error to handle exception.

declare same exception at method level.

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

Collection Framework/API:
-------------------------

DSA : Data Structures & Algorithems

Collection : Group of elements / values /Objects


Framework : Set of solutions
API : Pre Defined interfaces & classes are called as : API :

Application Programming Interface : API documentation : information of interfaces -


> impl classes, methods ,

JDBC API : interfaces & classes :


Servlet API
REST API
Spring API

Collection API : Pre Defined / Built in : interfaces & classes available:

interfaces & classes : java.util : Not a default packg : import is mandatory

https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
Collection Interface : Sub interfaces : List, Set, Queue

Map Interface : It's not child of Collection :

List: Interface
---------------

-> java.util.List<I>

-> List a sub interface of Collection interface.

-> List is having many impl. classes : ArrayList, LinkedList, Vector etc..

Purpose of List:
----------------
-> Dealing with more than one values/Objects/elements

->

int a = 10;
values[] =

ArrayList Class :
================

-> impl from List interface.

-> Purpose : How it works :


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

-> ArrayList internally uses Arrays.

-> ArrayList : a conecpt of dynamic array

The default initial capacity of an ArrayList in Java is 10.

Adding values :
------------------
add(Element):

-> Super clasa can refer sub class

Read/Get Values
---------------:

ArrayList values = new ArrayList();

-> The arraylist is allowing raw type values.

Generics:
=========
Generics is a feature provided by java for ensuring type safety at compile time
itself.

ArrayList<String> names = new ArrayList<String>();

ArrayList<Integer> ages = new ArrayList<Integer>();

: Student ObjectS:

Student[] students = new Student[100];

without generics :

ArrayList students = new ArrayList(); // raw value: int , String Student


with:
ArrayList<Student> students = new ArrayList<Student>(); // Student Objects

-> Collection FW classes and Interfaces are always supporting generics.

-> Generics are used to define classes, interfaces, methods level.

->

Rules:

-> We should not use primitives as part of Genercis decalrations, ratherthan


primitives use respective Wrapper classes.

->

LHS is mandatory to define generics decalrations , RHS is in Optional.

ArrayList<String> names = new ArrayList<String>();

ArrayList<String> names = new ArrayList<>();

ArrayList<Integer> ages = new ArrayList<Integer>();


ArrayList<Student> students = new ArrayList<Student>()

E -> Element
T -> Type
K -> Key
V -> Value

-> Real Scenarios :

-> Add, Read, Delete, Updating values


-> How to read/iterate all values
-> Advantgaes / Dis-Adv...
Use Case : Out of the szie index provided
==========
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of
bounds for length 5

java.util.Iterator:
===================

An iterator over a collection.

Iterator takes the place of Enumeration in the Java Collections Framework.

Iterators differ from enumerations in two ways:

• Iterators allow the caller to remove elements from the underlying collection
during the iteration with well-defined semantics.

• Method names have been improved.

This interface is a member of the Java Collections Framework.

Removing Values :
-------------------

remove(index)

** => List will allow duplicate values.


=> All impl classes of List interface will allow duplicate values.

One : Add
Two : Added
Two : Added

One,Two,Two

=> Set : will not allow duplicate values, maintains unique value.

One : Add
Two : Verify this value existed or not , if no : then add. if existed,
replace/override
Added
Two :
Overrided

One,Two
FAQ :

I have 2 AL, please make sure both ArrayList's are having unique values.

1,2,3,4,5,6
8,9,10,2,5,12

addAll()

removeAll() vs retainsAll()

Searching : contains(Element)
containsAll()
indexOf()
isEmpty() : just cheking given ArrayList is empty or not n/b AL contains values or
not.

String, Integer, Character ...

Student
EMployee
Order
Products
etc..

ArrayList With Non Primitvie Data Types:


----------------------------------------
1. Pre-Defined
2. User Defined

-> Define a class : I will add Objects of that class to AL

Products :

5 objects

List of Products
======================

Assignment :
=============
1. Create an ArrayList and Add 20 values
-> Get First 5 values with loops
-> Print All ArrayList values in reverse Order.
-> Print alter native ArrayList values

Assignments :
-------------

1. Take List of Employee objects :

Employee : id, name , salary , age , gender , dept name, manager name, city

Add 20 diff employees information:

1. Print An Employee who is having highest salary


2. Print An Employee who is having lowest salary
3. Print count of female and male employees
4. Print All employees belongs to a specific dept
5. Print Average salary of male & female employees
6. Print Average salary all employees
7. Print Average salary for each department
8. Print EMployees information belongs to a specific city
9. Print count of employees for each city wise
10. Print Female employees information for each city wise
11. Print an employee information who is younger
12. Print Manager Name who is having more employees under person

LinkedList:
----------
-> LinkedList is data structure provided by Collection FW.
-> LinkedList is an implementation of List Interface.
-> LinkedList stores the value in a sequence with conecpt of nodes.
-> Node contains data and reference/pointer of next/previous nodes.

Singly LinkedList
Dobuly LinkedList
Circular LinkedList

-> LinkedList : By default they are creating Doubly Linked List.

LinkedList<Integer> list = new LikedList<>();


list.add(100);

Which is better while insertion and deletion operations :

ArrayList
LinkedList: Yes

FAQ's"
======
1. ArrayList vs LinkedList
2. Which is better AL vs LL
3. ArrayList vs Vector
4. List vs Set
Vector:
------

-> Vector is a class impl from List interface.


-> Vector is similar to ArrayList only, w.r.to internal functionality also.
-> Vector using Arrays

-> Vector implemented as by default thread safety/synchronized.


-> ArrayList implemented is by default not thread safety/synchronized.

-> Can we make ArrayList as Thread safe or not?

Collections.synchronizedList(arrayList);

Returns a synchronized (thread-safe) list backed by the specified list. In


order to guarantee serial access, it is critical that all access to the backing
list is accomplished through the returned list.

Set Interface :
---------------

-> Set functionalities is also simliar to List Interface functionalities.


-> Main Difference between Set and List is , Set will not allow duplicate
values but List will allow.

-> Req demanding : we have to collect/store only unique values eventhough


same value are sdded many times. : Set

all students roll Numbers : Set


1
4
5
6
7
8
3
10
2
all students total marks : List
5 students : 888

-> List : ArrayList, LinkedList, Vector : All will allow duplicates


-> Set : HashSet , TreeSet : All will not allow duplicates i.e. unique
values.

HashSet & TreeSet :


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

-> No Duplicates : either HashSet or TreeSet


-> No Duplicates and Sorting order : TreeSet

Note : FAQ : HashSet internally uses HashMap concept.


-> How it is eliminating duplicates.

FAQ : How HashMap working internally.

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

HashSet / TreeSet :
Not allowing duplicates :
Data Types we are tested : String, Integer
String + Premitives

Non-Primitives :
-----------------
Class : Student

Student Object : s1 : 1, "Dilip" , 100


Student Object : s2 : 2, "Alice" , 99
Student Object : s3 : 3, "Suresh" , 88
Student Object : s4 : 1, "Dilip" , 100
Student Object : s5 : 4, "Bob" , 90
Student Object : s6 : 2, "Alice" , 99

HashSet<Student> students = new HashSet<Student>();


Use Case : 1
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);

size of an Array ? 6

Use Case : 2
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);

students.add(s1);
students.add(s2);
students.add(s1);
students.add(s2);

size of an Array ?

-> When content of 2 Objects is same then please make sure their hashcode reference
also.

-> Comparing content of two Objects :


equals() // cheking content : Same : hashcode() should be same
equals() // cheking content : Not Same : hashcode() should not be same

-> Please override equals() & hashcode methods based on above contract;

Assignment : Non Primitives : Please do with TreeSet : Data is sorted

Map Interface :
---------------

-> Map interface id part of java.util package under Collection Framework


-> Map is used to store data in key-value formats
-> Impl classes : HashMap, TreeMap & LinkedHashMap

Map<K, V>

HashMap : Class:
---------------

-> key & formats value

-> key's are not allowed with duplicates i.e. unique keys
-> Values are allowed with duplicates

-> In HashMap , as a key only one time "null" is allowed i.e. we can use
null as a key only one time in HashMap.

-> In HashMap , we can pass any number of times "null" as value for keys.

syntax :

HashMap<Key-DataType, Value-DataType> map = new HashMap<>();

Adding Values :
put(key,value)

Req : Store all emailId's and passwords.

Key : email Ids : String


values : passwords : String

Iteration of MAp Objects :


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

Req : Please print all key's and Values in the format of


key -> Value

Primitives & String

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

Iteration of Maps

Objects as keys and Values : Yes

Req :

Collect all Orders Information based on Order Id.

1 : 1,100,dilip@gmail.com,3

Key : Integer
Values : Order Objects

Req :

Collect/Store all Orders Informations (id, price, email) as keys and


it's status as values.

1,100,dilip@gmail.com : CREATED
2,200,dilip@gmail.com : DELIVERED
3,300,dilip@gmail.com : CREATED
3,300,dilip@gmail.com : CREATED

Key : OrderInfo

Value : String

only Unique keys :


order id : 6 : Added :
order id : 6 : Added :

only 1 Order info object with order id : 6 :

Assignment :
============

1. Collect All products information assciated to Order Information.


Key:
Order (oid :100, name :Dilip, price : 1000, noOfItems : 2) :

Value:
2 Product items
(1, Phone, 500)
(2, Chrager, 500)

Use Case 1:

Note : don't allow duplicate producst in an order:


Product : equals() & hashcode()
HashMap<Order, Set<Product>> info = new HashMap();

Use case 2:
-----------
Note : allow duplicate producst in an order:
Product : equals() & hashcode()

TreeMap -> HashMap :


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

TreeMap:
-------
-> Key's stored in Sorting Order
-> will not allow null as a key.
-> if we are provding null, Exception in thread "main"
java.lang.NullPointerException
-> many times we can pass null as values

Req : Please collect all students information based on Student id & make sure
student id's in an order:

key's
1
2
3

23,3243
44
5435456
45

Extra logic

23,45,3243,5435456, 23

Hashtable :
----------
-> Similar to HashMap

-> null not allowed as a key


-> null is not allwoed as a value also

-> is Thread Safe


ConcuurentHashMap:
------------------

It is thread safe

-> Reccomonded inplace of Hashtable

HashTable
ConccurentHashMap:

ke- Value operations :


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

Assingment :
------------

-> Objects as Key & Values in TreeMap also(ensure duplicate Objects are identified
and elimnated as key's)

FAQ : Internal Behaviour of HashMap.(PUT/REMOVE)


-> what is HashMap Collison
-> Internally How HashMap managing collison
->

Pre Defined FI :
=================

java version 8 onwards:

Function
Consumer
Supplier
Predicate

Function, Predicate, Supplier, Consumer

Functional Interfaces & Lambda Expressions

package name : java.util.function

Function
Consumer
Supplier
Predicate

FAQ's:
------
1. What is FI?
2. What is importance/pupose of FI?
3. What is diff b/w FI and a Regular Interface?
4. Is it possible to add more than one method in FI or not?
5. what is Lambda expressions?
6. What is the relation ship b/w FI and LE?
7. Can we Implement LE for a regular interface or not?
8. What is the syntax for Lambda Expressions?
1 line body
more than one line body : syntax
9. IS it possible to do Stream API operations without FI and Lambda Expressions?
10. is it Lambda Expressions are mandatory for FI implementation?

--------------
11. Have you created any time FI? User Defined FI?
12. dou know any Pre Defined FI in Java?

Package java.util.function Description:

Functional interfaces provide target types for lambda expressions and method
references.

Each functional interface has a single abstract method, called the functional
method for that functional interface, to which the lambda expression's parameter
and return types are matched or adapted.

Functional interfaces can provide a target type in multiple contexts, such as


assignment context, method invocation, or cast context:

Function
Consumer
Supplier
Predicate

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

1. Function:
-------------
Interface Function<T,R>

R apply(T) -

Type Parameters:
T - the type of the input to the function
R - the type of the result of the function

1. SAM is mandatory.
2. 0 or more than 1 abstract methods not allowed.
3. we can add many default and static methods inside FI.
4. default and static methods are non-abstract methods

5. SAM -> for that only we are writing Lambda Expressions.


6. Lamnda Expresssions are n/b impl of SAM of FI.

Assignments :
------------

1. Get Sum of Marks of given Student Object


2. Get Avg of Salaries of given EMployees.
3. Get All Female Employees List from Given Employees
4. Please check given employee is MALE or not and then return their name.

2. Predicate:
-------------
Interface Predicate<T>

SAM :
boolean test(T t)
Evaluates this predicate on the given argument.

Type Parameters:
T - the type of the input to the function

-> When we are passing i/p of any type but result is boolean then we
can take Predicate into picture.

//Req 1 :
// Please check given employee is MALE or not.
// I/p : Employee
// O/p : Boolean

Function<Employee , Boolean> => Predicate

// Req 1: length of a String : i/p : String , o/p: Integer

Function<String , Integer> : Yes


Predicate : No : Return value msut be boolean.

// Req : expired : true , not expired : false


Identify given Coupon Code is expired or not.
Cupon COde : String
=> Logic
=> o/p : eitehr true /false

=> Predicate : i/p: String , o/p: Boolean


=> Function : i/p: String , o/p: Boolean

Predicate can be replcved by Function but not vice versa.

https://www.youtube.com/watch?
v=NC4mHPobpGg&list=PLYQLxi4fXFVb3Cug9P_YvF64LQOwxY8x2&index=4

Supplier -> no i/p => o/p


Consumer : i/p , no O/P : void

Supplier

1. apply 2.get
3. test 4.accept

https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

Stream API:
==========

Java 8 : FI,LE....

THis is powerfull concept to dela with collections of data in functional way


or declarative way.

Stream API will enable manipulatinf data like fitering, mapping, grouping ,
collectiing, reducing...

java.util.stream.Stream<T> : Interface

-> an Interface can refer impl class Object

API : Predefined Classes & Interfaces

-> by using stream() , we wuse to make a Stream instance from our SOurce.

Stream<Employee> allEmployeesStream = allEmployees.stream();

API Document :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

filter(Predicate) -> Conditions


Predicate -> Impl -> pass to filter method.

Stream Methods : Stream Operations


filter() -> filetr Operation
map() -> ampping operation

2 types of Operations:
---------------------

1. Intermediate Operations
-> When we are using intermediate operations on Stream,
result is also a Stream Instance.

-> We can use any no of Intermediate operations on Stream


Instance,

2. Terminal Operations
-> When we are using Terminal operations on Stream, result
is not a Stream Instance it means the real type of required Data.

-> We can use only one Terminal operation on Stream


Instance at a time.

Stream Pipeline:
----------------

-> All Intermedate Operations or methods returns always a Stream Only.

-> All Terminal Ooperations or methods returns a result from the Stream n/b
when we call termainal method immeditely in Stream pipeline all intermediate
operations are executed result of all intermediate operations is ( Stream )
converted into the real result.

-> A Stream pile line should have always only one terminal operations
mandatory.

-> Stream pipeline will not be allowed more than one terminal method but
allowed more intermeduate methods.

-> In Stream pipeline first we ahve to use intermediate operations and at last
that means to terminate Stream pipeline and converting resulted stream into the
real/actual result we have to use terminal method.

resultEmployees= allEmployees.stream().filter(....).toList();
filter() Stream API :

map(Function)

Interface Function<T,R>

R apply(T) -> Employee -> String


String : Class

Consumer : void accept(T)

emp -> e

filter: Predicate
map: Function
forEach : Consumer

Collectotrs in Stream API :


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

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/
Collectors.html

-> A class is part of Streamp API


-> This class is part of java.util.stream , JDK 8

-> Collectors are used to accumulate elements of Stream Object into a collection
Objects.

-> Collectors, we can perform grouping, Joining operations from a Stream Object.

collect() method always performing operatins with Collectors.

grouping :
-----------

-> Male Employee


-> Female Employee
-> Hyderbad Employees

Req :
=====

Get Employees Count based on City

Key : City Name


Value : Count of Employees
New York : 10

TODO :
1. Get employes count based on Gender
2. Get All Products count based on Category
joining :
--------

Attaching

-> join all employees citys like


New York <-> CHicago <-> Dallas

delimiter

Mr. .....Name ... Sir * Mr. .....Name ... Sir *

Functional Interfaces -> Lamda Expressions

Req : List Of Products


111, MI 13 , Mobile, price, Country , Quanity.
// 1000

-> Get All Products ids and names which are belongs to Mobiles Category and that
to those mobile origin should be china.

// Map : Id : Name : collect : Result


// Conditionds : category = mobile

lsit.stream()
.filter( p -> p.getCategory.equls("Mobile")) // 200 // All Countries

.filter(p -> p.getCountry().equals("China")) // 66 // Stream

.collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));

https://github.com/DilipItAcademy/java-8-features/blob/master/Stream-API/src/com/
dilip/it/academy/StreamOperations.java

Optional Class :
----------------

This is JDk8 feature

Optinak class is a Container Object, this is used to contain a value that


might be presented or not.
-> In Side Optional Object, we can keep any data type content.

java.util.Optional

get()
isPresent()
of(T value)

of():
---
Used for putting a value/instance inside Optional Container.

get()
----
Getting value/instance from container

Exception in thread "main" java.util.NoSuchElementException: No value present

isPresent():
-----------
value presented inside Container or not

isEmpty():
--------------
value presented inside Container or not

filter(Predicate):
-----------------
idenitfying Container value is matching to a specific criteria or not.
if matching ....
if not matching ....

ifPresent(Consumer<? super T> consumer):


----------------------------------------
If a value is present, invoke the specified consumer with the value, otherwise do
nothing.

i/p-> void

if value prsented in Container, do some logic

isPresent -> Get -> do


not prsent -> Nothing

Method & Constructor References :


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

Java 8 :

Method References :
-> Method References are shorthand fromat of Lambda Expressions.
-> Method References dealing with Functional Interfaces.

-> Whenever we want to use Method References in place of Lambda Expressions,


please make sure the signature of abstract method of FI is similar to the method
what we are referring by Method References.

Synatx :

ClassName::MethodName

Note : No need to define method paranthisis braces

-> check given String is empty or not

Tyeps of Method References :


----------------------------
1. Reference To static Method - Done

2. Reference to instance method - Done

StudentOperations st = new StudentOperations();


StudentEligibilityCheck check2 = st::isMaleStudent;

3. Reference to instance method(of an Arbitary Object)

Predicate<String> predicate2 = String::isBlank;

4. Reference to constructor :
===============================
-> Cunstructor : Creating an Object

Student s = new Student();


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

ENUM :
-------
Enumeration

-> This is a special data type used to defines aset of fixed values/constants.

static & final Variable : once initilization -> Later No Modification

Week Days :
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

total 7 Varibales

syntax :
---------
enum : keyword

public enum <enum-name> {

values

ex :
public enum WeekDays {

ex :

Order Staus :

CREATED , PACKAGING, INTRANSIT, DELIVERED, CANCELLED, RETURNED, COMPLETED

public enum OrderStaus{


CREATED , PACKAGING, INTRANSIT, DELIVERED, CANCELLED, RETURNED, COMPLETED;
}

name() : Metohd from enum


------------ Use Case 2 -----------------

Enum with Constructors & Methods

Assingment :
-----------

// JAN("January", 31) : with String

Threads & Multi Threading:


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

What is Thread ?

Thread is the tiny/smallest part of a process, which runs independently.

-> a Process contains many threads.

-> Process : Process is the instance of a computer program that is being executed
by one or many threads.

2 types of threads :
----------------------
1. User Defined Threads : Created by the programmer for specififc tasks.

2. Daemon Threads : Background Threads.


-> Manage User Defined threads

Garbage Collector :
JVM : Object un Useed : Free Space

How to Create Threads:


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

-> Create Threads


-> Managing Threads

Create Threads :
-------------

2 ways : Thread n/b Object

Abc => Exception Class : No


Abc extedns Exception : Yes

1. By using Thread Class


2. By Using Runnable Interface

Abc -> Thread Class : No


Abc Object : Not a thread

Abc : Thread / Runnable => Thread


Abc Object : Thread

1. By using Thread Class:


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

@FunctionalInterface
public interface Runnable {
/**
* Runs this operation.
*/
void run();
}

public class Thread implements Runnable {

Step 1:
======

-> We eill inherit Thread class

package : java.lang.Thread

Not Thread Class :

public class FirstThread {

Thread Class :

public class FirstThread extends Thread{

Step 2:
======
-> we have to override always run() method with logic

@Override
public void run(){
// logic
System.out.println("FirstThread Started Executing");
for (int i = 0; i < 10; i++) {
System.out.println("FirstThread Executing " + i);
}
}

Step 3 :
-======
Create thread : Creating an Object

FirstThread t1 = new FirstThread();


Step 4 :
--------
Starting Thread:
Note : In this case to execute logic of run() as Thread we have to call
always predfeined method start() from the Thread Class.

Use Case : run() calling instead of start().

FirstThread Started Executing


FirstThread Started Executing
FirstThread Executing 0
FirstThread Executing 1
FirstThread Executing 2
FirstThread Executing 3
FirstThread Executing 4
FirstThread Executing 5
FirstThread Executing 6
FirstThread Executing 7
FirstThread Executing 8
FirstThread Executing 0
FirstThread Executing 1
FirstThread Executing 2
FirstThread Executing 3
FirstThread Executing 4
FirstThread Executing 5
FirstThread Executing 6
FirstThread Executing 7
FirstThread Executing 9
FirstThread Executing 8
FirstThread Executing 9

Use Case :

Prvent Simultanious Excetion : What to do?

t1 -> Complted,
t2 -> Start.

Runnable Interface :
--------------------

This is used for creating/implementing Threads

@FunctionalInterface
public interface Runnable {
/**
* Runs this operation.
*/
void run();
}

Step 1 :
--------
Define class by impl. Runnable interface.
impl run() method.

Step 2:
=-----

Creating the thread :


Create an instance of Runnbale impl class and gaina pass it as a
argument to Thread Class Constructor.

//created Object for impl class.


ThreadTwo t1 = new ThreadTwo();
//passing runnable impl class Object
Thread thread1 = new Thread(t1);

// 2nd Thread
Thread thread2 = new Thread(new ThreadTwo());

Step 3 :
--------
Starting Thread:
Note : In this case to execute logic of run() as Thread we have to call
always predfeined method start() from the Thread Class.

Thread Life Cycle:


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

New -> Runnable -> Running -> Terminated

start() : inviking thread for execution


run() : for Logic impl which has to executed by threads.
sleep(time in ms) : idle for that specific time
getName() : current Thread Name
setName(String Name); Setting thread name

join() :

join() is used to pause the execution of the current thread until the
specified thread finishes its execution.

t1, t2

-> make sure one thread complted execution before joins other thread.

synchronized key word :


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

synchronized methods:
====------------------
1. make method as synchronized method i.e. add the synchronized
in method signature.

-> synchronized method locks the entire method so only one thread
can excute it once.

synchronized blocks

File Operations :
==================

You might also like