0 ratings 0% found this document useful (0 votes) 4 views 17 pages Java Notes Part 1
The document provides a comprehensive overview of Java, covering its features, compilation process, and execution flow. It explains key concepts such as variables, data types, operators, control statements, methods, and arrays in Java programming. Additionally, it includes best practices and interview tips for effective coding in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Java Notes Part 1 For Later
WET EELELEL CEE RERELELE ELLE LER
© J @qa—insights insights
~ JAVA:
COMPLETE NOTES
= (Java) <
t1
. =e a
=| BEGINNER TO ADVANCED | =
SwIPE TO NEXT —> <—
See Le
CS a ee
FoLtow | <7 SHARE | C_) COMMENT | © LIKE@qa—insights
@® What is Java?
Introduction to Java
© Features of Java
Tava is a high-level, class-based, Y Simple Y Architecture Neutral
object-oriented programming language «& ¥ Object-Oriented (00P) ¥ Portable
designed by Sun Microsystems (now —_- Platform Independent — ¥ High Performance:
ouned by Oracle). It is platform = ¥ Secure V Distributed
: <=
independent, secure, robust and ee lat area
peas nee aero ear Java Y Multithreaded Automatic. Memory
applications, Android apps, web Management (62)
apps and more.
@) IDK vs IRE vs JVM -
Dk (dave, Devlapment. Kt) anpaeet crass
Provides tools for development TRE + VM +
separa eames JDk ect te fey
TRE (Java. Rantine Environment) pee eee!
Provides traces, JVM ond. other ‘JRE JVM + Cove Libraries +
(om) owe ad font pao Other Runtina Components
DZ JVM (Java Virtual Machine) Class Leader + Bytecode.
Za cna ated aM Vertter + Excetin Engine
runtime environment. + Runtime Date Areas
@ How Tava. Works?
Tava code (java) it compiled int» bytecode (class) using 2
‘the Tava Compiler (javac). This bytecode is executed by
JVM on any. platfrm
jen 3.
va] > | class] —> ‘
(bytecode) 5,
6.
3
}
i
{
i
1
{
1
l
p@) Remember
| Sm is “ite
‘cea,
i
| «BVH males Toe plat dependent
| + Bylecnde ts the Kart of
11 Hello World. Program
public class HelloWorld {
public static voi
Sys
smain(Stringl) args) £ |
[Link]. printin("Hello, Java!”"); es
very
Interview Fact ————
-
ney fan Anton” |_|
|
|
'
'
fe es Sacer Tae
'
Tae wet designed by Janes Gosling
in 1995 ond frst released in 19%,
| cade is java and for bytecode is ass |
© Compile & Execution Flow
Write Java code (java)
Compile a jevec (Compiler)
Generates. bytecade (lass fie)
JVM lads and veri bytecode
Output is deplged
class keyword -> defines a class
main() > entry point of program
System. [Link]() —> prints output
statement ends uith 5
File name must match class name (HellaWorld. java)
+ Wissing, main) meted
+ Wo sndertonding. compilation
eatin,
@qa—insights | Quality Insights, Better Careers!@ qa_insights 2D
JDK, JRE & JVM
® IDK (Cava Development Kit) (2) TRE (Java Runtime Enironment) (3) JVM (Java. Virtual Machine)
Heart of Java.
Full package for Java development. © Provides libraries, JVM ond
© Includes JRE + development tools. other components to run © Executes Java bytecode.
Tova applications
© Used to write, compile and run Platform independent -
Jove. programs. © Does not include development Write Once, Run Anywhere.
tools
aig ie eon ae ne ee & Manages memory, threads,
Trees sea ced peas
. WM
jo Camper (jasec) i
Tools (javadec, jar, jdb, ete.)
i i
& J tee ete & eee
@ Compilation Process
101010
= — > | esoses JVM
so1010
Hello jave SAVAC Hello clase (Execution) (Output)
(Source Code) (Compiler) (Bytecode)
© Bytecode i
| ‘Important. Note
* Output of Jove compiler (jvae) | Bie ee rset
Platform independent. | Pires aT nen)
i
Exeauted’ by DVM, not by OS divectiy compiler for better performance.
‘© File extension: class
© Execution Flow Diagram
Goon) [Smcam) [3M Eomte | dentep in 30K |
Using |=>| Bytecode |—>| Bytecode [>| Bytecode 1 & Run in JRE i
Caless) || 8 Ver Clnterptaton i Gf Evecation hoppers |
is i i
i
i
i
wie
[sen
[Gee
+37) inside JVM
t Y Write Once
{He Java ic Platform Independent because JVM is avilable on all major OS. | {Ran Arguhere@ qa—insights 3
Variables & Data Types
@® What is a Variable? @® Data Types
A veriale is « named laaton in memory
sed to store date that con be changed
a) Primitive Types b) Non-Primitive Types
Store single values Store reference to objects
!
daring program execution 1 c +
' i i
! z i i
int = 25 i i
int age ; : | |
i} i
fn tt, y i 8 i| !
it 1a i
Data Type vag Value [| Flot | 4 bytes 0.0f | | © Object 1
| | double | & bytes 0.04 { {© Collection (List, Set, Map) |
1 T char | 2 bytes | "wooo" fo i
it 4 bit fale J |
@® Literals ® Naming Rules for Variables
{= Integer Literal | BAL Must start with a. letter,
| « Floating Literal 3.44, -0.5F | Can contain letters, digits, '_' and ‘
i
i
* Character Literal + ‘A', ‘2', "\n! Zi Case sensitive: age and Age are different
+ String Literal "Hello Java” TZ Cannot be a Tava keyword (int, class, ete.)
(igkeeen ere ee eae LR] Examples of invalid names: tage, int, @age
® Memory Basics
Memory
sot] 25
Note:
based on its data type.
i
i
i
1002 >] 3.44 |
Primitive types store actual values
i
i
double pi = 3.145
7
i
Each variable occupies memory |
ble. oceupt ea
i
1003] TA’ i
char grade = ‘A
WUT
Non-prinitie types. store reference. |
1006 | true boolean ishctive = trus; et oe deen
SY Interview Tip
int a = 105 |B Use meaningful variable. names
int b= as // b gets a copy of value \
i
i
|
2 = 20; IJ b remains unchanged Hof dal fies
[Link](b); /] Output: 10
i
Declare variables close to where they are weed. |
@ qa_insights | Quality Insights, Better Careers!@ qa_insights
Operators & Type Casting
@ Arithmetic Operators
Used to perform basic mathematical operations
@® Relational Operators
Used to compare two values. Result is boolean (true/false)
® Logical Operators
Osed > combina mia rl
Operator | __ Description
| ak Logical AND
tl Logical OR
! Logical NOT
® Unary Operators
Operator [Description
Fd) Bay Veal
a Daryl is
$e | Precnronent
Sa Peter
Ne yess
Operate on a single operand,
Came EA SL ee
+ ‘adlton [ee | | Equal anh
- Subtraction | a-b Not equal to ath
| Multiptication Joasb | [ > Greater than arb
/ Division (awh) lees Less than ask
% Modulus (Remainder) | a%b | | >= Greater than or equal amb
+ | Tecrement | ase | stair EE
== | Decrement —-a
® Assignment Operators
Used te stn vale fo vers
|
au a
rasan
Bitwise Complement
Example Code
int 0 = 10, b= 3;
[Link] prin tin("a ob a" 5 (eB): 1 13
Syttemeat prin tin('a be" + (eB MF
[Link] prin tin('a b=" + (0 * WY; // 30
Syttemout prin tin('a / b=" + (a/b); M3
[Link] prin tin "a b= "+ (a %H); U4
System out printn"a >
(o>)
feats
Operators are the building blocks of expressions
‘and conditions in Java. Understand. precedence
|| 2) expe: (Narewing)
Larger Sale type (Hara!)
ae
| dele x = 25.35
inky = Gok) 5 debe te nt
faeces
L A b
(@> 0) bk (b>0) | geass i oie a
(> 0) I> 0) | es asa-b |
ME : coi ave
a Bee
© Type Casting
— aac ted oR rong
Pr + pliit (Widening) = done eutomaticaly
| * Eli rein) = de mel
ee 2 Tngt (tng)
el eee
Hrue false Example
a int a = 10;
ine b= 5] ted
a
Tong
short
i Always be careful while type casting
Narrowing conversions may lead to data losssights 3
Control Statements
Control. statements change the flow of execution based on conditions or
perform repeated execution of a block of code.
@® if-else
ith Be
i (m >= 0)
Sytem out. printin(“Poitv
Fale { |
Sistem aut printin("Negoive”) |
y }
int age
i
| if age
|
|
48) {
Syetem out printn(
"Eligible to Vote");
}
TD Executes block if condition TZ) Executes one block from two
Doo based on condition
&
2
@ for
int day = 25
sviteh (day) {
for (int i = 45 1 = 5; we) {
i
i
i
li
| i
Rec Splonet peancner) || i |
te
aa? Spimatgint ts | | Bick of} | | Systemoutprintn( Ds
cast 3-9 Slant pitt We), || toe J] |) |
|| fale,
Ain Seti |
Ht
)
Oh Bat he manta of
See aie ee
Tf Used when we have multiple
porsible values to match
int i= ty |
i int isa \ | batt
coc [erates
(ez Gabor |
(isin of aces ax oe Gf Eatin Hak a inl
condition is true once, then checks
condition
@® break & contin
for (int = 4 1 eo 8; ioe) |
© break fe continue ( fe Getto a tas me]
jf Ge 3) break; 1 if (i == 3) continues |
ee | sal Skpr caret tration | =}
eee Selenite || adn rt | Snare 2 |
—-
i We Odpat: 1245
GW pce ep ett tn |G Ba Pais td dap msn ty nt |
i improve cede redaity ond. performance conti to snl lose i
@ qa_insights | Quality Insights, Better Careers!@ qa_insights 6
Methods in Java <,
=
A method is a block of code that performs a specific task.
@ Method Syntax @ Parameters
© Parameters are used to pass date
accessModifier returrType mathodName(parameterLis) { ee rac ea
M1 method body # They act oe placeholders
return value;
public int add(int a, int b) {
+ return a + b;
}
pas pinks EE we New of Dopat a
protected, etc, ‘String, ete. ‘the method values a and b are parameters
@® Return Types @® Method Overloading
© Method con retum a value to the caller @ Same-masthod nama with differant
sont cea eee parameters
Return Type [ Meering
ois hE eel
int, double, ete, | Retums nanarie value
int add (int a, int by int e) {
ae ea |
E at return a+ b +; |
Teootean | Rats tr oF fe |
© Recursion
A method caling ul Z 35 r ra
pe a ifatine [Exar
Uae oe cp prt bo snl a
Pz cabana! neces rtd icek | int x = 10;
[int factrit(int w) { corte | “a |
| (or 0) return 45 11 Ban Cn ns Wis] Tie cs, | tats «ng | in ages
| return no factorial (n= 1)s 1) Resa Cl irate) as eject exits
hb ict es) EE ey oT
J (Cos Vr) oye te | | conti
@ Method Example (Complete Flow) © How it works?
publi class Deno ( © Tea
> | multipig() | —> | Returns | —> | Used in
Method Result main()
Ereaitad
public static int multiply(int a, int &) {
Interview Tip
return a bs
)
public static void main(StringL] ange) {
Methods help in code reusability, maintainability
and modular programing
int result = multply(S, 4)5.// mathd cl
[Link] printin("Result: " + result);
)
)
We Best Practices a fi
| GH Use meaningful method names, |G Avcid duplicate code i
FD Keep mathods small and focused. | (Follow single responsibility principle. | |
Remember:
[A giod method makes your
cade clean and easy to understand
@ qa_insights | Quality Insights, Better Careers!@ qo—insights 7
Arrays in Java
An array is a collection of similar data types
stored in contiguous memory locations.
© 2D Arrays | @ 2 Arrays
ea bea tie erecta eos yet ee tee)
ie Gatat |S tefl for tales, maiz, grid
COL] matrix = new int{2]13]5 ey
eee = 4; matrix (0) [1] = 25 matrix[0][2] = 3;
Is
rumbers[0] = 10; | Memory Representation |
rwmbers[1] = 20; matrix(1] [0] = 4; matrix [1] [1] = 5; matrix[1](2]
| numbers [2] = 0; | 10 | 20| 30/40] 50)
rumbers(3] = 40; t
rumbers [4] = 50; | vanbere C=. ipehal bes eos) aes
[Link] | itl)
© Array Operations
T
Operation Example
Declare |__ Create an array int] arr = new int(5]s
Access | Access element using index int val = are[2];
Update | Update element at index ‘arr[2] = 100;
Length |Get tatal number of laments int len = [Link];
ST ever alleal Roo ale such ae asear for (int i= 0; § [Link]; irs) { ... }
© Arrays Utility Class
© [Link]. Arrays provides useful methods
Sera
@ for-each Loop |
|
| Method n
|
|
|
|
|
i
© Simplified way to traverse arrays.
Read-only access (cannot. modify index)
Example:
e nae
| intl] arr = {10, 20, 30, 40, 5¢
for (int num : arr) {
‘Arrays. toString(arr) Returns string representation
Arrays. sort(arr) Sorts array in ascending order
Arrays. fill(arr, val) Fille array with given value
[Link] Farr, nenben) | Copies array to new length
‘[Link]. println (num);
}
Acraye-oquale(arr, arr) | Compares two arraye
| Q Interview Tip © Best Practices |
|e Arrays are fied in ie | | Use meaningfid names |
| # IndexOutOfBoundsException occurs for ‘+ Always check index before accessing |
| invalid index + Prefer Arrays utility methods for operations |
| # Use foreach loop for simple traversal. |» Avoid storing large data in stack, use arrays |
{ + Arrays are objects in Java. i in heap memory. |
@ qa_insights |@ qa_insights
:
String
@ String
Di
# In Java, String is an object of class
@ Strings are widely used to store and
manipulate text.
Example:
7 -
[ String name = "Java" ]
| String msg = new String("Hello"); |
| [Link](name); — // Java |
| [Link]; —// Hello)
U
@ Immutable Strings
B Sct apes ieee (rt tae
a, Aah opetin piers mg tate
asta ete eal
Examgle:
{ String st = "Hall;
| ie re
| String 52 = stoconcat(™ World), | “t
| i raf oti
| [Link](s1); 1 Wale oes fen
Pe aoe: Ae
® StringBuffer
s in Java
| ® String Pool
© String literals are stored in the String Peel.
| Tf a literal already exists, the same reference
is returned.
© Helps in memory optimization
String a = "Jove";
String b = "Java";
a b
| Game reference)
@ StringBuilder
© Mutable cass, used to may brings
© Nok spebenind “> nok rede
More efficent than Song fr single-treaded
sri
Example
‘StringBuilder ab = new StringBuilder("Jeve");
i grisd(= Prepsoiog') |
[Link](5, |
sb. delete(0, 1); |
[Link]( sb); |
| i
| eee
Hm is Programming |
© String vs StringBuilder vs StringBuffer
© Mutable class lke StringBuilder |
Eee hol ae | (estes Sing | StegBedar | StrngBaffor
4 Slower than StringBuilder bet safe for multi-tveding.| | — Mutable? No Yer Yes
Enanple | [rad sper [Yee Ne Yes
StringBuffer sb = new StringBuffer(“Java); | | | Performance Slow Fast Slow
Be te rman \ Less | Singla-thrended | Mull-threaded
sb. reverse}; | |] Use Case | modification | performance environments
[Link]. prints); // grinmergr? ava | tte,
@ Common String Methods
Mathed i Description | Esanple Outpt
length Returns length of string "Java™ langth() 4
sharAtCindax) Returns character at index chardt(2) «
tubatring bogie, and) | Returns part of string (begin, ond) ubatring(t, 3) ~
equala(str) Cape cetit cequale("jore") false
Salle sone ll Graetcgnararaieee equals lgporeCese( ore") tre
containe(str) nea WE errors ee fegemining ort Prog) [bee
indexOfltr) Bees indexOFCW 2
replace(eld, nan) | Replaces ll ceeurrancas raplace( "a, “=') Toes
{ollpperCase() Convarks to upper cate AoUpperCase() AVA
trim) Removes leading & aia spaces Tava". trin() “Java™
). Interview Tip
© Strings are immutable and stored. in String Poo
1 Une StringBuilder for better performance
© Use StringBuffer when tread safely is required.
@ qo—insights |
is Best Practices
raf StringBuilder ovr Sting for concatenation in lope.
+ bid ereting emmcenary String cel
ay mata tina fur bala realy,
Quality Insights, Better Careers!@ qa—insights 9
Classes & Objects in Java
Java is an object-oriented programming language
Everything in Java is an Object.
@® Object
© A Class is a blueprint or template * An Object is a real-world entity.
© Tk defines the properties (fields) and e Tks on instance of Class.
behaviors (methods). of objects | © TE cecupies memory in Heap.
|
©® Class
pee cael eeocenb wears Example: Objects of Student Class
Example: Clats Definition
(clase Slade ig st (Object) +2 (Object)
String nema; M fala name —> “Alice” name —> "Bob"
| — # as W Field |
| [ee 20 ~ > 22
| void display() { W mathod —S———— x
| System. cut pritia(eame +" is" + 090);| | i
| } | Both objects are instances
Ge of Student class
@® Fields (Variables) | @ _ Methods
+ Fields represent the slats or data of an object. | © Methods represent the behavior of an object
* Each object has its oun copy of fields + Methods operate on fields and perform actions
© Object Creation
© Objects are created using the new keyword.
203)
| a Methods are defied inskle the clas
© Accessing Members
Use dot (.) operator to access falda and
methods of an object.
Example
( Student sd = naw Students =)
a eninge | sfename = “Alice; M7 access field |
we Stale); tweet) || 1 accuse fala |
new Stadnt();_// 2 thr ot | 11 call mathod_}
@ Class, Object & Memory
Objects Castances Stored. in Heap Memory
22
=| name > >
age 2
LY Best Practices
© Das cates arund real-world atts
‘© Keep fields private and provide public methods (encapsulation).
[Use msn ames for dar, ale ed mad
Quality Insights, Better Careers!@ qa_insights 10
Constructors & Keywords in Java
© Constructor Syntax its |
© A Constructor is a special method used Mase ClasiNane { | Y Note |
to initialize objects ClassName() { | Constructors are
# Te has the same name as the clase | used to seb intial
+ /1 isitialization code | _
TE has no return type (not even void). | values for object
ets cllad| putas kde } Pea |
aed os chiatad { J
® Default Constructor ® Parameterized Constructor
+ A construcer with no parameters eth eae peerice
SF pe dog ere aca eh | 6 Used te inline object with specific vals
‘Java. provides a default constructor | —Eonapl
automatically i a
Winns ji wth df vl ness |
erate on ‘ee
class Student { ) |
Seis iaaey | Student(String name, int age) { |
int ages [Link] = nome;
Pa pregemyrees: up Ae
Student) { } | |
® Keyword: this | © Keyword: static
© this is 0 rofrece viable that refers te the © table mambera belong to the Clas, ok to ony opt
carve sjed. | 5 Cam be ecreted wing dats name
© sad be differentiate. nchnce verbs. from © Shared omong al ejects
teal wari
class Student { )
‘Sting neon |
int ages
Student (String name) {
(eens! ~ nae
counter 1 saa for ok ject
Student (String name, int age) {
‘[Link] = name; // refers te istnce vari
this-age = age; // rafers to instance vari
FE
)
© Keyword: final | Pe Quick Comparison
fia vt ene arg z
eee | ee
] | [static [Ce tt Case Only once
final vid show) ( Clark / Rasch | Doped ie
Final | cig rte | wate
Psyc oa peta Tae math cant be overdden
(dy Best Practices
| =e thin te evold anbigity btnean vale
| & Use stat fr sed dt and lity mathode
J JVM fro ie fae, {2 Use Fa ode scour oe
| Quality Insights, Beller Careers!@ wi
Encapsulation & Inheritance in Java
@® Encapsulation ® Getters & Setters | @ Inheritance
& ‘Ennpialetion iy Ue binting off te atts) | ©. Und to access ol plots print fll. | © Interitirwe. is the. omdhenitos where
eo ths that pratt dc —|—0) Galt etree 9 ain cna late aspires Charl) the
into 0 sgl eit, (cla). © Sater validates and ats the valu properi and behaviors of eother
Tk rice diet ccs to some of on dla
Sai myn a Sie
proacting the data
sights 44
Tk promotes code rentablity ond
class Employee ( establishes IS~A relationship
private String name;
|
| publ String getName) {
| return na
)
pbc weil stone (Sting name) {
hie mame nae
|
TF dass B iherts fron cass A, |
then BIS-A A |
Example: Dog IS-A Animal
® Types of Inheritance © super Keyword
# super is a reference variable that refers
(0 Ns inmalaln para dae obec
Matont [A (GrenParrt © Used te ccoess parent clast members
|
+ Sige Inher = One did hts
from ove parent
1 (fils, methods, contractors)
4 Malilevl Tahritanca ~ Child iar B (heed a =
from pret, and antl hd ihre (case sain
from tht et Sing type = Amal
‘nimal() { Sytem. print "Anal Cnetractor"); }
lens De entande Ania (
Sting type = “Digs
DeyO) ¢
)
]
+ Harari Inbitanc ~ Mai didn |
|
a poe ||
|
caieilanaiaind | (Beem) (erm
© Multiple Tabrdanee ~ One child inherits | utile
From maligle parents, (Net suparied in|
Save wth case, sgprtd with Tterfaces) | aca
System. out pinta ("Dog Canetractor");
eid shan) (
Sytem. ont print [Link] 17 scenes parent ald
super can be red te
eens pare dass fields: sper fildNare
Access pare class methods: [Link]()
Call parent clas contacter: super();
LY Best Practices
Dedare fis private and pode public accte methods
7 Use meaningful names for classes and mathods. |
Use sapar() in eld contractir to inline park part
1 Prfer Tnerfaces over Malte Tnbwtance with cles
@ qa_insights | Quality Insights, Better Careers!
Y Encapalation protects dita. wing priate + gulera/stirs
1 Tnheritance modals real-world hararchy using ISA,
Y Choate composition evar deep inheritance shen possible@ qo_insights 410)
Polymorphism & Abstraction in Java
@® Polymorphism a
Ryerss Teg free” —|-|
dow ajc of fen danas | |
| na-nbarface,
| lige implantes
-
te be treated as objects of & common
superclass.
—_ ( Different classes, sane behavior (draw()) )
© Achieved using Mathed Overloading
(compile-time) and. Method. Overiding
(runtime)
® Compile-time Polymorphism
© Achieved using Method Overloading
© Same method name, different. parameters.
@® Runtime Polymorphism
© Achaea sing Mathod. Overvding.
© Sune palhed none ord. sgncbre x pore
© Resolved by the compiler at compile time. and child class
eae © Resoled by JVM at runtime (dynamic dispatch)
a — | Example:
[clase Coleulator {
| ink addCint int b) { return a + bi
| int addint a, int ink c) { return arbres}
| Aouble add(double a, double b) { return a + 4
}
(class Avimal { ied
void sound() { [Link](*Animal. sound"); }
)
Alate_ Dog tend _Aial!
| eorerrise
|, Neid"Sound() { System. cut. printin("Bark"); )
|
|
}
imal a mew Deg): // Parent reference
W Bark. (runtime
@® Abstract Class
;
Je nade |
om J
© Method Overriding
Sytem. outprintln(Drawable interface");
Gok veh leg andl eaoues are © Contains nly abtract mathods (before Java 8)
2 Comet be eantied From Jove 6, can hav defull ond sae methods
+ aed te provide « common base and part TORS gry ieteacta® mihasue oharSaaas of ips
implantation iz
Example: | oamee
(Gabetrat sie Spe | (terface Dromable
[ON clcet doable artaQ; 17 abinat wend | || void draw Ms mathe
| adapt)" ¢ 11 tema cated | | | daft wad info() (_1/ dafunaad (Soe 84)
| |
|
u
\
LE Quick : Compaaak
© ld cas pridas spcisinglamenain of parent | -
‘diss eabeds a *e | [ Fectare [Compilectine Plynorphism [Runtime Pelynorphian
a re er a | |e cates ‘Static Palymorphiam Dypania Myarphion
@ Access levl canna be more resect | [paired By [Hehe Orrteding athed Ovriding
| | ining Tue | __ Compe Tine Tantine
nn prota Pernt"): || [Pethod Str] Different =
| satands Park ( | [Terns Wat Ragired Required
[SRL Csptan etter,» || [Bene ela, id) teand() Parent & Ohl
PY Best Practices
© Use absvecin te hide plementation and. show behavior.
Progam te inarfuca, nk to plantain |
+ Use @Override sonelation aluays for method owrriing,
Juality Insights, Better Careers!@ qa—insights 413
Exception Handling in Java
@® What is Exception? | ® Exception Hierarchy
Test aati G laa encnted een |
event that disrupts the normal flow of
program:
|S ty
ie ae
eeeroene at
[2 Hake etre
Unchecked Exception
Checked at compile time, Occurs ab runtime
Mast be handled or Not chucked ab comple
declared time. (RurkimeException)
© try - catch - finally | ® throw Keyword | © throws Keyword
R ches cae tsp eae + Used to expt throw an | Used in method sigature to
catch : Handles the exception. exception | declare eceptin
finally: Always enactes (opiznal). | © You can throw any Object that | + IE stifle the respoiiity
ae | in subelans of Thre | be the aller
[ty € |
| ik ea 10705 7 ty ote | | Enample: —
| Y catch CarithmatcEnception «) { | | (public void readFile() throws }
| [Link] "Canna divide by | ‘f (age < 18) € TOEscepion { |
| 3 feats € | ‘ema nou HagengumentEavpton FueReader fr = new FileReader |
| Solano pita Falak ae a} | | CA mat be 1B or abe) Cpiasa’) |
| Nea it .
QV u 2)
© Custom Exception | © Common Exceptions
he ase ea | Een Description Type
an || etna Tes ty ae, tll whens [tad
(Gans Tligaplon ettends Eocptin €) | | NultPointerException ‘Aecasting matheds on mul object Unchecked
ra ents (| | atl eniEmpn | Toa nan org aed
mu | | Cnnteentteim | Ton mere of Sag Wave | teed
feo | | rtp red opts | Cea
GlantFoestEseplin Clas eck fund a edi Checked
Interview Tip (ee Best Practices
)
: |
|| 7 eer igen scp
© amg prof space ations ome gunna | ‘pore oe
Shae re ree meron ome rat |S Lag mang rer mg
| © De nat catch Exception unlece neces
1+ Use finaly to ralase ratources (DB, fle, streams) ime ene =
|
|
|
|
| enc J
@ qa_insights | Quality Insights, Better Careers!
to@ qa_insights 44
Packages & Access Modifiers in Java
© Packages ® Creating & Using Packages | @ import. Statement
© Used to use classes from other
padloge.
© A Package is « nomespace that
organizes related classes and
interfaces,
© Helps in aveiding naming conficke
and improves code maintainability,
# Built-in packages: java. lang,
[Link], [Link], ate,
(w Benefits |
Y Aovide name conflicts |
Balter organization |
Easier cole malntonance |
V Access control |
Ey
DB com
“De
package [Link]. insights;
Tnporing « Class
208 from [Link] package
|
|
|
|
i
|
|
|
|
| are imported automatically
@ Access Modifiers
Subelasses
Modifier Within Class Within Package (onieeeion) Outside Package Best For
public Yes Yes Yes Yer Maximum cccesibiiby
private Yes No No No Data hiding
protected ve Yes Yes No Inheritance
saree fes fes lo lo ye level access
(0 modifier) M us es £ fotig
© Examples 2 \® Access in Different Scenarios
17 Pibie ~ aczebla onrgture | ‘Scenario public | protected | default | private
ec | 1 ky mts 1] Y same case 7 7 7 z
| 11 Pia = ec ly hin da | dss Pra |} [sone Putas |v vite x
| dae Prints { | pete widow’) || Fo
[pinta tent = 10; | 1| [oan v v x x
}) | |
| 11 Dj - se ayn pee | POs Package
l [istecargones| leet |v | = | «|
Best Practices
Organize related classes into meaningful packages
1 Uso cloar package names (e.g., [Link]. modula)
id wildeard imports (*), use specific imports
Quality Insights, Better Careers
© Always prefer least privilege acces.
© Use private for fialds and provide gottere/etars
NS ey
|@ qa—insights
45
Java. Complete Notes - Quick Revision ra: 1)
® Complete Mind Map
+ Fle 70
+ 308C
+ Aatatons|
+ Reflection
4 Tnmatable Classes
+ Design Patterns
® Top Interview Questions
LW i Torn ond he dae wh?
2. What ie SVM? Explain ie component
3. Difference blanen JDK, JRE and JVM?
4 What isthe affrnce bebe == and equals)?
5. Explain OOP eanept with exangle,
6 hal polgrphion? Typ?
7. Difference bhucen abstract cast and interface?
8. What i thease of slate bayuord?
9. What & exept handling? Explain flow
10, Difrens balan throw ond ren?
UL What ae wrappers? Why are they wed?
12, What i String pol in Jan?
3B. What is cllactons framework?
14, What is mallrentng? He to cree a Uread?
15, What ie eycrointion? Why ie ib nmaded?
3 Quick Revision Tipe
ie een
Pee ig pis ply
Sino 2 al
Dal ml pj sgh ng
ial a
and many more!
E
|
|
|
@ qa_insights
® Best Practices
+ Tova Features
+ 30K, JRE, JVM
+ Packages & import
+ public, priate
+ protected, default
oe
Fellow naming conventions
Use meaningfl variable
snd mathed, names
Prefer immutability
Use final wherever pos
Handle excopions propery,
don't ignore them
Follow SOLID principles
Write clean, modular and
reusable code
Avoid code duplication
Use appropriate data
shrachares
Comment enly where necessary,
v
v
v
v
v
v
v
v
v
v
WE Remember
1 Code nore, Thi oe
8 Undedand cmc dei ju
# Consiatnay is the hy te mastery
1 Make your oun short nats,
G
is
= Clases Objects
+ Constructors
+ Encapsulation
«+ Inheritance
+ Palymorphism
+ Abntraction
+ Keguords
+ Data Types
+ Nariables
+ Operators
+ Contra Statements
+ Aare
+ ley, catch, finally
+ throw, throws
+ Exception Hierarchy
+ Custom Exception
® Common Mistakes SQ
x
x
x
7 What's Coming in Part 2?
egensone
Stay tuned! 97
Forging to close resources
(Fle, DB conactions)
Catching Exception without
specific handling.
Using null without checks
(WullPeinterException)
Net allowing access modifiers
cenretly,
Mg te df
Net everiding equls() and
hashCode() agether
Creaking abjects iste lope
enneceeily,
Callao Dap Divs
Sreane & Fact Intrfces
Design Pater
SDRC Database Comactinty
V0 & NID
Tater QRA (Advanced Lee)
alone Prajett Tdsee
Chaat Shets A Ouick Nate
Quality Insights, Better Carvers!
iy Insigl@r
INSIGHTS
—— QUALITY INSIGHTS, BETTER TESTING! ——
~ FOLLOW.
& COMMENT
>
2
=
~
ommms « @qa_insights y cated
TESTING INSIGHTS | TOOLS | TUTORIALS | CAREERTIPS | RESOURCES