0 ratings0% found this document useful (0 votes) 91 views114 pagesJava
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
Sibauoe do Bao
ae y
pa ese,
‘erorte-3mg
‘peng ‘sppms sade
uy suse Jo 382709 eye
“sonapg sanding Jorg BV
1S eons smndivoD) 95 W
318" HUqUIELN SI,
pa] ease
ep ese “tootty 2m dam sre)
sexy sao. 24g pom wpagy
202125 amd J vo Pee,
Las (@ou2}9§ winduoy) 9571
ANT WARY AeEg “TY
[ — 49}sdu19g = dayndurod) *99'9 "AL
0g
L- eave suis
* SulMUIVIZ01g p3UI119 yefqO
Jo Yoog 3x91 V.sil ot
BOOK NAME: Object Oriented Programming Using Java - I
ASBN: 978-93.90769.36-0
2 ee:
First Edition: 2022
Copyright © with Parijat Publication. All rights reserved. No part of tis publication
ed or. transmitted in any form or by any means,
1& or other electronic or mechanical methods,
ritten permission of the publisher, except in case of brief
bodied in reviews and certain other non-commercial uses permitted by
Published by:
Parijat Prakashan: 40, Budhwar Peth, Appa Balwant Chowk, Jogeshwari Lane,
Vishweshwar Society, Pune 411002
Printer: 8.S. Arts, S. No. 75, Yash Heights, Railkar Mula Pune- 41
Price: - 250
pose eos hs ee made o st he norman sity according to the new approved
Neer cr ha be
a,
Preface ...
We take this opportunity to present this book entitled as “Object
Oriented Programming using Java - 1" to the students of T.Y.BSe
Computer Science as per the revised syllabus, June 299) gid down by
‘Savitribai Phule Pune University. This book is a ‘comprehensive, hands-on
{guide to Java programming,
“The book covers concepts lke An Introduction tg Java, Objects and
Classes, Inheritance and Interface, Exception and File ‘Handling and User
Interface with AWT and Swing.
‘Numerous programs have been included to reinforce the basic
céinceps of java programming This book 50 useful forthe students of
B.Sc Computer Science of other University and Engingering,
This book would not be in your hands, Without the help of many
besides ourselves. We must express our sincere thanks t Mr, Omkar A.
Maral (Deshmukh) and Mr. Sanket Kalekar and the entire staff of
Parijaat Prakashan for their help and patience in putting up with our
schedules.
Although every care has been taken to check mistakes and
‘misprints, any errors, omission and suggestions ftom teachers and students
forthe improvement of this text shall be most welcome,
AUTHORSumvangindngynduyereq
‘ueangindmondaypaayng ‘wesngindmonnduyepy sueanginding-mduy |'yp
surwang pue sj.f 0} oloNpomm] yy
worrdsoxg pouyog sesp) SuneDID Fp
Poi An parson oor yoweD ajdninyy ‘suondeoxy SuryoweD z'p
‘wondaoxg paxseysuy) pure pexseyD ‘ssej9 wondasoxg ‘sions quem SUT Tp
‘Suypuey ong paw wopdeory
‘Seoujsoqu] [PUOYDUNY puE 9H Jo 1d20u0) gE
souyzoym Burs wistydsowsjod sumyumy /°¢
‘sooqpomuy Supuowajduyy pue Suruyaq 9'¢
Sporyoui 1osisqe pure sseyo ensqeJO9S/) 6°¢
sauna] ¢ paadeay
se pe poxrout 01 parejas ploakay pom Jo 257 ¥'€
wstydioursjod oumunu pue Supeyarg poyyy £°¢
promAay sadng Jo asn puv ssejoqng ‘ssejoradn,
‘souey oyu Jo sodA], pur (puomAey spuarxa) soiseg souensoyuy [°¢
aumo27 8 soups9}uy pus someyoM ay
sassui sodderyy 3°
saBoyoeg Susp pu Suyssoooy ‘Baywasy LZ
powpaty ()yewioy Auisn eep Suing SuMEWIO4 Sse. IS puy Sse) Buns ©
(Qssa9328 ‘apoosey user“ POHL S819 129190 +
sasseig pouyopad 97
eaadoy
‘Spowpom pare splay ones y90Iq apes ¢
PromAo4 .SiI, Jo 287] pu storonnsue Supeo}s2AQ ‘sJoINASHOD
sivalgg jo Keay ¢
(Ginegap ‘sreatad ‘poroaroad ‘on qnd) szaypioadg ssaooy z
sessy]9 umo an0k Buy |
‘s9sse19 pus 5930/90 candey,
(Gommeog ‘seperyperayng ‘smaumdzy aur] pueunno3) mnduy Sundoooy
Sey az ‘a1 Buei99q oF
1qeHA [OU 6
saumaoy ,
sodky weg g°
. swaunnoy yo sadky, 1°
s0peae denet ‘pf sjooy. mary g
sumdoug envy ajdung 5°
outomaug eaee |
‘anf Jo spiowzzng Yo sammie
eaey Jo orsty soy y
sidsouo2 SuyuuresBo1g pawatig 199f90 1°
aR 0} uoHoMpaNOT Ly
amet Taadey
I~ tase Bajsn SaqamreaBozg payuaig 399190 zap, asun0y,Parjat Prakashan
4.4.2 Readet-Writer: FileReadet/Writer, BufferedReader! Writer, InputStreamReader,
OurputStreamWeiter
Chapter User Interface with AWT and Swing
5.1 What is AWT? What is Swing? Difference between AWT and Swing
5.2 The MVC Architecture And Swing
5.3 Layouts And Layout Managers
5.4 Containers And Components - JFrame, JButton, JLabel, JText, JTextArea,
ICheckBox And JRadioButton, JList, JComboBox, Meni And related Classes
5.5 Dialogs (Message, Confirmatio ileChooser, JColotChooser
5.6 Event Handling: Event Sources, Listeners
5.7 Adapters And Anonymous Inner Class
(€8-355)
10 Lectures
Page 4.3
Contents
1 An Introduction to Java
11 Obs Orned Programming Concept
2 Objects and Classes
2.1 Defining your owm clas
sented Keyword) nd Types of Inheritance,
3.1: Inheritance Basics.
3.2.3 Super Keyword in Jav
3.3 Method Overriding and runtime polymorphi
3.4 Use of final keyword related to method and
3.5.2 Abstract class in Java.sse-s0
“oye quouued Bupjeu apuo Buse
ons sxo1Aeyoq pur a9 a1GoW‘SSaupPY “AUIEN “GT se aves ane THM 30KNg se Yons 199/90
2 sunt song ‘eo Burddoys se yons sioafgo sey warsAs Suiddoys aurquo we ‘aydurexa 10
“parshyd 10
vio 2q Kew veyp pom [eat 2tp Uy sBurtp 0} puodsaxioo syo9/qQ (apod) so1aeyoq pue (rep)
ns sey yoo/go uy “souruayur pus wstydiomxjod yy adfs eNep soeNsqe Ue S| 309/90 Uy
49990
‘eep 3 wo suoresado pouyop-[]om Jo 2s & pur BI su pumoge urEBoud v sedeuOU
suueoug pawan9 129190 “ep pue 2p0s:siouHo|9 Ons Jo sD swesBOxd sR TTY
-SuyummesBorg paruauig 1afgo Jo sidaouoo o4seq puesssopum 01 sreyodu
| pony oo{qo axe eany wt suresBoxd ry “enep Jo aseq aun st Suruunesorg payersg 100/90
sydaouo: Suymuresdorg payua}sO 39940 TT
‘aBendue] VAY Jo Bunyeazo oy spea] wawaumbar sy] “Couapuadap wuope(d
te Aunqeuod yo anssi ayp sey afenSue] +49 pue D woq ing ‘eSenduy] Sumuresfoud
ruauo yo0lgo Suypeay ap sem sBerSuey SuuesBod +49 ‘9661 JO UES em IY
‘soBendue] SumunuesBorg pawaiig 199/90 amp Jo aU st oI pawanuT sem +45 aBenBuey
umunuesBoud au © ‘Apxojduoo sip awoaran0 0 wexBoud > afeuews os ynouIp 812 ‘opoo
uy urea0 sayeat azis wresBoxd ax 20U0 “Aipxe|dwod Jo peqaexp w Sey 1! ng -oenBUE]
munweifoid pamonuns Suupea| arp sem aBeniiuey SuyunuesBorg “spg6r 30 wes om IY
‘SuyurmresB01g payuayszg 399/40 Jo pean,
aes 0} UoyoNponUT UY | aydeyD
——————
rerconsnpanuy ay waipeqeg whned Tear sust doo
“uonngompeur pry xo@y9949
wauodwog pay siourEuoD >
svoBeueyy 1n04e7| puy sinoer ¢°
Sung puy amsanyary 9,
'S PUP LAY Usenyeq oouzagyiC| ZBUINS 81 IU LANW SE PUAN I”
BOUMg pUE LAY WT auys0qU] 1asQ)
urangindinganduyere,
ET “weangindingandujapy : ueangindyc-induy |p"
ANS PUY SAI} 0} UoHINpoHy]
wondooxg pauyjoq esp Buea)
19019 An pawn “oo]g yoweD 2[dninyy ‘suondaoxy Buyyoe 7°
wondeox pexsoyoun puy payoe4y ‘ssej9 uondoox sioua pia Binfeac |
Sunpuey any pue uopdaaxg {
Epa [eUOKOUN R'E
deen Jo SumMYO [9°
coeparu] Hunuewaydwry pue Buruyoq 9°‘An Introduction to Java
OOP using Java-t
Parijat Prakashan
Abstraction
Jn refers to the act of representing essential features without including background
smans use abstraction to manage complexity. For example if we consider washing
well defined obje wn. unique purpose.
ibstraction allows
People do not think of it as a set of thousands of ind
people to use washing machine without thinkit the complexity of parts of
freely as a whole object.
‘washing machine and how it operates. Peoples
Abstractions of complex systems can also be applied to computer programs. Also we use
programming language readymade constructs like loops, keywords etc. without knowing there
background details.
Encapsulation
Encapsulation is the process of wrapping of data and code associated wi single unit.
‘Access to data is only allowed through well defined set of interfaces associated with it. So it
keeps data and code both safe from outside interference.
This insulation of data from direct access from outside the wrapper is called as Data Hiding. It
protects the data.
Inheritance
Inheritance provides the idea of reusability. If certain object need to be used repeatedly at
‘many places in application hem it is not nevessary to define its common characteristics at each
place. Instead the object need only define those characteristics that make it unique at that
place. Object can access these common characteristics which are previously defined. In this
‘way it eliminates repetition of code.
Polymerphism
SY |
5355 Page 12
OOP using Java-l Parijat Prakashan
Polymorphism means many forms. It provides the idea of “One Interface, Many Mett
ble to design a commor
terface to a group of related activi
specific method as it applies to each situation. You do not ni
ction manually,
For example, you may need three types of stacks in your program that operates on int
not needed to create
floating point and character data. Due’ to polymorphism
fferent stacks. Instead you can specify a general set of stack routine
names.
This helps to reduce complexity by allowing the common interface to be used to spe
general class of action.
1.2. A short history of Java
Around 1991 Patrick Naughton and James Gosling at Sun, wanted to develop a prograr
language for consumer devices like cable TV switchboxes. The language had to be
generate very tight code; platform independent and portable, This project was code~
“Green.” 7
To overgome portability issue Green project engineers used the concept of virtual me
Inventor of Pascal language Niklaus Wirth pioneered design of virtual machine.
‘The Sun people, however, come from a UNIX background, they made the Java lar
object oriented rather than procedure oriented. Gosting liked the look of an Oak tee th
right outside his window at Sun so decided to call his language “Oak”, Later the nar:
was renamed to Java as Oak was the name of an existing computer language.
Around 1994 the Intemet was growing bigger and bigger. In mid-1994, the lat
developers realized that they could build réal cool browser. So they made the b
ee
(5355 ?ee { &
we S099
LS
noms wasopied opqneduoo eaef Aue uo uns pue pardos aq weo (ally atexpouncya]
sxBoud enef-poytdtwog) ary apoo aiXg ‘suopeld few ye uo somnsaxo wrerBord eae
[81020 WI] apuadapuy mop EIA puE a1q8}304 “5
“Ayunoas yay paveas sonsst Yons |e ofpuEY 0} peUsIs9p st
sense, Suyedue pur yoene stra jo su Wty st oq Benue pamnqunsp 5 eet omg
aamaag‘y
“CNR woneoonuT pomay aowry Jo dey
‘ajqissod st 3] “spoypour oqo yoea fTeo ues em Jey axe yoN sumfoud Om], 3YOAIZH
surfosd ay) uaamioq uoneorumunuos ajouas seplaoid eAey Jo AMEE paNqUNSIG
Pamqunsia’¢
“envy urea 01 Ase9 29
1 Soqumuexfoud panuowso roefqo ypu ze}ruey axe nok sr romp, “AB seapo uy page 10
‘gue Jaye axe 4449 pu 2 sy sxdaouod Sutsnjuoo Auepy “asm pre wea 01 Asea st BAe.
{0 0u are yorys sad4 ep axnnuud suequ0o easy Ing sio{go Jo su uy SumypAsaK
tuo9 aBenZue] peruano woalgo Aying “aensuey SurumuresBord payuawo yoafgo Ayy st eae
pxaduoo oxy soonpat
8 JO Jaquima ojut wresBoud joy ayy aptAtp
suuesBoud partou0 129fgo yo une ae aH,
ov uonsnpanuy ay TWeuseeg Weed Treacy aursn dO
[e102 80
INT] 22mBN PaIUdHIO 199/40 “T
(or0z ‘L102 mdv Ws] Bate Jo spromzmng YO saanjeag ET
1zoz 4am 91a eacp
0207 s2quidag SI aS eany
0202 HOE Las wavy
6102 soquandas elas ener
6107 wre ZLAS tac
“8107 sequandag (SED 11 as ear
8107 HORE O1 aS ear
L107 22qua3dag 63S exer
$107 YORE (SLD 84s eer
H10z Aine Las eae
9002 49qut200q 9.38 acy
‘p00 oquioxdag osaszt
200 Arenaqed wiasze
0002 Aer eraser
8661 s2qu209q zi aszt
661 Arenagag rvar
9661 Krenwey o1xar
9X PUE MIUOW ASHI} woRDA
“osm 280K pu ynuowsuoysion ea ayy Jo uoNNjons om says 2]ge) BumoIfog
“KopoySonunuoo ye azes> ney
24 peurdsuy ABojonysay sma] 32,ddy sv wnowy Safed gam aprsut apoo Supnoaxa Jo ajqedeo
| "Geporuonmpency ay
Tesora weed
[eae duis g00,OOP using Java-L Parijat Prakashan ‘An Introduction to Java
modification. It allows “write once; run anywhere, anytime, forever.” approach. So Java is
platform independent language.
6. Multithreaded
Single Java program can execute many tasks or process at the same time, This is called
‘multithreaded programming
7. Robust
Java checks code at compile time as itis strongly type language. For example all variables
must be declared before they are used. Java also checks code at runtime,”
Run time errors and Memory management errors are major ‘program failure issués in
‘traditional programming. Java provides features like exception handling and garbage
collection to handle these kinds of issues.
8. High Performance
{As Java is portable, the byte code file can directly run on any other platform that has Java
Virtual Machine (JVM). The byte code file is easily translated into native machine code by
using just
time (JIT) compiler. JIT can examine code which executed repeatedly and
‘optimizes that code for faster execution. But other interpreted languages sffer from almost
‘undefeatable performance while this translation and execution, This way Jaya provides high
performance as compared to other programming languages.
9. Dynamic
Dynamic, nature of Java allows linking of classes and method at run time, It also allows
analyzing objects at runtime
1.4 Java Environment
C5355 Page 16
OOP using Java-1 Parjat Prakashan
An Introduction t
Wis the collection Java Class Library and tools used for development and execution
‘program.
Java Class Library (Application Programming Interface) contains thousands of built-in ¢
and methods grouped into Package. Packages plays same role as header files of C lang
‘As header files in C language contains built-in methods in same way Java Packages oo,
built-in Class and Methods. As in C language we can create user defined header file
‘methods in same way in Java we can create user defines packages, classes and methods
To use any built-in class or method we need to inchude that package in our progran
include packages import keyword is used.
Example:
import javaio.*;
import java.uti.*;
importjava.awt.;
import java.lang.*
Here java, i, util, awt af lang ae all built-in packages. The javaio indicates that o pac
is included in java package.
Above four import statements includes all clases defined in respective packages. To ing
only specific class we can use:
import java.lang Math;
‘Above statement indicates that class Math is included in lang package whic
‘included in java package. Here it only includes Math class and its methods,
———
5.355 =$5059
La Sis
_ypeur 02) apoo akg swans soda (|) aut, use ase su ‘pas st PuBUINGD
pf wresSoud eavr ainoaxa 0 sajaxdioyny eae Aq pamaxa aq o1 spaet ureBoud sit DN
wopeyaidsoyay (2
eas uy ssonotg vopepdmog mesdong F108
a Tamm
soe |§ aes
30 aug) dit avepausanut
dio jryssooons J0yy
ny
-sayaxdnm eae q wor nd9x9 30)
{51 sm, “ssepp'sum0aqou se 2yyj 209 214q v ateaID TIM
avfouogjam oeaels
‘pucusuoo Buuso0p Jaq pure [eUTENAL
ip uodo “21g 2p0o arkq or poranuoo st ayy eamos eaef eseyd sup Ul pasn st PUPUIOD
anf uesfoxd easr ajsdwoo’0j,saqydinoa wap Aq patidusoo oq 01 spoou wrexBoud si IY
{102390 Ws] wonenidaue3 (I
wopnooxa (2
worrsdiuog (1
‘5984S On UL SOHO
Supwolod
{
umeiSoad ener ‘wesfoxd axoge Jo uornoaxa pue woneydutoo jo uoneueydxe om St
{
Trenoy Bust G00
SApy of UoTaMponT Ey ‘uoyseyeig vee
*(2180y eA0¢ 1 auioqoy, ud no warses
}
(Qs Suns)ueu pros ones gad
}
aooyon ss
“S111 88 2p0o sup aqua og ‘aBenue aanisuas-aseo 5] BaBy“watf-owooZoM se
‘1y Sip 9avs pe oupa Aue wt apoo Sutmoyfoy ams4y “UresBoxd wavy 2fdunis SurmOTO} Zopfsu0)
“uojsuarxo wavf sey aurou wesfoud oy, tuesSoud ut ssejo pouout urew Jo 1%) se sures
94 ssn wreBoxd jo oureu aq “s25se[9 axoU 40 auo sureuoD exp ots 1xo1 Sf unEsBod eae Y
weidorg wave dung ¢°
eaefoureuweiford somataraiddeg
-sraiddy enor uns or pos sty | _somoqaraydde
aura as
“twesfoud pany aanaax9 oj pasn st yoru J0}a1dsquy Wael 81 eat
eaefoureuraresBoud aeaelg
‘uesZosd way oqydusoo oy posn st yon 19144409 eaey st seaef
"RAPE Ut pasn soo} ued xn 30 autos Smoys a{Gen BuYAOI|O oRDDXD
ue youndojanap weiSoad ut ajax yevoduy sAejd o5[8 GABP Sjo0) AzeNQr SSEIQ BARE OY]
‘aby oF vOnoNpoHU] Uy. Tepe ee TS| OOP using Java-l Parijat Prakashan An Introduction to Java |
| __ specific code in buffer ard executes the program line by line. Ente the following command in
terminal. Don’t give any extension to java program name while execution
Sjava welcome
After successful execution it will produce outpt as: Welcome to Java Magic
Interpretation
class }
Ourput
Figure 1.2 Program Interpretation Process in Java
Let us discuss above program in details. First line i
class weleome
defines a user defined
Hose name is welcome and indicates entire class with code and
data. The class name is simply ident
‘Next line contains opening curly brackets * which indicates beginning of class.
Next line
publ
id main(String s[])
indicates main) function ffom where every Java standalone program exécution begs. The
public is Keyword which is access specifier. It controls access level of class members. The
Static is the another Keyword which allows main() function to be called without creating
abject of the class. This is compulsory because Java interpreter calls main() method before
Aany objects are created. The void is keyword which indicates main() function does not retums
any value, The String s} inside round brackets indicates parameter to main() method. Here
S355
Page 1.10
An Introduction to i
aracters. The's' is parame
String is data type in Java which is used to store sequence of che
name which indicates array of strings.
ing of main) function.
‘ext line contains opening curly brackets '{' which indicates BEBINN Ns
Neat line
System out print("Welcome to Java Magic");
|} isthe output line, It prints following output:
‘Welcome to Java Magic
it-in object of System clas.“
Inthis statement System isthe builtin class, The ow oo — srophant
print() is built-in method of out object. This method is used . ee :
sever in round brackets in double quotation mark t0 be Pri i
Java, It causes what ee 7
= jcolon. All executable statements in Java program en
ends with semi
Next two lines contain closing curly brackets. One indicates end of main() function and
one indicates end of the clas.
16 Java Tools — jdb, javap, javadoc
1. jb [1M April 2018]
js a simple command-line debug
This tool ised find and i bes in vargas 6 SPE SN
for Java classes. It is déne after successful compilation fo 0
Syntax: jab (options) [classname] [arguments]
Where,
355eriatea : ses
a SS
ydutex9 105 5,
BRIS PrEAUOT PUL ysliaIse YPM spuD PUL ,/,, Se JoquIAS YSUAISE pu Yse]S pIBMUOT LA sues
134] au wexpazow sure yuotmOD uoys posh St] “uy 9u0 URN ax0UL 30 940 ued WED
JuourenoD auyDIOH (2
ouoysno Jo 2oueyeq P2qP 01 pasn st URN Sy //
‘durexo 3042 sures ap uo spua y se sysew pua
ust oso4,“9uH| atp Ye Spud pur ,//, Se YSEIS prEAUOY Om IPL SERS 3 ‘aUN] aH0 dtu sueds
Wommeno aur] a7Bung (1
wounw0 UoREWaUINOG (¢
ue au ITN (Z
sounio; aur) iS (1
-swueuney
9 sada samp are axa 2121 papoo uaqp ‘1 pepon o¥h 2¥H| 9poo Inoge UONEULOJU! NOH
2 soururafoud Joy rash s} yf siuowareNs ajgeinoaxa 104 azesqSuod se syuounOD =n
oust Ajdums s.dwio5 ‘opoo somos ynoge woreuosut soprnoad ey 1x0) uid st qUeKsWE>
syusumU0? Jo sad, LT
1m eael ooyar dueyenef Buoy eaef sopesel:apduTENG
sepio Aue ut soure
Seysed ‘suondo puounuos aoperet yo sy # ure
Wy 20m0s pure some
oureU ae S91810@)
‘}qeueae suondo auy-pueuuo> snouen are suondo
rn
Abf or wononponuy uy euseyeag ised T-eaey Bust doo.
i
i
“seoeds Aq porermdas wounaop 01 Hem nox sayy 20mnos eaey yo soureu ae soyy-2omos
‘sonds 4q pareredas wouunaop 01 wea nok xp soffeyoed yo soureu are saBeyoe4
‘aso,
{[se1g8se@) [suondo] {sapy-oamoslsafeyoed} oopenel zxeyuks,
‘SOI s0anos waey Moy} woNUEUMDOP [ay Jo Safed THALH seveU08 Joor st
aopeast¢
Wo Bue wael denel spdanexg,
passonoud oq 01 saonds £q paresedas saseyo asour 10 auo st ueusse.
‘qgeqeae suotydo ouy-puewoo snouea are suondo
‘orem,
“alyssep (suondo] deaef:xeyusg
‘3101 passed sassejo ayp Jo sporiatn pue ‘spjayy ongnd pure parsoyosd ‘oBeyoed ayy siutsd
preuroo deaef aq) uaqy ‘pam axe suondo ou uaqya “pasn suondo ayy uo spuadap indino ai,
“Sell S8e[9 mnoqe woneuzojut sane 3 sueatn 9] “sy SSe}oaxoUt 40 aUO Sa[quIassesIp Joon SUL
[3102 20 wil deacf-z
suuoojem gpt cardia
Sse} ayo pomiout uyeu ayy © possed syuaumnaue axe stone
nqap oy sso ew ay yo aueu ayy st aureuseyo
ayqeyree suondo au-purunaio snot are suondo
Akl 0} UOHONpoNN Uy ‘Weyseyxesd Yel ‘Peaee Sujsn dO.r QOP using Java-l
Parijat Prakashan An Introduction to Java
‘This function is used to check balance of customer
This function is written by XYZ
Date: XX/XXIXXXK
Time: XX:XX
”
3) Documentation Comment [1M April 2019, 2017]
It is use to generate HTML file from source file. It starts with one forward slash and two
" and ends with asterisk and forward slash as "*/",
asterisk sym
Using this style of comment you can insert information about program into program itself.
Using javadoc tool this information can be extracted and HTML. file is created. This is
convenient way to create HTML document related with program using single command
javadoc.
The javadoc tool has many tags. Some are listed below:
@author: It specifies the author ofa class
@version: I specifies the version ofa class.
Example:
”
* This class manages banking transaction,
* @author Parijat Prakashan
C8355 Page 1.14
|
iy
‘An Introduction to Javt
Parijat Prakashan
1 oP asing mat
| gvesint0
i
av
When you use javadoc tool on source file containing above documentation comment i
generates different HTML file containing program documentation that will show author as!
version of program.
{ 1.8 Data Types
* 4 daa type or simply type is a characteristic of data which tells the compiler ot interprete
44 how the programmer going to use the data.
‘ Java is strongly typed language. It means every variable, expression has a data type. Ever
data ype is strictly defined. The Java compiler ensures all assignments, expressions a”)
4 parameters to make sure that the types are compatible. If any type mismatch is found i
profuces error and needs to be corrected.
4 Following figure shows the hierarchy of simple types in Java. Simple type can store sing!
i cobra time
‘imple Type
aor.
shor, it, long) (Goat, double) (chat)
4
(boolean)
Figure 1.3 Basie Data Types in Java
‘shown in above figure simple types in Java are classified into four categories as
elunosop uiisés apootun "waNsKs HIOSY Jo pEBWU! apoatun Sasn 1 asnEa9q S=NKQ Z st azs
‘ausm) ses's9 © (oo00m) 0 safes pue soda z sad enep 289 Jo og sires
31UN) 14-91 -pousisun toys ED ay ~raIDeRBYD afBuIs a1yS oy pasn st dK seq oy
srapesey (¢
SCD “1p ayqnop
Sa‘ yp Roy
ssoydunexg
2d ep ajqnop soubas Que “Qsoo ‘Quis a seoury eoneworpeyy Aaessneu
rorstooud Jo 2ax8ap ysry wow pasn st adAy ajqnop ayy “Axessavau you
vaifop yBiy voy ryosn st 2443 yoy ayy ad aqnop weM
eA uorstaaud ajqnop soyeorpur ajgnop pue anyea uorsroasd afSuis sereorpur reo adfi oy,
oy) Jo aury
8€049P'E 01 ShO-2p'T ” anon |
80C+28'] 01926-26 x 0p, |
asuey Gay wpm | ada ujod-supeot_|
‘mo|9q Uant@ are sodky yutod-Buneoy jo SoBe
{WPIAN “9}qnop pue yoy ate yor suequinu quIod-Sumyeoy Jo sadki qns ons are aH,
jwod-Bune01
8L'0b ‘sh'68 Se ons wed jeuon2e3y yum ssoquimu osoys 0) psn axes
(Groquiny jeay) sraquina yuod-Supeoys
‘gm qu‘ yur Bu]
Torcononponuy uy eysergeag elie
x i
'¢8°75 ‘1s uous
‘€9°29 "19 0g,
-adhy eep says uonexepsop ayqeure sopenstoUtap ajduexo Suymojog ssodanerg
“pasn oq pynous
Wom Jaq 2jows 31g axors 01 poou sf aseyp 19AaUaYyA “98re sj Buo] Jo oBuey “o19 iq
53 pauos oq 1 ane dup sad se adda qns auto spoap wea xowumesBoxg “sonyea so a8ue
p sedfa qns asomy oonsag aouasoyrp Ao oH, Bip Jo ada ous saxors sada qns asamp ITV
L08'SLu'vss'9E0'ZL¢'£27'6 01 BOs'SLLDSB'9Co ze ECG +9 uo)
4 L9‘68H°Lb1°Z 01 849° ERE LPL Z— ze ma
4 couze 01 89L'e- Hoys
iI “a z ag
a auey (sq up wpran | 9443 208ayuy
“moyoq wont are sad oon Jo sos ue Mpa,
uo pue ar sous nq aze yoru ad 28H Jo Sad qs snog az az sa qu poustson
Bosdns you soop wavy sanyea aanedou pue annysod ‘poults ame S0HLL “219 09 ‘Og se Yons
aed yeuoney mous ssoqumu st ye staqumn 2foy asoys 01 pasn axe sad wep Ja8oHH,
F saatonuy (1
eajoog (b
suaroeseyp (—
® sroquimu yod-Buneo1 (2
suedonyy (1
:tey 0; vonanpomuy Uy
“unyseye Welieg Tener Sus dOO
i”
i
:Parjat Prakashan An Introduction to Jav
international character set. t contains characters from all human languages. I isthe union of
many character set like Arabic, Greek, Latin etc Is useful for global portability.
‘Example:
char chl, ch2;
chl=a';
ch2=u0063';
Here variable ch2 contains a Unicode character 'c’
4) Boolean
Boolean type is used to check the tut of condition. It ha only two possible values as tus or 5
false.
Example:
boolean test;
test=true;
1.9 Final Variable(iM April 2016]
Variable is used to store a value in program. It denotes storage location. Whenever variable is
declared it allocates memory as per type of value (datatype) to be stared inside variable,
Syntax: data type v
Here data type specifies ty ue variables vi, v2,...wil store.
Example: int nl, n2;
eee
g cS385 0
OOP using Java-l
5
me
a Reis
Parjat Prakashan ‘An Introduction to Jav
double di,d2;
char ch;
a, constant is called as Final variable. Value to final variable is assigned only on
declaration. After that its value cannot be changed throughout the program. To cre:
Je simply precede variable declaration with final keyword.
final double PI=3.142;
‘Now in program you cannot change value of PI. I is convention to create constant naine
jpercase to distinguish between variables and constants
1.10 Declaring 1D, 2D Array
“The limitation of ordinary variable is that it can store only single value at atime, To overec
this limitation array is used. Array can store mult
sami type. Any type of array can be created. To access elements fom the array index is w
10 (One Dimensional) Array
‘One dimensional array has only one subscript. Following is syntax of ID array declaration
datatype array-name[};
ere dta-type specifies type of data being stored invariable array-name,
Example:
)
immune, / int CJ aT = new intl J-
/
nen eed
cass Pag.seg
“fesse zm pass 29 we YM SIOo Jo Joga
muxou SO}EIpUE azI-MUNJoo puE sao Jo JoquME UMUTHENL SEDIPUL 321-01 234 Git'to-rupioy
‘{oas-mumoo|fozs-aou}od-enp aouaoueu-seue ‘(am swouopp fexry, mud no wapskg
480'2I'sp) ={}soqumi yn
“ener ur oresado woman
Ssowaw yore sowezado wou, Busi pareoo[e S| Aroma} “auop Jou st woReooTTe AoW aay
‘OO rw yw -
ojduerg
(Gs 8omg)meu pros am
7
“sureu-eue ayqetsea ut paxos Saraq ewep Jo add saytoads adk-eep 25h} rouiopkexe sexp
{(Qouwu-cesse adAy-erep ‘smuauraje Aen (| Supund pue Suuoys sarensuowap umrsoud Sumoyog
‘ooz={ehaqumnu
{ ‘oot-fobaquu
vor sasaiday uojsuounp sit “skduosqns 20 suoisuounp oA Sey Aare (q]Z) [eUo}SUOUNp OM) 4
fesry ((ouoyeuamm ou) Gz {
25s se xopa oxey 4 Wow® se pur x22 ql sires BurxapUT key
SL. 21 Spares fay andng 40182 SO 88 yORG rebs wxapurBuNods paseo oq we IE AeA
(Asses pene pnp ct tema
{ or} mou-roqumu — :oyduexg
\ : “eazy pos 2g uno Soe oquma ume Spel ats yy
poquima)yaud-mno-wensks » ‘foasodhe-nep mousouee-soue
"eaey wl zo222d0 uoneooHE AsoUoU
Fees sorezado ou, Sur pao st Kiowayy“ouop you st wonesoe Arowsu aieH
Aefo} uonanpong] wy
Testy Sut dOO.wij: Ma SG eee
Parijat Prakashan An Introduction to Jav
Example:
ml=new int
ia};
Above statement c
s array of 12 integers containing 3 rows and 4 columns.
2D Amay elements
square bra
-index and column-index in separa
ly row-indexing and column-indexing starts with zero.
2D array stores data in table format as given below.
100
* |
Following program demonstrates storing and printing 2D array elements:
class araydemo2
public static void main(String s{})
OOP using Java Parijat Prakashan ‘An Introduction to 1:
int number(][]={{56,34,23} {89,45,10}};
System outprint("2D Amay elements ae");
forfint iM0i2i+4)
{
forfintj-05<35+4)
{
System.outprint(oumiberi}§}"");
)
System out printing;
Output:
963423
#94510
Naw: Difference between prin) and printing method i printing method inserts. a. newt
afer print operation but print) method doesnot insert new line after print operation }
111 Accepting Input [5M April 2016]
1-7
C55 Pat({}s Suing )urew pron oners oyqnd (Qs Sung)uew pron oes ongnd
' )
Ppyourqpueuno sse19 ‘owacgaur-Tpueuniuo, ss]
‘sur pueuntuon woyy passed siaquima ox Jo UOHIPpe sarensuouap umeiBoud BurAO|OL “ou pueunio9 wo4y juss si aweU soya HOST
ap sooi8 uresfosd sy, “stusumB.y aury-pusumuoy Jo asn sowensuoutp ureZoud SurmoIlO4
[oF wr Pano su TE, vaumde OF Oise xopur ys
uxapuil use SY 7s, snousesed [PUNLOY OF
oranaco tuo passed 990 xan ‘juan aun puewsuoo sentaoas “cep Huns jo Kune st yor, s0rouesed TowIo5 219}
ABE st eAPL al2f{ °,UIPY O[[9HL, SE Icino soonpoxd yf JeURNIeT uo pasaqua ur puRUAIOD (js Sumns)ureu pyoa anes argnd royduaer
meg outa qeurqpueur, ‘weston cant
pee a 1m porpout Qurew jo sejouresed younoy ap £q poatacay are 2uy] pueuw09 WY JUOS sIwOUIMSY
5 , oye
‘uopnsaxo surfeq wesSoud oxy
word i oy uonouuoguy wonemdiju0> ono) sn 14, “2uy puwunuoo axp wos passed
a 104 ‘9q wea SwuaumBre Jo soquinu Ay “wonouny
| ca paysndwoooe sts. ms nod uoqy tuesZoud eacr 0} uonewozu ssed o:
|
urey owaqourTpuruitu0) eAelS
{c1oz 20 Ws] swounay our pueato3
‘pavf owacoutppueumuo; aeael eels
“yndyno-Supund pue yidut
Supdo00e 205 past SEIS
‘woy wesBoxd ut posautas seq “Ore
RUT RBIS sutwwu0. oBKIEU OF eawy oy, “sosnos. andr
Seyoed Sursn wonesodo sndino indus suoddns eae
J
Torapeyed eed ‘aby 0} UOROMpANLT UY yseyeng relued Treaty Susn gO,
‘exep 0} uoRIMpONU] UyOOP using Java-L Parijat Prakashan
int n3=nb+n2;
System out println("Addition is:"#n3);
}
Input:
‘Sjavac Command! ineAdd java
Sjava CommiandL ineAdd 20,
ery
Output:
3
Here s{0] stores first argument sent 20 a
ores second argument sent
form sing parselnt() met
ited.
class. Next addition is performed and output
BufferedReader
he ™ BufferedReader i the Character Steam Class used for accepting input It reads text
a charact
stream. The buffer size may be speci
default size may be
The
large enough for most purposes. It has two const
| 1) BufferedReader (Reader in)
2) BufferedReader (Reader in, int size)
Jo -read_data_from Keyboard, BufferedReader. uses another class known
fo ~sead_data_figm Sy"
treamReader. Following example demonstrates how BufferedReader is used to
su data tom user 4
import java.io.*;
public lass demo
“> public static void main(String sf) throws IOExe
InpurSteamReaderisr-new InpuSeamReade(System.in);
‘BufferedReader brl new BufferedReader(ist);
» 4%
System.out prin("Enter the city name:"),
String city;
ciybrLseadLineD «>. 6 poche A
System.out printin("Welcome to "+ity);
}
}
Output:
Enter the tity name: Banglore
Or ooo
Page!
Biss 2sri eg 2
sie a C—O
CT
‘souueag qpneae! uodtat
“pasn. 2q 01 anya yo ad sad se
psn 9q ueo sporyour indar aap wow poreato st ssw sameag Jo 12910 aaug “azedsoriya
sutyaip wesBoad anoge y, f4S94!W MJP Aq Yom “wowed seep e BuIsn suox0, oY indur suds .
tsouy inday Sursdao0e 203 pasn ssefo somoue st y[“a8eyoed jorveae! wr pauyop st ssey> sta
anopBueg 01 2w02}244
samuvag
avojSung :oureu Ao amp 220
; - *(Qourqpear [2q)ojqnoqasiedqnog=aBriu2aiad o|qnop
sam
\ ‘(Qouyqpearysqhojesredxo80y0,=280 yr
“ane wy sossopo zaddeua jo ajgejene sporpoun Sursred ayy Jo
suo usa ad op ponnbas oj Suuys yeauoo snus nod UoKp BENS UEYRJOKpO BHEP WEN NOK J]
pan st por ()peat
sum porpou sry, 3999 wo (Bus) 121 Jo ui peas o
‘pose om 23294 ‘suonesodo wwasaygp Surumopsod 105 sporow At
Mp ayBuls w pros oJ, Suns
i porpew QauyTpeas
sapeaypasayng,
*(Auros,, 01 awoojoqy, ud ino wHaIshs {
sQaurprawas-Ai9
ho Buns Srepeaypasayng Sunears opty ast yoafgo ssed 0} Aressooou 19 seproupanyng
{(:9ueu Ap mp soyag, rua nO WeIsKy oog pax ‘weans indur prepanis
eer PSP wTuARS mpm! aL PREG Wo Hp Sopp ety sn SNS
: 270 J0 900 sy SL SSE zapHIYMEALIgINduy Wo parea! sas] 29/40 uonouny QUIEN UL
ee |
7 i “pus ay) ve wondaoxgOr sMomyy Axessonau
(QsSung)meu pion snes ogged “ou porous Qurew ouput spomou pur rej nino nd 2
) SBeyped oreatf ayy, uoweiedo indino dur 1 yom eaes 46 afy0d
to fa
ouraquottas se 1884 ce
a
a1ojfiieg 0} awoojem
asm wo} pep Suns 8 peas 0 pas s sse ssumeag oy sovensuoUR yee HHMOTOA
TE TOO. pth OF UOTINONUT UY
2s8f 0} uoRINpaUT Uy uueysenead weed f
eyseyeng ele Teac Bust dOuses built-in class Scanner which is us
created from Scanner class
ee atitt Prakashan,
keyboard. In the line
city=se-nextLine();
we used nextLi
‘This method returns a string.
input operation. In main() function object sei
me of the classes used in Java for reading data fron
keyboard. The parameter System.in indicates standard input stream typically connected tig *
«+ Java Environment is the collection Java Class Library and tools used for
‘method on Scanner object which is used to read line of text from uset +
If you want data other than string then you can use different methods available as given
below:
Method [Ue SY
[nextLine) ‘Used to read string value
nextinn Used to read whole numbers
nextDouble) | Used to read real numbers
nextBoolean() | Used to read boolean value
nextLongQ) Used to read whole numbers with large range
(smn
Object Oriented Programming manages a program around its data and a set of well-|
defined operations on that data
‘The ultimate aim of object oriented programming is to divide and conquer
an abstract data type with polymorphism and inheritance,
ing invented Java language.
Abstraction refers to the act of representing essential features without including
Ano
background details.
q
development and execution of Java program.
. is Java Interpreter which is used to execute Java program.
«+ The appletviewer is used to run Java Applets
«+. dust in Time (STT) compiler converts byte code file to machine specific code in
executes the program line by line.
tool i used to find and fix bugs in Java programs.
p tool disassembles one or more class files
+ The javadoc tool generates HTML pages of API documentation from Java sourc
+ files.
‘Comment is plain text that provides information about source code.
AA data type or simply type is a characteristic of data which tells the compiler «
interpreter how the programmer going to use the data
To create final variable simply precede variable declaration with final keyword,
Array can store multiple values unde single variable name of same type,
“The javaio package contains several input output classes used for accepting input ax
Printing output.
+ To include packages import keyword is used
+ Command Line Argumeut i ued to pass information to Java program when you r.
it
‘The BufferedReader is the Character Stream Class used for accepting input.ti saa
ata S589
weoy (P ueysu09 (9 ysu0o (q XU
{Baws ur SwmEjsuod ayearD OF pas st plomrcay YOM (p]
iP wal Wg we
{roquuss yong yum sues uaue9 vopeNBaLmO0G (
aeael (p deaet(o sopenet (q oot
{Sly somos easy wioxy uonmeuaUund0p [ay Jo seBed “TALL Save19U28 j0on YONA (CI
aeael(p dealt sopeaef (@ colle
sumeBond eaeg ut sng xy pure pug 01 pasn st 003 Yona (12
fe do (9 5019 (q aaafle
214 apoo aysq jo worsuans9 amp st ey (1
fo do (0 ssa0(4 enefle
maoud wary yo uorsuanxa amp 51 AN (6
eal (p oeaet fo eral (q eset
{gumeoud eaey amnaoxo 01 posn soon Youu (8
yeast (p eal (0 of (4 eal
{qwerfoad eats aqtdazoo 0 pasn st yoor yoru (L
oda (p epnyout (9 suas (q sBeyged (e
{882 01 aBeyoed apnjour oy pasn st puOHsAay HORAN 9
FTorvononponsy uy Teipeyeg eae Taney Bun d00
asngou (P
pangunsi (9 Agnqened (q— Supeanpymny (&
ypvoxdde ,-sanainy ‘suméue ‘oroyadue und ‘20u0 aqM, SmO]TE amUEDg EARL HOTUAS (S
dmongewelg (p —wosdwoyy uy (> oryorry stag’ (q —Su14S0K sourer (e
WAVE JO sonmaan amp St OUAN (
soaeuaqu] (p — msiydiowfjog (0 uonsensqy (q —_uonensdeoug (e
{SPOKEN Amey ‘BOE aIGT su, J0 PaPL atp Seats Idz0UeD JOO TOM (E
4 somuequr(p umrgbomivog(> —_wompensay(q_vonesttoua
4 ‘Aaquqesnay 30 vapr arp saatd sd2ou00 {OO HoTUA (Z
" sounnoqay(p — usydiomsjog(o —wonpensqy (q—_uoneynsdeoug (@
a {afun aj8urs ovr apoo pue wyep jo Suuddeum Jo ssaooid st yom (1
=
suopsand a9j045 adn
© ‘pasn aq 01
pa Jo ody rod se posn aq ieo spoyjaur du waxayp uayy pareas9 st ssejo ou
ypalgo sou “sesn wioyy indur Sundaooe 303 posn ssepo sotpoue om st sauueag «
é
2 a
Ryo wonsnponey Uy Teyseyelg Tred Treacy Suisn dOO,
a :
i15) Which package is used for 1/0 operations in Java?
‘OOP using Java-L
aot a
Parijat Prakashan
An Introduction to Java
OOP using fave-l Parijat Prakashan
‘Trueor False
Object Oriented Programming Language.
Iteritance allows repetition of code.
{3 polymorphism means one form.
| 4) The aim of object oriented programming is to divide and conquer.
F 5) avai weak type language
6) After successful compilation of Java program class file is created.
E
bis platoon dependant language. [1M Oct 2018]
8 The prin() method of out object inserts a new line ater print operation,
49) The tool javap gives information about class files.
The float type indicates double precision value.
The char type in Java uses Unicode system.
a) java lang Bjavaawt ©) javaio 4) javastl
16) Which package contains the Scanner class?
a) javalang. b)javaawt ©) javaio 4) java.util
17) Which method is used on BufferedReader to read a string?
4) read() b)readLineQ) c)readString) _—_d)nextLine()
18) Which method is used on Scanner to read a string?
a) read) b) readLineQ) creadString) ——-d) nextLine)
19) Which method is used on Scanner to read ainteger data?
a)nextDouble) _b)netintQ) )nextBoolean 4) nextLine Q
20) What is start index of aay in Java?
al bl 90 4) any non zero value
Answers
Da a (ae aa yo oa Ne
Hb He 1056 1b Te Tad
He [1d Tb Tb | 20%
12)Jeva isnot fully object oriented. (IM Oct 2017]
" CS.355
Paget Sass
Its not possible to pas arguments trough command line in Java.
"Import statement is not essential in Java", [1M April 2019]
Sree!
Page 13a IOI] POO) onan
[2102 160 wis] “wwexBoxd ears Jo uonertdan Jo sxo0sd amp wre (|
‘eaep oF voHoTpOnu] Uy
-aydurexo yo dj ups sqerep ut sso zaeas upg (6
“any ur yndut id2oqe o1 pas sj sapeayparayng Moy uy (3
[9107 1d ps] ‘p2t9qKay 20 ajosuoo woxy Burns yndur peas or she snotzen urea (S
‘nog u sustnnos Jo sodA ays ue (0
‘wavy ur sdeare uo 2ou 8 aA (L
“qwouruonaug eae Wo ayou ® aM (E
bo
{supp sommeag Buysn anfeA WeaIOog peas OF pasm st POrHeA YONA or °
aapeaypaseygng Bun Suns w peas 0 pasn st porpou HOTA (6 il
it
[e10z 1mdy WI} cap £q uraus nok op 1eHM (8 |
{gswoumfize out puswusod s1 vem (L
jsBeyped st eu >
{8192 190 Wr] {1001 dese jo asm amp st TeUAN (E
jquoneynsdeoua streHyA (©
guopoensge S176 (I
suopsand) samsuy 04S
astea (EL
oma @1
au (I | ase (Ot 6 onal
ami (9
astea(s
amay(y| —asmea(e] sted al onus (1 |
‘Feney Butst AOO
_llOOP using Javact
Parijat Prakashan
Chapter 2 Objects and Classes class Fruit
Introduction t
‘
Object and class are the rich concepts of object-oriented programming. Java is a pure String name;
void view Qs
required. While writing a java program the main function should be inside the class. Ts. }
‘signature of the main function is: ‘A data member is also called as member field or instance variable. Here memory,
ic void main (String args (}) alloted for member fields.
‘As we know every program execution begins ftom the main. JVM execs the main functio 2-2 Aecess Specifiers (public, protected, private, default)
from inside ae
SN a Sah eee dee SL ‘A diss can be declared as public, protected, private or default, These are called
2.1 Defining your own class specifier in java. We can set the scope or accessibility of clases, fields, and metho.
these modifiers/specifirs
‘Aclass defined a new type consist of data members and methods.
1. public
Syntax:
_g. Tee acces level of this modifier is everywhere ie if we declare a method as pubic
lass class-name : By canbe accessed from within a class, outside a class within the package (collection of
{ - tad outside the package. It has the widest range of accessibility among all the
sprites.
Data members
Example:
‘Methods
ass Animal
| (
Example:sso NOU tO PlaYH)
pur ojqeua aveaud ss0008//
‘Qeieq w2u=p Ie
eyed Jo 109
aD jf
}
(Cayour []Bunns)ayeur proa oners on|qad
}
omacy ssp ad
(
ssurutmasoesd |
ayquuws awwaudy i
’
ena
“wo we aap sep somo wont
Jujssaooe are am pury “sureu ojqeutea Bung ayeausd e axejoop aa ‘afdurexo Suysoyoy A MT
SaS5515 pu S001) Tuayseyerg rele
Trenty Suisn 00, S2sse]9 pue s1091GQ,
‘pune we we | nding
{
{
‘Odeydsip'e
ayqeisea ouqnd aq Buyss9008)/
Spoumogseye
‘aiqeuTeA oxjqnd oup, Buyss9008// i
Qyeumuy aou=e yeuiruy 1]
sepa ognd ain Bussa0ae//
}
(care []8umng)urew pron snes onjqnd
}
‘owaq sse19
{
{
1G. 882], euMODBaq+,9AeG |, JupULG Ino wA}SKS
‘Coun w we und no was
t
(exp pron agand
uoyseyead velisedParijat Prakashan
d.name= "Classes and object";
Objects and Classe:
hos
f objects in the java. An array wt
ive. we can create an array o
ge objects in an array
led an array of objects.
} Kesopte
name has private access in Data
name =“Programi2";
| error
3. protected
The access level of this modifier is within a package and outside a package to onl
¥
classes.
4. Default (Friendly)
The access level ofa default modifier is only within the package. It cannot be accessed fa
cside the package. Ifyou donot specify any aces level i willbe the default or indy.
“Accessible to Publie [protected | default | private
‘Same Class Yes Yes Yes Yes
Yes Yes Yes No
Yes Yes No No
Yes No No No
2.3 Array of Objects
‘An array is a collection of homogenous data types java is an object-oriented pro
I ides the fail
8-355
>_By using objects we can access variables and methods.Java.
§mport java.io’;
‘gclass Demo
inti;
String name;
String author,
Demo)
{
!
‘Demofint id, String name, String author)
{
thisid-id;
this name=name;
thisauthor-auto,
4
void putDataQ
{
‘System .outprinthn(‘d:"¥i),
ae
8.355piow.6ey sp, Jo asp) pue s10}oN.ySU03 SuIPwO}TaAG ‘sxO}INIySUOD
Imay-toqpry
da02uRN
pt 3009
eagsrx ogy 30
pou same
a
ened
‘Oeecnnd fp
‘(aompneg’sureug'prqjoutag «22-{1]P
‘QamrTpearg-somneg Buus
{( caoupmy 3009 sow, op INO" MEISKS
‘Qaurypear iqowweug Suing
+( aur yooq s21, upusd no masks
‘(Qourqpearsqhinyosted soGannprg wn
*(-p1 4009 some, Jap ino wasss
GeHiqpSuay pot S=1 wos
spafgo Jo Aeure se pajteo St 2Aoqey/
‘{aloutag wouef}p oma
ee
s(uraasks)
‘opuoyuwanginduy aot)sopeayparayne Movaq ApeaypoHUL
)
sondaoxgor stonp( [se Bunng)wew pros ayes gnd
{
sQowpnes,:zorpny Yoo, upudmno'warsks,
‘{oure, 219. yo0q, JmpU No waISK
Treaty Buism gOOOOP using JavacL Parijat Prakashan Objects and Clas Objects and Classe
2.4.1 Constructor
‘System.outprintn("
System.out printin(’Name:"*n
}
public static void main(String args} throwsLOException
to initialize the object.
‘The following points should remember while defining constructors in java: ‘
BufferedReader br-new BufferedReader (new InpwtStreamReader(System.in));
+ Constructors have the same name as of class System. out printn(" Ent
+ There is no ret type not even void os
Example: System.out.printin ("Enter name");
1 ‘String amb. teadtine();
t Demo d-new Demo(6sam);
into; 4 puta);
Sing name; a3
Demo()
{ put:
} Ester rll no
Demotint mo String name) 101
i Enter Name
this.mo=mo; tw
‘this.name=name; Roll no: 101
2 Name: Vijay
bic void purDatad)S881 Pa s122Iq
“Omwennd'zp
*Cameyos, ‘2owaq mou-zp owog
‘Oneand'ip
Ces‘ Dowsg moxatp owag,
)
(ste ns) oex pos ones onqnd
{
{(e4,28y, nmudmowayskg
IN, qd I wash
Oe, upd yo asks
:
Omeqnnd pros onqnd
f
‘2eofr snp
‘suee-owewsiy
‘ou:-oursiy
t
(28e 1'sureu fuuns‘our wow
{
‘sueu.sunwsnp
TOuLOursm
"Nonenaesu 332fq0 wo spuadap s soronsysu09 v Bypeo og “soronNsueD
musjourened oy) s|]e0 xt siowourered uyssed 4q 109{go ue oyeaxo am oq puY -soroTURSUOD
Pep om s|eo y proMKey wou e BuISN 190[g0 UR aqeaID am uoyyA “sigueIed sey
fonaisuos pazusiourered svasoyy\ ‘Sioiourezed ue ney you Soop o.annsUoD yep 24,
“spf atp azyegmr 1 sxoorwasuno pazuorourered pur yeap auljop tea ayy “2p1dUI00
fx om fa poe a soonssvo ponisy wou Sus parnuns 5 xGo w uayK
*,sio1onnsu0d Sumpeopano, payed st
UIP pue oureu ous ayy axey ssoronjsuoD U2tM ‘PapEo[aAo 24, WED
stoyonaysu09 Sumpeeyasg THT
Teyseyeg ed Tartu d00Objects and Cle
static block is used inside the java class; it is executed when the program is first loaded
JVM. Itis used to initialize static data members,
Syntax:
‘Age: 27
class Test
Roll no: 2
Name: Soham t
‘Age: 0 static
2.4.3 Use ofthis keyword {
The ‘this’ keyword is used to refer current object ofa class. When an abject is created using
new keyword, constructors are called, Constructors initialized the object using this keyword
i
“this’ keyword can be used to
+ Refer to current object of class
“Refer to current parameter of a method
Return current object from a method ¥
2.5 static block, static fields and methods
The static keyword is used in many programming languages. If we don’t want to create a copy}
‘of the variable then we use static keywords. The static keyword can be applied to-
‘Block
sFields or variables
Page 2.1 5.355tzeieg
sv7za8ea
earl ur
sejo pauyapaud st ssei3ywolgo ssepo tues af
Qsseiquad sseio youyongnd | “p
s2fgo
WB Jo wonewosardax Suns om su2Auos yf
QSunsor Sung oygnd | “¢
40 Jaquinu apodysey ay) WMI Oepoouseuar oyqnd
1 algo won am saredaoo | (@s8afgo)sTenbaweafo09 angnd
wopduseg spoRPH
‘sso 10090 Jo spowams am are SuIMopOHf
sof se a0 30 se pn S59 Anu mo wolgg WE ag om
soafgo pie sayqetmea uo suonezado snot wuopad
‘vappuiano 9q ueo yep spornauy sapraoid stax “Enel ur sosse[0 pouyapaid snourea ore axayy HPSS9008 St Poa
ReaD pur sO
S8019 199190 1974
eave uy sosseps pauyaparg 972!
0:4 Jo anyeA,
Oqjosne, 3 ft
{
{
“Ofedsp aL :
oe
(sire Suuyg)uew pron ones ognd
“(qe Jo anes, ud no wasks
“Cb Jo antes, Jupad no waysks
xed
BT
1 1 ones
}
1804, sse19
oydorexg
54.930 ane, Jupund no weshs
“(grail J0 anqea, unui yno wash
}
(Qs82e Suns)utew pros onexs anjgqnd
veyseyeng liedOOP using Java-l Parijat Prakashan, Objects and Clase
class Test
{
public static void main(String argsf})
class TestStr
{
{ i
public static void main(String args())
Object a-new String(*ParijatPrakashan"); (
Class s=a.getClass(); '"**STRINGMETHODS'
System out printin ‘cass of object a is:"+s,getName();
String st="ParijatPrakash
, ‘ ‘System.outprintln(*Strn os
4 Systemoutprintn("Length:"+strlength();
hhh : ‘System.out println("Whether string is empty or not:"str.isEmpty());
2.6.2 String class ) er
Siting class provides several methods to perform operations on string object. Following sf
System out printn("Second String:"+stl);
ee eae System.outprintn(*str& str equality:"+strequals(str));
Sr.No | Methods Description ‘System. out printin(*Concatenate String:"+str.concat(strl));
1 [int engti Ttretums the length of a sting. as
2. _| sate String format(Siring format, Object a) | Itretum formatted suing .
out pintia("Replacin in PaijtPrakashan’);
3. | boolean sEmpiyo Tt checks whether string Is emy System.outprininRept m Pa
| or not. System out print st replace
| 4, _| String concat(String s) ‘Tt retums concatenated string ‘System.out.printin("Fotmatted String:*+String.format("%s",str));
it 5. | String replace(char oldchar, charnewchar) | It retums new sing }
i replacing oldcher with new char
Page 2.wzsded
Buoy all nod
‘ropiog a8 eYoed ap tpg
spisi 3 aang ‘soBeyoed uty anoge S59008 UE 2m TEU OS EMH ZILA OL OIPS MOU EUad cordmery
-sroproy oujtoads srotp s9pum pareaso aq [Tt sayy sseya" surexBoud wael- amp qpog afidiwo;, TAY Bae UF a|qeyreae souyoed ut-ying snoweA are aoqy.“sporpaut stomp Jo uonezyiEIN
saBeyood asouy uodust oy anny asf 2g WWAL UL pOUap ApeasTe ame saBeyoed
‘sop sip aptsusioqumu 2anp Jo aBwane ainduzoo 0} poo « a4 “32pfoy 338 Jopen
jeadieig UM TT axvg “aBeyped yrs 40y wreBox! v aM 0} soNpa somoUT UadQ
a8oyoed pouyap as) +
, i
1 saqumu aap Jo wmnstseur syndoo oF 2p00 € aA T4PIO}SIPEW J9pan stoped um
PW Wim 4 aang “aBlyped sqpeUT Joy weHOAd w ayM 0} soy Ue Lad
“soda om onm paztoBayeo ame sofeved wang aBeyped Bucy sf WEIGH Gael Kian
“is pur sym siopjoyous fF yasaid aBe3Dedyaeyoq-uresBoud sno ut aBeysed axp azimn ov pasm ut psoMLkoy ody
ayeax yn am adnexo sq ut aro ‘owen afeyoéd se ours stoumen asoyn sopoy vartat) 4
: sassepo
:aBeyoed ayeana oy sd —
"Say doa St sBenBuey SururuesBoud enef ui yaouoo jyasn Aan om sa8eyDeq
‘loquinu 2anp jo aBeiane popu e yun woneadgieg
ssn pla yes aleyood salgoue ayeaip ‘saqumu samp Jo wnmxeu poy oy porpaut ans
2 «qm 2Beyoed sys apis uoneradosyey seep auyaq sypeu auren aBeyoRd © aa
sadeyed L'7
uoyseyesnefued ‘Suing paneunoy
ndwory etched
‘unysoyosgiofeg ut... £q 2, Bu1oe|d3y
— dW ax, Aq 0, Stdeydoy
autjap J9sn 205 ajdwwexa Suumoroy axp J9pIsuor “wAel uy ABoyoed wao sno oyaiD UED 2 ‘SurunuesBorg eaerueyseyergietey ‘Song ayeuaweouoc
‘oueu-aBeysed 08 291% :Auyenba tases
‘Suyumrerforg ears:Buing puooog
anand pind eps BHD. a57e;0u 30 Adu st Buus sau,
se Aiang “afeyoed sno 0} aweu Kue 29 9 “30SN £q payeala are saBeyoed pauy
° League]
soreae
: unyseyeigielieg: st Sung
Sef enol
seeeenenes+SCOHLAN ONDUSstsse¢eeee
veyseyerd lle
Treacy Bust dOOOP using Java-l
‘/?MathsOperation java file under maths folder
package maths;
‘MathsOperation
public static void max(intaintb,int c)
a
iffe>b && ame)
‘System out printin(a+"is Maximum");
else
iffb>a && be)
System .outprintin(b+"is Maxinturn);
else
‘System. out printin(c#"is Maximum");
)
}
package stat;
public class StatOperation
{
public void average(ina
{
°)
Objects and Class
ans=(atbtcy3;
System outprintin(*Average:"+an5);
}
sport maths.*;
por sta;
ic class PDemo
public static void main(String args)
{
i ‘MathsOperation.max(3,5,10);
StatOperation s-new StatOperation();
saaverage(3,6,7);Miia ee
vec ated Sse)
i ee
tweoxdv Jo sseo yoea tu ojonI9SH09 940 (@
{Burpeoyson0 Joronnsuos st SarwoTI09 2p JO YON “|
ep = 5 ‘244s ep axprunad sty so sdeun 090 aso seo Pstsseposeddeun y 6
: ‘eyoed se poe st sasseo payeyanyo uot .
Bast urplowy -foustoqyaafendue sass yorya ea ‘2221p ame s2ssep9 pouyapaud, a .
Suymoyoy atp Jo yorym Buisn Joponsuoo papeotsaKo JoqOUE [feo WED IOIINIISUOD Y +g Pesta ons, non eomy eee
Ostenbep —_(2e/qo)stenbg 2 (oalgo)renbsq
sPotpout‘sioannstoo ut posn oq ued
2oalgo saqpo atos xoqnayy o—q9 6} pasn st woH}oUNy SuLMO|jo} 2Mp Jo YOKIA'S
. “parsaroud ‘ayeaud “ongnd
rtp ais Sonya aarenel-2 ‘Fonew pm gems jo sco: a amis oom sna someones
sured suonoury
armor ama farooda spun sep addanapsosndest steel muy y] RPE Sogwour END Sumy adh Mau e aR eD y
saueutgp .yomgs afeypea"g ong v
‘ompou pomoa LON st Buymoqey 2 30 wm “¢| (srwmss
stump ~
‘Owsoy aouefu se - i
Ws, matte [] 189],
. (0) soapy oun
G2p09 Suywom1y amg payaso axe 12, Jo stoalgo Aue MoH “ZH (©) s08a17 oun sos,
wounsqe'sannewq = yeuly “e ‘oam
el
2} pauysp eq wy spe ‘seo 0 Suyog afgausnw Saye yy puowioy am URN “TY Surxo9oiney
2 aide,
“Buyxoqun se pajes
01 ofa J6 worsens ap pay Buprogoyne po s rpafgo 01 adky
Samtunsd 30 wysieauoo oy) -afeysed Sumyeel wr axgeieny axe sossepa sodderm waet yy
99 AKG "Igo WoL “ON ]dmexg
S850) puP SHINO ‘WEyseyeig Tole00P using Java-T
Parijat Prakashan Objects and Classe
+b) more than one constructor in single class with different signature
€) destructor with each constructor
4) more than one constructor
le class
4 False 3. True
9. True 10. False
8. Which ofthe following is restrict smbers to get inherited?
a. Private b. Protected —c, Public. Both
9. Arrays in Java are implemented as
a. Object, b. Class. variable —d.None
10. Which ofthe following cannot be declared as a static
| Write down syntax for equals () method, [1M Oct 20
State the use of toString () method. [IM Oet 2018]
L
. 3, Explain the use ofthis keyword in java. {IM April 2018]
4
s
ls
6.
b. Object c, method 4 variable
‘What are Packages.{1M Oct 2017]
List two names of Wrapper Class
Ba
10.6
Oct 2017]
Define the term Wrapper Class.{1M Oct 2015]
}._ State the purpose of the static block {1M Oct 2015]
State the use of Wrapper Class.
1. “A class can bé defined as public/privateprotected.” Justify.
‘What is static block and what is its use?
2, “import statement is not essential in
3. “A class can be called as object type / 0. How to create and access the package in java?
4. Wrapper classes ae aot used to convert any datatype into an object. 1. State any 2 abcess specifiers used in java
5. By using to String we can di
1. What is “this”? Give an example. {IM April 2016]
3. What is the output of the following? {1M Oct 2015]Igtoz pady pe] soueysoquy yo sadky zp¢
\darexaajqenms & pm ssnosicy zac
Stoyyoads ssaove aBeyped ox urpdeg ga8eyzed ateaso 0} moyy
suree-ssepsadng spuanra aueu-sseppqng ssp
nanan OM] POOL) nee enncnanennnen a
{5102 adv ws) ‘odévoasays vod pue noduut yom ured ZaBeyoed st RIM'S
ur IV pee SLaquiows Heys UO a}OU ® ONAN “y
Jed & sso00e pue owauo Ufisap am op MOH “¢
‘ajdurexa aqqeuns
T1940 SSE paauap se uMouy ose st Sse Runstxo Woy porn 1
rads 10 ssefo yuared 40 ssejo aseq se UMoUy osye st sse[> SuNSH
din ang are veyp sassejo au ayeaio we9 no yeIp St BABY ut dourOGUE PUTHoq BOP SLL i
‘amy s9q uy Jo saddy pue (p1omay spuayxa) 59}
ae H.9}u pure aaueyLsOyU “¢ aayde4D
ree Bu
woyseye elie
dabeyped st rea, %
lumexe ojgeuns © ya Hop UF UI|dxg cenel w oBeqDed st EEA “T
sramsuy 3u07,
Burg moungs Sung
Bung mou-zs Bung
)
(() size Sins) ue pron ones oygnd
owags sseyo
Tener Suis dOShuai. Snoopy
Inheritance and Interfa
public void methodQ
{
System.out printin("Child class method");
7)
4
Figure 3.1 Types of Inheritance 4
‘Note: Multiple Inheritance isnot supported in Java through class Fr ths interface concept i
wed, ~ 2
1. Single Inheritance :
damn easy to understand. When a class extends another one class on}
le inheritance. The below flow diagram shows that class B extends ‘onl 4
Here A is a parent class of B and B would be a child class of A. :
: ouput
Base class method
If cud clas method
public void methodA() + Mates tetame
‘ j ie ikriane feo esis a OO teconloywhe one en inher fe
: aud example refer ~ Multilevel inheritance in Java
4
class B extends A
Page 33aa $5859
en
‘spuarxe y ssejo
{
5G0,)apaud yno-wryshs
}
(Od pros oygnd™
}
ose
"Ast ut dousy9qa! pugAd se [fom se aydnymu aney Meo nok saoepiau Butsn KWH para
0K Sak ‘saoepiour Susp) 99 we 2ouesLoyut ajdnynu Se Kea. ous & ut eaet oxy MH ponaryoe
4 mo soumoyut pugky Y “aAoge 2yH{ Yoo] pItOm uRsFED wOY. rerdhs y -aoMWaYUE
‘ores pur afBurs Jo uoneuqui e st oueou pragty rep Aes uD no suuen afdums wu
soueouuy PLACE 'y
2894p Jo porpayy
a ssep Jo pomayy,
‘W S519 $0 powoyy
‘V SSeI9J0 pom
anding
{
‘Oppoweurzigo
* ‘Oapoqour fq
SES pM Ry PTOI
‘Owpompaurziqo
‘Ovpomaur {go
‘y syo Jo porpaus ayy ss0008 te $9SSEI9 ITV //
100 sou = zf90. 9,
‘Oa mou = 1190.
}
(Qs8ze 3uung)ateu pio oneis ongnd
}
aydurexgqeaey 5819
t
$40 89819 J0 powpaur, utd yno warség
}
Qopoyyaur pros ayqnd
+
Yy spuarxa 3 S88)
{
$4.9 55419 so pomauy,japad no waIskg
}
Oapounaut pros onqndeek Me
OOP using Java-l Parijat Prakashan Inheritance and Interface
public void methodAQ
{
System.out printin("Class A method";
I
I
class B extends A
{
public void method
{
System.outprintin(“class B method"),
}
}
class C extends B
{
Public void methodQ
{
System.out prithn(‘class C method");
}
public static void main(String args)
{
Cobj = new CO; 2
+ -ee
5-355 Page 3.4
obj.methodC); /ealling local method
}
}
Output
Class A Method
Class B method
Class C method
3. Hierarchical Inheritance
jcalinberitan
‘When more than one classes inherit a same class then this is called hie
For example.class B, Cand extends a same class A,
class A
{
‘public void methodAQ)
{
System. out printin‘method of Class A");
}
ot
class B extends A_6e aie se
“aojonasuoo ssejo qwazed ayerpourunt ayoaut 0} past aq ueo ()adns-
poqiausseo nared aqepatsun axon 0} pasn aq ung sads-
‘ajgeuen 2ouesuy sso red syxpouru 3290101 pasn aq eo sodas:
row oy sods wane yo 3805p)
‘aygetea aouozyar rons Kq panayai st yous
‘Atyonda paiva sr s8e19 yuared yo oowesuy we ‘Seyoqns Jo 2OUR}Su a 98219 NOK J2A2URY
“waefgosso
twared aye;poumuy s2jel o} pasn sf YIN opgeten aouaropar v St eARy Uf lon sons ay
[10790 Wel vase wy promey sedng e7'¢
{qns 20 SSe[9 ply 40 Ssej9 paau9p se UMoUT 0s}
S801 QMS TUE
‘S81 sadug 7g aang .
7
a
sso ad
‘wexBetp sip ur auafy“S5e[9 xodns 20 sseyo uated 10 ssejo aseq se uinoury oste st ssejo BUM
ssuj wadng pz
paoaiay sadng Jo asn pure ssejoqng* ssejquadng 7°¢
“0s tao
‘Soup pure aoueTqUT ueseyeg welled TreaepButst dOO
‘SoeptUT Pur SOUT ATCT
:0q mau = {99
}(Q)s@re Suuyg)ureu pros ones onqnd
{
SG.q,)unund no wash
p
Odstp pion oxiqnd
}
VV spuatxo (1 $sej>
{
{
Ca unuudino-wesks
}
Odsyp pro ongnd
5
2 spuana qsse9
{
{
Gv. lond no worshs
}
(Odstp proa ongnd
+
moyseeig ied Tener aust dOLOOP using Java-l Parijat Prakashan Inheritance and Interface
eS
Example
‘The super keyword can also be used to invoke patent class method, It should be used if
subclass contains the same method as parent class. In other words, itis used iff method is
overtidden,
class Animal{
void eat(){System.out printin"eating..");}
}
class Dog extends Animal{
void eat) {System.out printin( "eating bread..");}
void bark(){System.out printin("batking..");}
void work()(
super.ea();
)
class TestSuper2{
public static void main(String args{){
Dog d-new Dog();
.work0;
y
Oviput:
cating
(7 eee
(8-355 Page 3.10
OOP using Java-l Parijat Prakashan
Inheritance and interfa
a Inte
barking...
Inthe above example Animal and Dog both classes have eat() method if we call eat() mett
from Dog class, it wll call the eat() method of Dog class by default because priority is giv
to local
3.3 Method overriding and runtime polymorphism
‘Method overriding is an example of runtime polyriorphism. In method overriding, a subel
overrides a method with the same signature as that of in its superclass, During compile ti
the check is made on the reference type. However, in the runtime, JVM figures out the obj
type and would run the method that belongs to that particular object.
Example 1
See the example below to understand the concept
class Animal {
public void move() {
‘System out printn(" Animals can move");
}
}
class Dog extends Animal {
public void move() {
System, out printin(*Dogs can walk and run");
Public static void main(String args{)) {
($-355 Page 3.1Sse-50
(ot0z‘stoz tdy WI'L107 390 ‘Wel Pxoméay yeu Tye
SSE] PU PoMPaPA 09 payejos promtay oULA Jo 9s/ HE
offen Surmesp
-~apons Suyaesp
~~opBamjas Suvtesp
sinding,
{
{
‘Omeap's
‘QeBaeuy mous
sQmeups
‘arang wou
sQmerp’s
‘Qor8ueroy mous
‘sodeys
(sre Sung)urew pron ones anand
Yeursmyduoujogisay, sselo
{
{:(;"218ueuy Supwesp, upund-yno wayskg} esp pion
Jadoys spuonta oun, sep
Soujisoy pu SouTaIy ‘ueyseeig welined Tener sursn dOO
zveateg
{:(."2foqp Supaeup, upd no wershg} erp pros
Jedeyg spuapxa afamtg seo
{
{:(."arfmenoar Suysnsp,jopund ino wors4s}Qmemp proA
Jodeys spuorxo ayfuera0y sso
{
{:(c" Sutaexp, )opmud ino-warshg}(aeIp pron
Jedeyg ssejo
adeys yduerg wsiydousog oupumy vary
zayduexg
tu pu ae ueo sBoq,
‘nour uo syeumry
anding,
{
{
sep oq ur porpou amp suru ‘Qaxourg
sso yeumry wx pompous ayn su (Qonoure
‘palqo 8oq ing aouasayas jeunury // :8oq Mau = q yeuEy
spafgo pun aouajar
Pury /‘Qqeoruy wou = ¢yeureyParijat Prakashan Inheritance and Interface
QOP using Java-L
Final is keyword that can be used with entities in Java to restrict their use. We can use it
thods, and variables,
{we initialize a variable with the final keyword, then we cannot modify its value,
‘We can use final keyword with 3 entities -vaiable, class and method which has different
purpose as shown in below figure
Final Keyword
Cate > Baws > Ciena
Toy
ocese — Toprvet Tepe
Canaan Werance Matos oerng
Figure 3.3 Purposes of Final Keyword
Final Variable in Java
Once we declare a variable with the final keyword, we can’t change its value again, If we
attempt to change the valuepf the final variable, then we will get a compilation error.
Generally, we can ct
constant whose values:
ler a final variable as a constant, as the final variable acts like’a
ot be changed.
3.4.2 Final method in java
We can declare Java methods as Final Method by adding the Final keyword before the
‘method name.
‘The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the
Final Method is to declare methods of how's definition can not be changed by a child or
subclass that extends it
Syntax
final-keyword retum-type method-name();
Neen eeerrend
(5-355 Page 3.14
OOP using Java-l
arijat Prakashan Inheritance and Imerface
Example
final void rund);
Ifyou make any method as final, you cannot override it.
Example of final method
class Bike
final void run(Q)
{System.out printinrunning");}
3
lass Honda extends Bike
void run
{System out printin(‘running safely with 100kmph");)
public static void main(String args(}){
Honda honda= new Honda();
honda.runQ;
}
4
Output:
Compile Time Error
3.43 Final Class in Java
We can also declare a class with a final keyword in Java. When we declare a class as final,
then we restrict other classes to inherit or extend it
S355 Page 315