B2-Sep-18 Notes
B2-Sep-18 Notes
=============
About Me :
=========
Dilip Singh
MNC , Asc Manager , 12+ Year
Java Developer
Beckend Developer
Skill :
Java , Spring, Spring Boot , & Micro Service App
Theory :
Real Time :
Java Training:
=============
Placements :
->
Programming Lang :
------------------
Java :
Framework:
----------
Struts
Spring
Spring Boot -> Right Now
Quarkus
Micronut
python : Django
.net : asp .net
js : RJS , AJS
Biryani :
Swiggy : 1 day : 10 < orders
Mon- Saturday
Core Java :
----------
1995 -05-15-2025
Java :
-> Core Java : JSE : Java Standard Edition
-> Advanced Java : JEE : J2E : Java Enterprise Edition
Core Java :
Baiscs and Fundamental of Programming lang
Rules & Regulations
OOPS :
Errors / Exceptions Handling
Collections
Java 8 Fetures
-> By Using only Core Java , can we create a Real S?W app or not ? No
-> By Using only ADV Java , can we create a Real S?W app or not ? Yes :
2 years
+91 8125262702
What is a Language?
Language :
English, Telugu , Hindi ...
S/W Applications :
Editors, Phostoshop, Paint , Sublime text etc..., Zoom
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.
Web Applications:
---------------
Internet 100% , Browser
Netbanking ,
-> PL Leraning
-> Scietinst
Mobile Applications:
--------------------
App -> FE ->
+91 8125262702
Java Installation
First Program
Steps :
Terminology : Concepts
let's installation :
Downalod Java S/W:
java 17 : windows:
https://download.oracle.com/java/17/archive/jdk-17.0.11_windows-
x64_bin.exe
Java Compiler
JRE : Java Runtime Environment
JVM : Java Virtual Machine
-> Name :
FirstProgram
D:\Classes\B2-Sep-18\programs
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
<FileName.extension>
Ex : Product.java : Valid
ProductDetails.java : Valid
Product Details.java : Invalid Java File Name
Productdetails
Baisc Commands :
Windows :
linux OS : Commands
Java 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.
-> I have .java & .class files, now I deleted .java file, Program will be executed
or not?
-> 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.
Platfrom Dependent : C
What Object?
-> A is Child of B
-> B is Child of C
A and C ? A is father is B , B's father is C
-> Abstratction
-> Polymorphism
-> Encapsulation
Programming :
Class in Java :
-> In Java language, We will write logic always by using a concpet called as Class/
Classes.
What is class?
Object Oriented programing lang: / Run time/ Excectuion -> Object Driven
Student Class -> How many Object Can I create for Student ? Many
-> tHose words are reserved by Java lang for a specific functionlaity or a
specfic reason.
Car ->
Syntax: Template :
-----------------------
Java Case Sensitive :
// logic
// 3000 lines
Ex :
public class Student{
// Logic
}
=> JAva will use always main method() as an entry to start execution of loigc
=> When we execute, then JAVA/JRE/JVM is always looking for main method :
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
Assignment:
=> Write a java class: And Print Information of your Details
Object :
========
Which is having an existence in this world is called Object.
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 :
======
Ex : int a;
int age = 30;
int mobile;
...
..
Example :
int a = 10;
String name = "Dilip";
2 types:
Varibale Names :
---------------
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
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
int 4
long 8 byte
5. float - 4 Bytes
6. double
7. char
Character : A B a x
AB is not a charcter.
Y
N
char passed = 'Y';
gender : M
8. boolean
if(conditions){
// logic : instructions
}
try{
}
catch(){
// lines : ended with ;
}
}
String : class
Arrays
Classes
Interfaces
Annotations
Enum
etc.
USer/Developer- Defined:
========================
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
Rule : In Java, string Data Type values hsould be enclosed in between " "
always.
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.
Types of Variables:
===================
1. Static/Class Variables
2. Non-Static/Instance Variables
3. local variables
1. Static/Class Variables:
=============================
main(){
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.
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.
method1(){
String email;
}
method2(){
boolean areYouOkay;
}
}
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
-> Whenever We creates an Object for the class, for every Object,
instance varibales are allocated with their respective sizes and values.
-> Whenever we created an Object, that will be created always inside Heap
Memory
instance = Object
10 created Objects
10 * (5 * 4) Bytes =
10 * (2 * 4) Bytes =
10 * (5 * 4) Bytes
(2 * 4) Bytes =
0 Objects :
-> 2 * 4 Bytes
Req :
Company Name
Company Emp Count
Company CEO
Product Name
Product Price
Product launchingYear
Many Objects/Products
Dynamic Person :
Static : Fixed
Calculaor:
let result = 0;
result = a/b;
result = 40/20;
result = 2;
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
Methods In Java?
----------------
What is Method?
---------------
Ex:
Please calculte EMI Value for loan amount.
Identify Formula
P = 100000
I : 11
60 MOnths
3 I/P Values :
O/P : 1 value
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
..............
Types of Methods :
----------------
1. Static Methods
2. Non Static Methods
1. Static Methods :
-----------------
Syntax :
--------
//Logic
// Set of instructions
// 1 line to 100 lines
Ex:
public static void addition(){
//logic
}
Access Specifiers:
public
private
protected
default
i/p: cash
-> Visit Apple Store
-> Findout 16 pro
-> black color
-> Pay the amount
Ex:
public void addition(){
//logic
}
-> 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
Method Arguments/Parameteres:
--------------------------------
-> Create a method , and that method should take 2 values and that
method should return addition result value
// 0 arguments
//Logic
// Set of instructions
// 1 line to 100 lines
//Logic
// Set of instructions
// 1 line to 100 lines
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 :
System.out.println(name);
Req : write a method which should print email and age of a person
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 :
-------------------
Syntax :
--------
//Logic
// Set of instructions
// 1 line to 100 lines
static int a = 10; -> Behaviour -> Completely Diff from : Method ARea/Class Area :
singel copy
-> > 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);
-> static content of a class, we can access directly from either non-static methods
as well as static methods.
----------------------------
Assignment :
===============
non-static : addition(double,long)
static sub(int a, int b);
Assignment :
===========
-> varibales
-> Create Static Method , where it should take i/p of Static content
-> Non-Static Method : Take non-variables
20 Prog:
==========================================
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)
ClassName.MethodName(arg-value);
-> Create an Object for that other class and by using that
ref. we will call the method (object required)
-> objeName.methodName(arg-values);
Summary :
A{
int a = 10;
static int b = 30;
B{
// access A class a, b varibales
Summary :
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.
=================
Question:
==========
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?
}
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
-> 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()
40- 50 methods
API documentation:
=================
API : Application Programming Interface
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
// Constructors
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
0 -> 1st
1 -> 2nd
char c = name.charAt(4);
attaching / joining:
int a = 10;
int b = 30;
int c = a + b;
c value ? 40
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
-> d -> D
i -> I
// Logic
DILIP123XYZ
2 -3 hours
Integer :
String value to intrger :
https://docs.oracle.com/en/java/javase/17/docs/api/index.html
https://devdocs.io/openjdk~17-package-java-lang/
int Student{
// Inavlid
}
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.
}
==========================
RealTime Projects:
-----------------
100% difficult
IDE , this will enables easy way of developemnt, testing and debugging
environment.
IDE will enables all activites in GUI mode.
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.
Workspace Path:
================
Workspace : This folder will contains all your java projects / code
Source Code :
-> right click on src
new -> class
Enter class Name :
Execution :
=============
Right click on java file : Run As -> Java Application
packages in java :
------------------
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.
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
many packages:
String belongs : package : java.lang
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.io.File
what is default ?
-> Other tha java.lang content , we have to use always import statement
with package information.
what is . symbol?
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
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
----------------------------------
Domain: https://www.swiggy.com/
swiggy.com
pkf :
com.swiggy
swiggy :
project:
src :
com.swiggy
com.swiggy.customer.payment
com.swiggy.payment
com.swiggy.delivery
com.swiggy.delivery.boys
com.swiggy.payment.upi
instagram.com
com.instagram.<modulename>.<functionlity>
Guidelines of Names
Guide Lines :
Better way,
Class Names :
-------------
StudentInformation : Valid
Student Information : In Valid
student.java
Student.java
STUDENT.java
StUDenT.java
Student
StudentInformation
STUDENTMarks
Productdetails
ProductInfo
product
student
calculator
ORDERINFORMATION
}
public class Student{
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:
==============
swiggyapp
swiggy-app
mypractice
my-practice
Operators:
=============
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
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
===================
+ : Positive Number
- : Negative value
++ : Increment Operator
-- : Decrement Operator
! : not Operator
++ : 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.
-- : 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.
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;
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
==========================================
true/false
!true = false
!false = true;
SOP(areYouMale); //
SOP(!areYouMale); //
CSE
EEE
CE
ECE
MLE
AIE
1000 Studets
s1 : CSE
student.branch != EEE
selected
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
== : 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;
35
30
35 > 30 : true
35
40
35 > 40 : false
-> LHS operand is greater than RHS operand, then result is : true
otherwise 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.
-> LHS operand is greater than RHS operand, then result is : true
as well as
-> 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
10 < 20
-> LHS operand is lesser than RHS operand, then result is : true
otherwise false.
-> LHS operand is lesser than RHS operand, then result is : true
as well as
-> LHS operand is greather than RHS operand, then result is : false
! 2000 <= 1900 ->
10 mins :
a = 10
b = 10
10 - 15 : Mins : Individually:
progrmming :
============================================
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
statement:
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:
OR Operator : ||
------------------
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:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
syntax :
=========
Example :
int a = 60;
int b = 80;
Example :
//People who got more than 70% and female persons, they are eligible:
String result = percentage > 70 && gender == 'F' ? "Eligible" : "Not Eligible" ;
// A : F : 60
=> Asgginment :
===============
instanceof operator:
---------------------
After the topic : Super Class / Sub Class
https://www.rapidtables.com/convert/number/decimal-to-binary.html?x=999
-> Control statements are going to decide wheather logic should be executed or
not.
=> 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
synatx :
================
if : key word
} // if block ending
=> if block
=> { } : block
2. if - else statements:
==========================
if : key word
else : keyword
} // if block ending /
-> Wehen we are joining more than one if...else.. blocks togeather is
called if else if ladder.
synatx:
========
} // if block ending /
} else if(condtions){
} else{
// default
// All above if block conditions are false
}
Req :
=====
Loans :
-----------
CIBIL score :
5. nested if statement;
-----------------------
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;
->
<5k
5k -10k : 1000 of
10-15 : 1500
=============
eduction :
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:
----------------
Time Table :
------------
SUN ->
MON - SUN
TUE ->
MON->
// 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
}
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.
-> whatver data type value is defined at swithc level, same data type values should
be defined at case level.
-> whenever we defined cases in switch, please make sure breaking the logic
execution.
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
default block:
==============
synatx:
default:
//logic
-> default block will be executed always whne no there no mtach with case
values.
Assignment :
=------------
Req :
Create Calculator Application ,
ADD
SUB
MUL
DIV
REM
You have to pass which Operation should be done on two values always.
int a = 10;
int b = 30;
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
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:
========
i/p : grade
D -> certifciate
F -> WARNING :
switch. if else if
-------------------
switch :
2. Looping/Iteration Statements:
=================================
Loops in Java :
===============
what is a loop?
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 :
//loigc
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
Assignment :
===========
Req :
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 :
2.while loop:
-------------
synatx:
------
// logic : Repeatdely
Req :
print values from 1 to 10:
Starting : 1
Ending Value 10
Increment way
// logic : Repeatdely
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
3. do-while:
------------
do : key word
synatx:
------
do{ // starting
of d0- while loop
// logic : Repeatdely
====================================
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 :
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.
Note:
======
Usage of loops is reduced from java 8 version onwards .
Arrays
Collection : List Set
while ->
for-each
do-while
3.Branching/jumping Statements:
------------------------------
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);
}
return 10;
}
}
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
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
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.
double,
char
float
boolean
Today onwards :
if data Type and values are not matching : methods used from Scanner class:
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.
*/
Constructors:
-------------
Most Important : Involved in Everyday Programing w.r.to RTP
what is Constructor?
-------------------
Constructor:
-----------
A Class
A a = new A();
-> 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{
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
}
Behaviour:
---------
4. Constructors are executed only once while an Object is created for that
class.
Question :
If I want to execute constructor one more time, what we have to do?
//constructor
public BankApplication() {
// Logic
System.out.println("This is Constructor of BankApplication");
}
-> While creating an Object, JVM verifies any Constructor defined or not. If
defined that will be executed immediatley.
Question:
----------
-> No
-> 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?
either 0 or 1 :
public BankApplication() {
// Logic
System.out.println("This is Constructor of
BankApplication");
}
public BankApplication() {
// Logic
System.out.println("This is Constructor of
BankApplication");
}
}
Compiler Error:
=========================================================
IMP:
---
2. Parameterized Constructor.
============================
// Deafult Constructor
public Employee(){
// Parameterized Constructor
public Employee(int id){
Question:
--------
-> In a class, How Many Parametrized constructor's we can define?
Constructor Overloading :
--------=------------
There should be a difference in parameters section w.r.to
no of parameters and data types of parameters.
public Employee(){
//Logic
//Logic
}
Execution:
---------
-> When we have to initilize the data for non-static/instance variables while
creating Object, then we will write 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:
==========
Arrays:
======
price = 99.99
99.99,88.88,77.66 ..... : Set of : More than one value : Arrays
Arrays :
Defining Arrays:
-----------------
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:
------
what is index:
---------------
2000 pages :
1,2,3,.....
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 value :
prices[1] = 33.44;
Assignment :
------------
Take a String Arrays :
double :
-> 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
synatx:
-------
for(<datatype of Values of An Array> <varibaleName> : <array>){
//logic : varibaleName
}
for | fro-each
=======================
Req :
All values : for , 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.
-Assignment:
-----------
=> Non-primitive :
===================
-> when we created an Array with Non-Primitive Data Types , then we can store
respective datatype/class Objects inside an Array.
in such case Array index maintain references of Objects but not a copy of Objects.
address :
return names;
}
Assignment:
===========
1. Define a method with Return type int, double, long ... char..
via loops
Assignment :
===
->
====================================
why main method is having String[] args
public static void main(String[] args) {
//logic
}
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
by using command line args, we can pass values to String[] of main method.
Eclipse :
------------
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
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.
int a = 10;
int b = a;
Integer c = b; // Auto boxing
int d = c; // Un boxing
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{
//
static m1(){
//logic : values :
-> 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.
Question:
==========
instance block /constructor ? which one will execute 1st?
class Student{
OOPs Principles:
---------------
class Student{
// 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:
-----------------
A{
int year = 2024;
m1(){
}
}
B{
m2{
// m1 of A
Create an Object of A
a.m1();
sop(a.year);
}
by using a keyword called "extends" , we cam make inheritence relation b/w classes.
syntax:
=======
public class A{
// 5 methods : 5 functionalities
}
// 5 new add
syntax :
-------
class <Super/Parent/Base>{
1000 classes
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?
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 {
PaymentThree{
PaymentFour{
Implementation :
================
class PaymentOne{
netbanking(){}
}
debitcard(){
creditCard(){
upi(){
}
}
=============
=============
Arrays :
//
456
Abstraction :
=============
1. Interfaces : 100%
======================
what is an Interface?
Example :
Synatx:
Error : The type ICICILoanapplication must implement the inherited abstract method
LoanInformation.getLoanType()
when we defined a method signature but not logic that means those methods are not
concrete methods (methods without body/logic)
syntax :
======
abstract classes
===========================
}
Inheritence in b/w classess:
=> Rule : provding impl for all abstract method of all interfaces in the class.
interface : 3 methods
class : impl for 2 method only : Compile Error : 1 method is pending
static varibale :
----------------
Interface :
InterfaceName.varibaleNAme;
// variables
class Two{
final variable :
=================
final is a keyword.
Class:
class CompanyInformation{
-> 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;
=-====================================================
// variables
========================================================================
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;
------------------------
interface A{
inrerface B extends A {
inrerface C extends A {
4. Multiple Inheritence:
=======================
Which is correct?
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.
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{
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.
-> How many abstract methods can we define inside a class ? More than one
why we are adding abstract method inside a class rather than in interfaces?
----------------------------------------------------------------------------
2. When we don't want to allow creating an Object for a class, then also we can
make that class as abstract class.
}
============
Note :
// final variables & static : naming convention :
Polymorphism:
--------------
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 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 )
case 1:
-----------
int sum(int x, int y)
double sumb(int a, int b)
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 :
-------
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:
---------
Overriding : When are taking one more time same exaclty which is already existed.
Method Overrding :
-------------------
-> Method Overriding : Same method signature including method parameters also.
-> 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 {
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 :
bought a bike
Child
Use :
use parent bike
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:
A{
m2(){
}
final m3(){
B extends A{
m2(){
}
m3(){ // Compile error
final class:
------------
final varibales, methods, classes.
Syntax :
======
=> When we make a class as final class, that means that class not allowed to be
inherited.
// no overdding
Question:
keywords:
this keyword:
-------------
A a = new A();
a -> reference
this -> reference of current Object being used by JVM.
*** RULE : Calling constructor should be 1st line of constrcutor body. Oherwise we
will get compile time error.
constructor chaining.
only one constructor shlould be called and calling should happen from 1st line
public ProductOne() {
System.out.println("This is Produc One ... ");
ProductTwo pTwo = new ProductTwo(this);
System.out.println(pTwo);
}
This keyword always represents content of super class 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 : Can we call super class constructor from child class is possible or not?
Yes. super
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){
Errors ->
Polymorphism:
-------------
OOP principle:
2 types :
1. Compiletime/static/early-binding Polymorphism
Method Overloading
2. Runtime/Dynamic/late-binding Polymorphism
Method Overrding
1. Compiletime/static Polymorphism
}
double add(int x, double y){
2. Runtime/Dynamic Polymorphism
===================================
Method Overrding :
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.
Sub CLass:
CreditCardPaymentApplication
NetBankingPaymentApplication
UpiPaymentApplication
Use Case 1: Not Overddien Method & Method is From Child Class
===========
CreditCardPaymentApplication#creditCardPayment() :
payment.makePayment("CC",9999);
payment.creditCardPayment();
Use Case 2: Not Overddien Method & Method is From Parent Class
===========
PaymentApplication#getPaymentType() :
payment.makePayment("CC",9999);
payment.getPaymentType();
Note:
-----
When we are using super class referring sub class object concept, the method
should be presented in Parent class.
//
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.
4. Encapsulation :
-----------------
Data Binding
Req : At any cost don't allow any other class/Object modifying student id value.
POJO Class : NO RT
100s of POJO classes
1. DTO
2. VO
3. Entity CLass
4. Request Body
5. Response Body
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.
Rules :
1. Define private varibales
setter method:
==============
getter method:
==============
Lombok library
Assignment:
==========
Object Class :
--------------
Object class is a global super class for every class defined/implemented in java
lang.
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() :
O/p: com.dilipit.Employee@2f92e0f4
System.out.println(e2);
com.dilipit.Employee@372f7a8d
com.dilipit.Employee@372f7a8d
com.dilipit.Employee@372f7a8d
com.dilipit.Employee@2f92e0f4
com.dilipit.Employee@2f92e0f4
=======================
reference : ClassName@hadcode
-> reference : Print Data Of Object. : Overrdie toString() method
int hashCode()
In a class, When we override equals() method ,we have to override hashcode() also.
-1157744794
-1157921609
-1157744794
Type Casting :
=============
Data Type :
Casting : COnverting:
Type Casting is a process converting one data type to another data type.
Auto Boxing :
Type Casting :
========================================
a : 32-bit memory
long b = a; //
b : 64-bit memory
byte -> short -> int -> long-> float -> double
double -> float -> long-> int -> short -> byte
88.99 : 88
Non_primitives : References:
------------------------------
1. Up Casting (implicit)
Smaller reference -> Larger Reference :
=================================
}
from java 8, onwards
along with abstracgt methods, we can add static methods and default methods in
interfaces
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 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.
-> 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.
Req :
provide guidelines of a loan.
guidelines are common at every place.
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 :
Exception Handling :
Process of identifying the bug and it's root cause/ details as well process making
solution / fix this issue.
analyse the source code : why and where the issues are happening at run time
level.
Experience :
Executing : Applications
2 modes :
1. Run Mode
2. Debug Mode
Break points:
Whatver line, you would like to pause JVM execution flow, there go to
that line , on top of line number do double click.
Step Over :
Step Return :
Annotations:
============
Annotation : Metadata
Java :
Classes / interfaces
Methods
Fields
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.
Syntax :
@<annotation-name>
User-Defined annotations:
-------------------------
Create Annotation :
=================
Ex :
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Source Level
Compile Time level
Runtime level
RetentionPolicy
SOURCE,
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.
ElementType : enum
Java 8 version :
----------------
Functional Interfaces:
=======================
is this FI ?
public interface CalcOperation {
Ans : No
is this FI ?
is this FI ?
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
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.
@FunctionalInterface
public interface CalcOperation {
int add(int a, int b);
Synatx :
<FunctionalInterfaceName> <lambda-expression-name> =
(method parameters) -> {
//logic
};
lambda-expression-name.sam-name(arguments);
Ways :
======
2.
FI:
Abc{
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.
Exception vs Error
Can we call Error handling and Excectpion Handling, both are same ? No
bith are diff.
==========================================
-> Error are always generated due to infrastructure but not from logic.
What is an Exception?
---------------------
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.
Handling
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
-> An Exception class is a child class of Exception class and derived from
RuntimeException class is called Runtime Exception.
Handling Exceptions:
--------------------
1. try
2. catch
3. finally
4. throws
5. throw
1. try
2. catch
3. finally
-> try :
-------
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;
catch block:
============
1. catch block should be used always with try block i.e. we can't
define individual blocks.
syntax:
try{
// logic
}
catch(TypeOFException ex){
// logic of handling exception
}
Types Of Exception :
java.lang.ArithmeticException
NullPointerException
IndexOutOfBoundsException
FileNotFOundException
ClassNotFOundException
MethodNotFoundException
RuntimeException
SQlException
etc..
-> 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.
-> 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.
try{
//Logic 1
}catch(Exception ex) {
// Logic 2
}catch(StringIndexOutOfBoundsException e) {
// Logic 3
}catch(ArrayIndexOutOfBoundsException e) {
// Logic 4
}
-> 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
}
finally blocks:
---------------
finally : keyword :
syntax :
finally{
//logic
}
-> 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.
-> we can write try-catch-finally blocks where-ever we want as prt of logic impl.
-> can we arite more than one finally block? No , Allowed either 0 or 1 finally
block.
->
try-catch-finally: Done
-----------------
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.
propagate :
-> propagate/propagation:
------------------------
throw :
-------
-> 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.
Yes, We can do. But we have to follwo few rules to make sure class as Exception
class.
Checked/UnChecked : Checked
-> when we throw Checked Exception, Compiler showing an error to handle exception.
=========================================================
Collection Framework/API:
-------------------------
https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
Collection Interface : Sub interfaces : List, Set, Queue
List: Interface
---------------
-> java.util.List<I>
-> 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 :
================
Adding values :
------------------
add(Element):
Read/Get Values
---------------:
Generics:
=========
Generics is a feature provided by java for ensuring type safety at compile time
itself.
: Student ObjectS:
without generics :
->
Rules:
->
E -> Element
T -> Type
K -> Key
V -> Value
java.util.Iterator:
===================
• Iterators allow the caller to remove elements from the underlying collection
during the iteration with well-defined semantics.
Removing Values :
-------------------
remove(index)
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.
Student
EMployee
Order
Products
etc..
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 :
-------------
Employee : id, name , salary , age , gender , dept name, manager name, city
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
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:
------
Collections.synchronizedList(arrayList);
Set Interface :
---------------
===========================================================
HashSet / TreeSet :
Not allowing duplicates :
Data Types we are tested : String, Integer
String + Premitives
Non-Primitives :
-----------------
Class : Student
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.
-> Please override equals() & hashcode methods based on above contract;
Map Interface :
---------------
Map<K, V>
HashMap : Class:
---------------
-> 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 :
Adding Values :
put(key,value)
========================
Iteration of Maps
Req :
1 : 1,100,dilip@gmail.com,3
Key : Integer
Values : Order Objects
Req :
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
Assignment :
============
Value:
2 Product items
(1, Phone, 500)
(2, Chrager, 500)
Use Case 1:
Use case 2:
-----------
Note : allow duplicate producst in an order:
Product : equals() & hashcode()
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
It is thread safe
HashTable
ConccurentHashMap:
Assingment :
------------
-> Objects as Key & Values in TreeMap also(ensure duplicate Objects are identified
and elimnated as key's)
Pre Defined FI :
=================
Function
Consumer
Supplier
Predicate
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?
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.
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
Assignments :
------------
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
https://www.youtube.com/watch?
v=NC4mHPobpGg&list=PLYQLxi4fXFVb3Cug9P_YvF64LQOwxY8x2&index=4
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....
Stream API will enable manipulatinf data like fitering, mapping, grouping ,
collectiing, reducing...
java.util.stream.Stream<T> : Interface
-> by using stream() , we wuse to make a Stream instance from our SOurce.
API Document :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
2 types of Operations:
---------------------
1. Intermediate Operations
-> When we are using intermediate operations on Stream,
result is also a 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.
Stream Pipeline:
----------------
-> 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>
emp -> e
filter: Predicate
map: Function
forEach : Consumer
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/
Collectors.html
-> Collectors are used to accumulate elements of Stream Object into a collection
Objects.
-> Collectors, we can perform grouping, Joining operations from a Stream Object.
grouping :
-----------
Req :
=====
TODO :
1. Get employes count based on Gender
2. Get All Products count based on Category
joining :
--------
Attaching
delimiter
-> Get All Products ids and names which are belongs to Mobiles Category and that
to those mobile origin should be china.
lsit.stream()
.filter( p -> p.getCategory.equls("Mobile")) // 200 // All Countries
https://github.com/DilipItAcademy/java-8-features/blob/master/Stream-API/src/com/
dilip/it/academy/StreamOperations.java
Optional Class :
----------------
java.util.Optional
get()
isPresent()
of(T value)
of():
---
Used for putting a value/instance inside Optional Container.
get()
----
Getting value/instance from container
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 ....
i/p-> void
Java 8 :
Method References :
-> Method References are shorthand fromat of Lambda Expressions.
-> Method References dealing with Functional Interfaces.
Synatx :
ClassName::MethodName
4. Reference to constructor :
===============================
-> Cunstructor : Creating an Object
ENUM :
-------
Enumeration
-> This is a special data type used to defines aset of fixed values/constants.
Week Days :
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
total 7 Varibales
syntax :
---------
enum : keyword
values
ex :
public enum WeekDays {
ex :
Order Staus :
Assingment :
-----------
What is Thread ?
-> 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.
Garbage Collector :
JVM : Object un Useed : Free Space
Create Threads :
-------------
@FunctionalInterface
public interface Runnable {
/**
* Runs this operation.
*/
void run();
}
Step 1:
======
package : java.lang.Thread
Thread Class :
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
Use Case :
t1 -> Complted,
t2 -> Start.
Runnable Interface :
--------------------
@FunctionalInterface
public interface Runnable {
/**
* Runs this operation.
*/
void run();
}
Step 1 :
--------
Define class by impl. Runnable interface.
impl run() method.
Step 2:
=-----
// 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.
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 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 :
==================