0 ratings 0% found this document useful (0 votes) 11 views 34 pages OOPS Though Java Unit-1 Question & Answers
The document discusses the history and features of the Java programming language, including its development by James Gosling and others in the mid-1990s. It highlights key concepts such as encapsulation, object-oriented programming, and Java's portability, robustness, and multithreading capabilities. Additionally, it compares compilers and interpreters, explaining how Java manages memory and handles exceptions.
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
Carousel Previous Carousel Next
Save OOPS Though Java Unit-1 Question & Answers For Later vO Llhat {Ss History of Jove 2
Bovt hyo wos developed toy James Gesling., tke Sheridan aud
Patio, Nowgiiton during 124s ot Goo Mievy Gycterns The,
F Pedy, Te wear called “Greectalk’ by Torres Gostng . oud
lotey 4 wos called Ook , abreresarde WE was xenamed
ax “Gavall
Many vtercionn of Tava ove ovotlalole, thay are.
IDA Alpha aud Beta (5)
SIDK LO ( Fan 1896)
ZIDK Vi C feb (994)
G TLSE 2 ( Dec 1978)
©. JASE b> CMay 2000)
BD bq ( Feb 2002
APSE SO (Sep 2004)
@-daua SE G (Dec 20067)
Tora SEF ( Jat 201°)
lo.doan SES (Max 2014)
(1. Tava SEF (Sep rot
LEGG. ISeenTO (Max 2018)
13, Tova SEN (Sep 2018)
Ilys Tova se (> (Mas 2004)
ts. Tova SE 1S (Sep 2017
16, Java SE 14 (Mor 2026)
14. Javase (S (Sep 2626)
lS Sowa SE 16 (Mor 2021)
Iadova se 11 (Cp 20>!)
2 Tova CE 1S (Max 2023)
Fron Janase §- onvoascly Oracle Corporation { faring
Care ef ik|
| Define Encapsulation? i
Anse Encapsulation fe dehined On the vovapping, UP ef data under a
Gingte usik- Te ts +e mechanism “Har binds segewer
code. ard data « rrantpulates -
% “the variable: of dala qa class ts hidden fom any
cher claw and can be accessed only througt oon
member function A i crn Claw tO Lebich we
declared .
ae Thee tg done by making member OF methods ef a
Clay “private.”
“e TEU combination ‘dala bicling and alostraction?
Clay Area
5.
int lengthy;
‘int breadth,
Drea Link terath, 1 ‘oreacth)
a
this. Lent = lonatr,
denis. Beeadtto = breadtly,
x
putic votd getAnent y
fie
tat n> benath + oread th,
Syctern. out: printin ("Aveo ” +),
4
ofclags Exon ple. 5
L
pubic gratic void main (srang ogg)
1.
Aven xecrongle = new Boren (2016),
srecrangle. ger treat y
y
Outputs=
Ayea: 3h:
lc Ex plain feoturez OF object oriented programming language.
Aps-|| Features_of Jovor-
6. Olek Oriented
1 Simple
rSeeurre A Multithreaded
3, Portode @. Axchitectural- Neutvat
9, Kien: Pecfoxmmence.
4G. Drrerpreted
Ib. Dictnouted awd 1. Dynoncic,
i]
|
|
|
| &- Robust
Lolth tg direct descendent
| Sivnple:- Tonia ie velated to CH,
nevited From these
| eke ,Muely of Chavackes of Jawa ts
|) tase lawpages:
|
| = From c, ‘jena deves ‘tks Syke
|| Ae Mony of Java's object ovtented Rearuves where
i influenced by CH
|| Jon wor devigned +o be €
| quad ute ebtectively. ay fox Yue proqrorrenes
4o learwSeeuves- Every anna. that Yoo dountead a normal procvam®
HICKLNG, sity urcal “fection - Prior +o joa, roost users
Atdnt doronload ereatalle Proqvans Frequuentty ound
rose Aik ALanned than for rixuses priot tO exes tore
-¥ To addition to Uéruses, ONothes type oy malicious
Prvopans exists thak tmousk be auateded again -
% tte type ck Program can qatthes toformation cleout
turer private Information, Acich a4 bank account detaile,
| credit | debit Card deroile and pauworck by cearching
the contents oF Your computers (cual Pile syctem ,
¥ Bvo totywduca, a wowpe tated “-fixeusall” between
| a networked appicattan aud \ous compuler
| ® when you use jevo- cermparibitity wee bruutser, YOu
fom Lalgly dounload jaro capplets usitheut fears ef
| Nival infection ox malictous IMrer:
Portablei- Many types e- computes ouch opeesting seycterny
are Wm We “rrrouqrout tho world and wHANy Ore connected
| Ap internet
—k Foy ‘tlhe programs 4p be dynomt
coully devsnloaded to all
Narious types of platforms connected tn the internet»
Acme mean, ef aeneraking porratle esewtable code
te needed:
Objecde Ovtentedi- Java Manages ty 4hike a balance
“
|) (erueen tine purich’s Erxewything tT 09 obigck"” parodia
and are proamatic, “ Groepou of my wa! smedele* the Object anedel to jove uw Sinope oud easy to Ce
enttend. while sienple types Such as integers owe Keo
Os align Retormenta NOn- objects
Tora ts a Object Oreented Programming Noupaas3
‘dk helps to brea tie complet cote tne easy to understand
objects and MHANAAE Kao cornple nity progam iw Atak buted
ears environment = .
rkex preted: fox omns programming language Wee tense,
ether ie could be O earnpiled ona or Te CO” ae
Interpreted lonopacye , the difference ts teat.
Torecpreter_& Coropiles
1. A cornpiler ts trandaxoy wich conver Program ty
AQure tanqyuoge (high-level Langage) foto Obdjeck
language [maciiine langeage’) ap Coricask wilh —
an wwrerpreley 1s a program eotticld iwirates ececuitony
the proqrarn corttten 1 source lanquag
2 Another difference pekween estnpiler and “wterpretes
ts Xho compiler asnverts tne anole prograrn in ome 4
on he otter hand Antec preter torent the POQTAND
by taking, O single lero of a tome.
Cornptles candh Toner preter ave the taper of
locquaoe erandlater, whicn TS eofiwave hich translate
Ane programs fear & SOUXCR Lanquage that ave 19
human reacalole for Wto 29 equivalent proqram
tw oO» objec languagePre
Procew . Precewing, 6
Cocke J
Compiles
Hes
Source | Pre ]Tntermediate ber
=
code JPriy| Code
Thterpreter
Comparision Compiler Torerpreter.
be Typ Te toKes entire Tk takes a cingle
| Proarar ok ne efcode GO
el Anstructton at a Hine.
Sutpa- De generates Be doesn't produce.
| Amterrme dicta intermediate Objece
Oojeck cacte code.
llevking Compilation done Compilation and
} Mecnanicmn befpre. execution erection take,
| place Kmultaneoutly,
abe et eKeutt Comnparntt
| erection Seaton Easiex Company hel
1 Patoiuiw
| Pevkotwinns, 0, Cr+ PUP, Pel, Python,
Progyranomny uses uses interpreter.
Compiler -
Lamepiagesthat anpdtted part ef thetr code tc cttll wang. a
> Fora virtually elimenates these problem, by managers |
Allocating and deallocation., Ty Java, deallouatn ¢%
atomatic becawure ‘tk Wes Qantbacy. colletttorn for
Unwed object.
| 7 Exceptional condition, hen arise po stuattowy Such
%. divide by aero or Ale Net Found- Tava help vo
“hts ore tay providing Exepttenel bonding,
7% Ta, Prigram call sun Roe errs, cam and Alrouldl
: be managed by pram.
I Muttitthreaded :- Java war destqued to mack tua swal-coorld
| environment of oreating *evactve, RetWwOTKed proqyarnd
[#00 supports multttimeaded prgramrntag » ihich alles yew
4p wwile programs do rnany Auinge Simul pancoucly
% Javalk eayy 40 approach -o Tout tthreadiaay allous (Youro
ABINK about pectic behaviour EF program,
t a a A
j “echt heckuva Neutrali- Wwe rain problem face sy prqom,
| So that 90 Quenantee erists Ahhac even Pru rite pecan
Aaday, AE Will sun tomornnte, even onthe Lowe machine ,
because operating syctern upgrades aud, changing in core,
Sytem seCOUNEEL Gory all eambiwe fo make programy
Malfuinckorn .
Jove, deeiqne re made a deckdtan wr te java
Lamguage and made Jove virtual machine -to alter ‘es
Aikuotion ond ttety opal t to meet a feature wlleg
|
|
|
|Tava enatle that tre Oukpur of jova program U4
Hothing at 39 Antermediate veprescentation coed java.
bytewde. and tie Com toe Interpreted om ANY SyRkenn tae
| provider jovo Aertua) TNachiwe Gum).
me Tura Ic ao inkerpreter fox bytecede.
| % JIT Lyuck to Time) Compiler ts pare A tha Jum, tk
complles ‘bytecode, ante executable code tH Seal time
ona prew by piece:
+% JVM needc to be ienplemented -for any SUystenn ty
| Suecesc full Kon TON. :
| ful erect! of eo Programs.
Robust: Java veshicty you tp a foo Key oreor, to force
Youto Rind your roictakes €ovly tn proqaro development
—# Tava 1 oO Arfetly Typed lanquage, te checies tue vode
th tompile tine, however it algo cheass ONY vode at
Suuntime.
—* Tova & stobuck , consider tum main reason, fox Pregreim
Aotluve memory management misrare, £ mishandled
excoptional eoncdibtorn . Lounttme exrorc),
—* Mernory tnamnigement com be cAifHeulk tesla th
Aradttional programming environments: for example ,
W ClCH, the proqronnmer must mannually alienate
4 Free al dyramtc nero.
| Rts comeing, lead to probleru became proyramnmey
ill etox focggt +n Free rmemory that far been
| Prioviovaly allcked ov wore try to free come memeryytate once sun onyechore, anytorue hrevey”? 6
Heeb Rerfoeenenco:— Whoo Jono prograrns are enecuted| ,
AN does not Interpret entive code ink machinve Anchudey,
/ TE Any attempta ko do tuic Keen Kore oll huge performar,
Tonpack for We Nigh cornpledty Progra:
| Deshdbutedi- Java ts deciqned fox tuo dichAiouled enveronmut
| of iua Intent, becawe tk handle, TePLTP pretocols.,
Acedia O Seaxcures Ux A URL fs much diferent Fron
Onceeeeng afte:
|
36 Tova, hay o featune called Remote Method Tnwocatcon cami)
Ke, method ef anotwoy
I wong vate a program (om fon
i Progam acrogg Aue Newel and gp the cutput.
Dynamic: Tava programe acceu Various Stunkine Silbrate,
oud ‘formation tide tue compiled ecde ray tecoded. Tris
dynamic feature. alleus you to updote the piece, of
| ltbyavser uoithout effecting the code wxeong ww
‘|| Dakine Polyrnor pinisrn?
oy Poymorpitam & derived Fran 2 greek ook: poly amd
| Tooxphs, “tLe word" poly” mean mang ard “morphs” means
{
forvns. So Polymorphic means many -formy ,
|] # Te ta emepe by which “Engle attion equ be dens to
) Mifewene usage?*& Ply Morphicmn te adhieved fp tun type, _ ®
\. Compile: te Poly tnorphi cry (Method Overloads
A Quntine Poluyroox phism, (Method Overiding)
Desabioe Acope aud [hfe tere a a Varvable7
“ava allows vorsalsle to be declared usithin any block , ik
begins with ts open curly bom aud will end by coke
curly brace. “trut block debiner “supe”
| * Sicpe won toe nected , for erample ech tims You ureoke a
| bouk ef code, you are creaking a wero vested Scope.
| The objec Getloved wrthin tha *MMerccope UAll not be.
| vigithe to outside te
but howo tong avaralke exist befpre.
1g)
|
|
| 7 Nifetime (6 notuing
i ‘iK destroyed.
| Class denno
x pulstic Arokte Vo main Shing argtia)
Uk E10, I] +L visthle to all code iM main
(4 ==)
ba 11 Sroxts new Ape.
int Yar0;
Syctem. out-pantia (Hay ore "4 © +)
¥
IP MENARD, I Fe uktl Mok execute hemee
Sugcenn out pantin ("1K %6" 45Exploin, bef ty alcout Shing Clay and diserus Vordoey poetiecl
in Asin, clats with, example:
Shing TW fequenwe of chovackers. But oie ee
Oejeck that Teprecentt a sequen of chavackers. “he
Java: lang. Sting clay ts tued to creda a Shing elojeck-
\ By shing \kera)
2 By neo Keyword:
hang, Wtevall ewer Shin9, breval te created by Usierg, double
quote For Example..
« weleome”,
Hf tha ASN vortalsle already enise ‘un heap memory, te
ak wall oreatte WELD one.
Shing Ae
| pal Sretuxn that vorialale, Otlorucrses
i
Bu “
New Keyword:~ _p ‘ ‘ "|
Keywordi- im will create aring, obj ech nso keyicd
au.
Sting A> now Shing (“ Welesmre”))
public clax Sting example
i
partic Ayotic Nad matin (Shing argatdy
L Y
Sroeq &-" fava”,
Aba chief,
Sting Ar>
Spang A= NAO Shing t" you");
neo Shing ("Welesmed!);Seprenn- put: psnttn (A);
yeeros out: psorta (4S);
Syctem out: potty (4%)5
laya: gq: Sheng claws provider Many Weful method 49
Perini operations on Sequence é- croxacter Valuer.
0: Method Deception.
Te suture choy valu tov
ehay chaeAk (int tndey)
tho particular Index.
int length 6 At suturing length ef the
Ating,
Shing Aatostong lint Yagicinded) Tt oetumny Cabshing
fox Aen been uundet
Stang Aulasringlint beglidter, ink endinde’)
Te satu. cilosring for given
begin der and end inder.
» Woolean Contains (ChaxSequance Ss) TE Seturng fue OF
fore aller crakching tle
Sequect ef Chat valuc.i
i
3
i
|
|
it
i
{|
i
lo. ic Shs T sl
(0 Ata Sheng equalsgrove Case Shing another)
* Shing -bien O
Mets. Deceiptin ©
G
boolean equals object ancthe’) TX checks equality
ef tun aren totth Lo Gren
Oojeck
bedleon ‘cEmptyry Te cheers tf ching (6 Lemp
Sring eoncat (shang are) Te Concakenaler the specitred|
Aring.
Sting suplaca(enen eld choy Wem’) Te seeptaces atl
Oceurvencey Of eperified chert Value,
|
" De wsrmpares anothe( ating
De deecn't check cous.
INE tinder OF (int c's) Tr aetumns we specified cha.
Nlalua sadom .
«Shing trhowerGery TE seturng tue cong 8
lowercare.
"Shing AoUpper Carers TE Steterns tw ring ho
Upper Coe
Tr sumoves Beaang aul ending
SEMCEK OF “tele AS
Shs Cone
SSNQTy apt (Shing ges) — BE swrumy a shit Ahing
matching, Seger.i
3a. | Define type Casting? 6
Type Costing ( When You awiep a Value ef one primitime
datatype to another type .
en
When one type ef data tc asdgned te anole type ob a
Vortaldle an automatic type convercion will fake place. Af
fattowsine tw conditions are rnet
\s tun types rude be Loon pattilole,
a. dectnation tupe loxqer than courte type -
ilablle
Bb) Discuse the Affferent levels af accesses protection aves
w jor will exoraple.
Ange the acceu modifer GY accen cpectfiers “in joven specifies
| “he Kcope a Vorsalsle ; metred, Cencrructoy , oud Clow -
i These are Rout types ef java accey modifters.
1b Pavate: cen level ef prvate roodife, te only wn
Ake dat, Te ovrnct be acceved einen ourcide Clary
ies Pubblicr= Aceon level ef Puldic mmodiver Is ewewywhere. Te
1 Caw be accenec| From within clay, oubtide clay, witisin the
I i. Pate Ft-eons be octered within the pockage , Cubicle
| “the "package “trang unit clas
[4 Defaut: ~De ts only for usttitin tha package . Tr con not be.
accened from ouivide-tre package. Hf we dont spect fy
AM fhe ¢ atcove( Pavate , Palolic. Rocked) Key wakes , eb
if
i
i!ae WWite obouk Conditional Aratement. ®
Control Poo Aratemente are Used ty provicle tue Lovo ee
Crerrtion wit condition.
Lv these Aratemenk are diMded Wty “three cakagenes,
% Selection | Decigion rating: Avatementy
i leopine | Trevakve Aratementt
a Branching | Tamp Stoternentty
Decisiory Mating Grotementirthe Flom of exeurtien Te bared}
| OD condition, -Peodded by one of the following
fig
i
| a Saikety
| H- stakemewt:—
Keyvoord weds %F
{Ran enpretdon 1s hue, “then only the srakemerty witht y
ie Weck com be €recutect -
i Sole 44 Cenpresvion | tet Gmatitten’)
i L
| Srakernentte 5
|
:
boy
|
|
|
i
i&e-— claw Exarnple ®
L
puldtc Aratie: Wed main( Shivg ages)
AN N=ld5
§£ (o ro)
oa a
Sygter-dut-paatte (* Number ti powative’);
i
|
ob. Nuumloes 1s pessitinte
ite welse: Koyo, ured io if, ele
[et Aue tondiion te hue, Sratementt dif block ton he,
ervecuted, oluxuice, ele lalocg ull fakes place.
“Syntes: - Be Cexprewion)
Ul code.
& i
a
i ER Clan Example)
| z
i pulotic. Arakic veil main(cring amit)
L
| ‘nt N25,(70) @
i
Sixrers. out prantln(" Number 6 Possitive”) ,
x
alse
g
Suter: cut: Pantin (" Number 1s not Poseitre”))
| }
§
1
Quip Numioer tC Reatvnes
[Nested af akatement:— Kajoords tied Uf ele
7 It provide, av alkernative Pally ef execution When an
“EE” cla “€ evaluates to falre.
+ WE tory have Chain o tf-ele Avatementt-
Snap (expre ios)
L
|
|
|
|
i
Araternent'',
4
ele tf (expe wien)
L
Arekemeut 25
Fatement 35,
4 >Holey Mute ®@
e pulotic. Aratic veld roan (sting args LY)
| L
| we nets
| tf (n
2
|
|
|
|
|
|
|
|
|
Setern.out pratt (* Got Trkeger data’);
5
cid Aisplay (Shing a)
- "
Syptern- out println (* Got Shing data’)
}
putic Axatic. ie oo) (Grang orga)
s
display (1); Output
aA ‘ | iy to") Got Toteer data
% =e Got Shing dala .
a
ag ie atl ty ola- bile o program to find “he exe efa Given mabin. é)
‘enpost java. uttl Scanner,
pullic ‘cla’ davaMlahix Dnvere.
L
public cratic Noid mnaiy(Sting oreqet)
a:
“wnt by,
Ptoat det, ternpy
Float mattis new fleath1h1,
Scanner Ac= new Scanner(Syctem- in)
Sugtern. out: POH Enter elemenk ee mahi 100 we);
For (i205 (425440)
a
oi(j05 05444)
moat {iItyI= Ae nertfloatOy
5
det = (mat (oltol enat (IT) — Cenat CONV mat (ited)
Sustern - out prantia (“derex minent” det);
termp ~ eno (OV (8),
mMOkBIL0} = mat LIUY ,,
mat (abe) = temp,
mato Or} moto ll,
mat (J Co} = - rat G9 Co}, /
Suatern~ out patio (“Onvene. of @ rahi ®),=tb!
for (i205 e2y44t)
L ;
fox (j-0)$ 2299)
ia Seysrer: out paotln( (rat Ci Cae) aoa
4
aq
y
s
OQuipubs—
air deeeh oe
“i
2k
determinant = (00
Tnverse ok mati 6 +
eg jock
~O2rv o4.
Explain poramete: passing mechanism io ‘ova .
os MOLE cormanky Uued MMedhawrigens ave .
|. paw by Value
2. pews by Tekerence.
Pass by value. % a rmechanien for a roetned cole oy
Paring avoluz. , ike not effected by ovegnal Vole.
AD paw by seferente, objet U paced G4 ON anqumunt ,
TE we rade chor Anthe porameters ‘Insane mmemler
Re would eftetk ovaqinal value, ;pulotic ctax demo @
e
‘int aztogilata=50,
void Changefint a)
2
A> A4100)
i
voc aisplay (desno A)
e
d- datas ddata 10d)
4
pulsic Arak vord mein (Shey args)
L
dernod d= new demor;
Sextem- ous pantin[ before changing ee 4 Si,
d. change (seo);
Saastern. out: pontln (“abter chanaring, aiwa4d: a)s,
Syserm out prointhn(# ies change scree sacha
A dsplay (a),
Suyctero- out» prontin (" Phen Change dala is'+ d- dake);What ie an ova? Wile a pwqrans “thar oreate ont
inikialtges a -four ‘WWleger- elemenk amay. Find the cum
and overage & th value.
TAn orca. is acellection of similar type d-elerments
tokich hos eonttquour memory locstton ,
ar Reta io Java f¢ inder-bared , the fick element of
the array 4S Ktoved at 0% “der, 24 element 4s Stored
on &F irder and 40 on.
public claw Progran
L
Puldic Atatte void mnain(stong ong)
L
Ant aL \> 210,20, ao.Qoy ,
ine Org=0, Aum =05,
for lint 0) Leorlengtty, iby
gunn = dum + atl,
4
ONQ = Suny la. lent,
Suctewn out: pantin( Sum = “turn )
Siem eu proto (™rerage«
4 mage ss avy),
2)
Output —
Suen = 100 ANrerage= Dis