0% found this document useful (0 votes)
2 views57 pages

Java Programming Unit 1,2 2

The document provides an overview of Java as a general-purpose, object-oriented programming language developed by James Gosling in 1991. It highlights key features such as being both compiled and interpreted, platform independence, and its object-oriented principles like inheritance, polymorphism, and encapsulation. Additionally, it discusses the Java Development Kit (JDK) and the structure of a Java program, including comments, package statements, and the main method.

Uploaded by

k9c7x8cdcq
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
0% found this document useful (0 votes)
2 views57 pages

Java Programming Unit 1,2 2

The document provides an overview of Java as a general-purpose, object-oriented programming language developed by James Gosling in 1991. It highlights key features such as being both compiled and interpreted, platform independence, and its object-oriented principles like inheritance, polymorphism, and encapsulation. Additionally, it discusses the Java Development Kit (JDK) and the structure of a Java program, including comments, package statements, and the main method.

Uploaded by

k9c7x8cdcq
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
Dr. Mrs. Ranjana A. Ingolikar | Ms. Ritika P.Wanjari_/ UNIT 1 INTRODUCTION: Java is a gencral purpose language, because java applications can be developed in almost all fields like house hold devices, mobile application, web application, information systems, gaming etc. Java is a truly object oriented language, because it is not possible to write down a program in java without a class. Java is a case sensitive language and is strongly typed. It is a strongly typed language because every variable has a type, every expression has a type and every type is strictly defined. It is known as a strongly typed language. HISTORY OF JAVA: Java has been developed in 1991 by James Gosling and his team from Sun Microsystems. The original name of this language was Oak and later was renamed as JAVA. The team developed the web browser called HOT JAVA to run local applet programs on internet. "How Java is different from C++? Java is a truly object oriented language as everything in JAVA is thought in terms of classes. A Java program cannot be written without a class. Whereas in C++, itis possible to write a program without using a class as well. So C++ is an objected object oriented language but not a truly object oriented one. Geatures of Java:,@ +4. 1) Complied and Interpreted: Most of the languages are either complied or interpreted but here, we have a language called JAVA which is both Compiled and Interpreted. A Java program is first compiled and is translated to a byte code. This byte code has to be further interpreted to get a machine language program which can be executed. ~ Platform Independent: Java Language is Platform Independent because of byte code. The byte code of a program can be transferred to any machine, may be of different configuration or having different operating System. A change in system or operating system does not force any changes in a Java program. A Java applet can be downloaded from a remote machine to a local system via internet and can be executed on the local machine which may have entirely a different configuration or operating system. The byte code can be further interpreted and executed. Byte code has made Java Platform Independent. 2) ‘compted Bye cate Source cose Into ae Exe cate Daan a pare obecorented nngvage as eventingiJAvy Chee cebuses undoes. Ajraprwam connote Moxy Saar me ora he gel onented eautes Hike code reusability, sink, aumrocton tg ‘object Oriented features ‘}etaes lass isa user dined datatype which nyresent the rel world obj» LOMcreay. it can te eomored ns blueprint or protetype fram which ‘SEEN Seated te because of clan, our data cae. lean be consideree ‘Goer in hich the data andthe functions (methods) which enn aeeess the Ee Se wropred iogetber. loan excellent example of abstraction. oven An syect isa particular instance of clans whieh has actual existence [Asunber of tec aa be crested [or nrtances| fora clas. An object in OOP: ths sone sate aoe behaviour in Jam, the state le 4seLofvaltes of an object's ‘able atany parcunr ime andthe behaviour ofan object simplemeated st {i neritance: Inheritance deseribes the parent cil relationship between Neo (dhssrs clas cap some ots chareteeis fom the parent cl an hen ‘dare easnen of oun, Inhertance makes estat postble. Rewoabily ‘Ses our efor ef wat the cede again and recomplin 1n) Polymorphism: Tae silty to change ‘orm is known a3 plmerphiar. Javo ‘Supports dierent ln of polymer pista Like overloading, overtaking parainee (uz Method overlong and consirutor ovesoading se exellent teamples pobmerpiam, “Abstraction: a abstraction we use ating without giving the background ‘he dtl of the thing are den rom te Uae. A clas sun exellent example of sbsiaction as ii dct defined ond dacs! withoat giving ie Barren Another example of abatraction swe se fan without hnoving ie deta, ‘i Bacapetlation: Encapsulation ithe proce of wrapping of ata properties] {2 features (methods) of an object into a single uni a the unit here i © ns, Encapsulation enables das hiding hiding iclevant information ta the ‘sere of cass and exposing onl the reevant detail required by the user LAI Object Oriente 4) Robusts Java is a robust language at automs he memory when notin Use Jaea ally does the garbage cllecti eserves memory dymaraicall ~ . program execution, It ira checks the relay of the cade teforesxtgation fe pies belerprasranctn neo ames tces Seed ice tat ed presen en eae See ee eee ane ecommerce Sete ete paleo chet erent eerie Btn re ater seagate irene menor as caine Spree as etapa Seapets eeateriniee reece Se fegeerenirenace roscoe iSipacrc ar tbe Sintra rei ert tn abet rg eae oe tin ratte tema ates ie eee as wee caatuien meneame cen fate o a conte _———_ entag vevied with 8 sono ap sen rem ons apn ot 20 es af ped hi Inset ape expres, NL a eee, Ti ws card gence? tie empath ene te diectory JDK, Fropomis rein ie AUST mone contortion icimom Hardware Configurstlon: 1) Bicerpaible 86-8. 2) Minimum of 8 MB ne 3) Awindeus-compaibl sn 4) Anardctt. 15 AMicerot-campebe mouse Software Requirements: I) aden Windows 95 Opcrting System a bore Soppar windows, macnosh Fn 2) SOI Zeer en supare browses He Internet Explores seas iemeceesa etocape navigaor etJava ‘te code makes it posite wo run the program In wide varcty of envionment because foreach platform, we need only QUVAE When JUM is installed in msyatem, Teun fun a progon that is complied on some other platform, Adiflerent V8 has tobe defined for w diferent platforms no JVM eilers rom platform platform, The Cacist way to erste truly portable program is tgyacute byte coe in JVM Surprisingly, aly UM tens designed so an ltedietr. alo makes a Jav prosrammore secure. Abyte nde enables JVM 0 extcate programs much aster » Fircomper ten spate of V8 in that ease selected poruone of bytecode ae ‘compiled into executable code bn teal me om a peer by piece buses Difference between Compiler, Interpreter and 3vM ©! 2. “Sorapler Taare ae Toners aoe |W canvas w aur Game | T comers Bye code Coie into” byte | into amachine code. | nto machine cade, Shey machine code Say aR Ge Se ELS | RET ING Teel Sa ditrent| ed. on arent | paid orient Phra pialorn Fito aR RE | Gamers Ree | Sted porns of Ti a cue ade, ne a | sate an ompled te wine cade atthe | machine “cade one | emeutabie code i eat fine hen A eeor | ritementxt tine. | Ue on piece BE Beer aon : = = hu 8 Se Se a cen a tomer ear mer ear “a Cer comparatively slover| than compilation, Ye senajnade | Be = = a pe rake TE ajc porte. figereat hardware | indrpreter Se Soe es eae va se See wos BE race lu gnye ot pe ‘ees a aig i ar ih wt ic amc ica lve tin line oot wth ence the eee he cote gly red set ‘hat roves ecu and portables THE “ Server of Java program: ~ ih Jova program has the flowing structure in general ‘aan Son TF Saint [eer Tapa [eee i eh Tree waronee Ca eon « msinmetiod dfn > Docureatation Section: 2 ‘Donixeiton possible withthe help of comments, A comment is non icc utr geaeraly wren for proper understanding ofthe usc: Fee tseolacommnest aes fe pop mre readable. The comment above a endinligent Oerussof comments snnecessury increases re efor (ibe propane comment shoud be abot but inlet ‘There are three types of comments avaliable in java, 1) Sing ine comment Sing ine comment is represented by //. The statemen inte ene line sartng fom // is treated as comment. 2) Matiine comment: In Java eveything thats inched within /*and*/ is teat aszcompent The comment can comprise of mile ins. ote: Athoueh this section is optional, te recommended to include thi action Ih the program sothat Une prgram is better underaood, Package Statement: In this secon we declare the name of the weer defined package. Whatever classe ae defied afer his declaration, These classes belong, ini packics anda menage acorn passed tothe cmp. The plane Deciartion of package package sample; Import statement: {f we want to use methods defined inside @ class, that class 1h oie imported nse the program Its neccesary to eno abot the pacing to which this lags belongs to, Aclass can be imported in rogram the falowing ‘inp. We may have the import statement in & program may" 20 import Statements are optional ‘Import packagename classname; ‘Bxanpe:Impor sample. Tast; Interface statements: Classes heving certain testictions on it are known as Interface. This s uted for multiple inheritance, Deliing an interface is optional (Clas Definition: Jt may contain number of classe ® which can be weed in our program. This sections optional sain method clus definition: This the mostestentil part of aJava progam. The ‘ain method marks the execution peat of the progam. Inti method, wc ean ‘ieale objets of various clanaes and establish communication between them. ‘After teaching the end of main), the program wil be terminated, JAVA DEVELOPMENT TOOL KIT ‘There are mimber of development tole available in Java which are going to help usin developing and mimning progeass, 2) javac: javacis.a java compiler which helps us to translate java source code into ‘bytecode ‘Bxanple/* This pogrom takes marks as np, alultes the total and percentage SYax:path>jovacSlename java ‘and ln decides hte a sudent has passed o olled*/ ‘Example: C:\JDK1.2,1\bineavac Test ara, whece Test ew Clasename, 3) Documestation comment: Documentation comment ia represented by (2) java: java isan interpreter which interprets the byte code and converts it into HTM tha documents our program. Beample: ‘his Cass draws pie chart author aaeer “overson32 ” A). This form of comment ie seed for general documentation sutomatcaly. Documentation comment is specially used 1! ‘achine code, I also runs the appicalon program on commend prom Syntax pathejava filename Note: java extension a not eguire, Example:=C:\JDK1.2.1\binviava Test ‘9) appletvlewer: An applet viewer enses us torn Java applets on standard web browser, [views Java applet program on web brow. ‘Syntax: pati>appletviewer ename htt ‘Beample: €:\JOK1.2.1\bin-appleviewer Test. htm Note: An applets embedded within an HTML code and saved with ml extention neous eA “ecoments ome source code fle Ros an Systemovtpenn Hello Worl" Times cork et netanelee : + mtn CUDKL ATW raececteimioaricodey sy fe cong race a sr a syntac pate) Benard ‘Where cos i. keyword. Hells Word ia the classname which isthe main eis a8 {he method main is defined inf Generally «Class name stars witha capital ins Testo Bale ser whieh converts byte code fi aaa dnessembier jocapisxieascmble {then "the bences mar the bly ofthe program and the entire java code has tobe Se feriten inside the clas. ‘pron pogram deep tive methods sp jabs pres header fle forthe us of eerie tneroductiont Aplcation te APES ain is a fenction which essentially hue parameters fm Java, on en pope chon sTt achin, | gthch an ober ote {percos an aol = cde hat a Tun ex a remoie ash “rnnfunetion i pbc beentte we should beable to accessit fom outside the sss step foreretingand erecting Java application ‘This faneton le static because, it belongs tothe ont cass ‘Tie funtion is void ecase, i doesn't return anything $y eure hat JDK inated inthe stem. SNe oped oeny Joa spared editors UES texte ping se method, which wll print the aring included in gouble quotes In Ihe an array 2 ie or ee db ted ha ara program haste ten win papethess erat i aol Oke Onented angus. ‘ysem a class and out eam object of the la ayer 4) Salta Bente in evbectny wich is preaent inte destory IDK 8 pry Jaa statement should He terminated with aerial secsasen i Note: Sin "Sing? ond System ae in capital aa they are casenames Bangle Testjvs where Testis the Classname, 1 compte tis code wits he are compiler, ‘Multiple classes in a Java Application Program rope rac Test java dassRecterole £ ‘Aer coping te sourcecode, we get byte code (a code whic isin frm of 1 ‘On The te codebase cave ame asthe sre eode name bute extensc ae . vo ett font) 15) Ater success camslatin, interpret the dave the java interpreter 5) Aher sucess complain, interpret the Java code with the java inter length ‘Synur java Cltenae breath ote: java eension snot cegied > ample jaaTest 6) After imerpretaton, the eutpu wl be displayed R pascal aye ‘las Rectanaledreo ‘eoss Helowons ig ov piste mas mc ub state old main (String a e String arg) Alea ares: Reetanslesreaobj_areaenow Rectanglonrea(); xeon Joe Programing =< Soy cua gent . Sete [Link] wees grt tener Fare AONE ntl Jara cote which i wae In ntene! computing, This code ao apret igo so Soe computer fo another computer through internet aS ich ne ce erred the cde shoul have ape views, TESS Eien oopporsdae. An ape can perf an Ieee ra REy parties aay anunds,ceate deer Input, cree anintion ‘Ey tucrecove games. An applet canbe local or remote Sample Applet Code Inport veamecraphis: deste apeet ape € ‘public void paint{Graphics a) ‘ .crawString( Hello world!" 5, 25); » \tokene ‘The smallest individual meaning unit ina program a Imam as teen. There sre 6 upesoftabens 1. Keywords 2. lMentisers| 3. Literate 4. Operatore 5. Separators ust Keywords Keywords are the words whose meaning i lready explnined to the comple, in ‘advance and it eannet be changed bythe user They serve se balling bee for the atatements writen in Jur program. Keywordaure wten in lbw eae Evry word in Java is either keyword or an identifier There ae total 60 beywutde i \Jeva which are used and reserved fotutire uses eywords have a specie means ‘in dava and cannot be used as variable names, class navves, method nama ste Keywords in Java: abatet [aetna [te ‘pantar ——[apmchionbet ‘oats ——[ a ater ‘his Break doable [implements —[ paciage [Weal ye lee feepert [private es Tjoase [extend —[inner prelected [thrown os Tales Tmstansead [pate eons nth inate aires —[ ets [i char Tea Teo her wr ai Ter abe ate wot eainus [gener [ul whe Identifiers Idontfers are the names given to part of a program, They may be names of srables, arrays, meiods, classes, variables, objects, packages sn lnterface ia the program. Roles for defining Identifiers Mentifiers area sequence of letters and digit. Letters may be capital or small ‘An identiier should start witha letter or an“? (Underscore) Te should not start with adit, Keywords should not be used Spaces cannot be used, ‘Special symbols ether than "cannot be used, [An identi should aot caniain white spaces, ‘Beamples:DateBict,, interest Rate, AMOUNT, M1,SCont Literals ters are fined vatues that do not change during the execution ofa program. ‘They can be assigned to variables. Assignment cepends on ts type. They ere aso called as Constants Literals can be divided into integer numbers, Geaiog point hhumbers, character nd stings shown nthe [Link] speaking ere arc wo (pes ofcoastaite 4 name for identifier sure ors Programming _ Ae yt et 1] Numer Costes “the main ndvantuge ofusing hexadecimal number is it requires tess CChareter Consent [nd conversion from hexadocimal to inary number syatom is e285 const ire frequen used in programming, LEmmples; Valid hexadecimal integers; OX2, 0x07, OXbed {i Octal Number System caer ‘Oct nuraber system has the base 8 and uses only (etal mamber anal aways start wth a. x Constant sng Constant Advantages of using octal mimbers oe 1) ttuses less number of digs than decimal ayetem: 2} Octal numbers are mvch easier to rend than biniry 3) tt requires lee storage space than binary valid numbers certain rules applied t0 it Tt show on fin, cea ea betes the Con ‘Buamples: Vali otal mumbers 0123, 057 orage space cours and Ox ete 8 digit i from Oto 7. An hora aves ear constet RICO 1) emericcenstants Numeric natant cons erate Moc hibaala mete, namoamerten foros Peer sa vinci wrmmentemloc 9 a ‘represents off position and 1 represents on position. Any number ‘whether it is 1. Integer constants ‘Gecimal, octal or hexadecimal ean be represented os a binary number. A binary 3 ses See he ce ahctae anne ere ete emer 1. eteger Constants ee are othng bot Tned set of gts putinaseaence, All positi Adeantages: Nee Sec noers whut decimal point are lteper constants Gf ech beta then Aces oe eided int our tp 2) Simple to implement. Decal 8) Ithas the owestbuse posse Oca 4) Engy o understand and ean be used to build any typeof ole gate. 1 eres 5) Robust in transmission, i Bina ‘Vad binary umber 0110, 1113, 1010 ‘nDecnal Constants ote: ‘Adecial nie tas alae 10. Iss the digs from O09, Decimal eonsturi_t) Octal numbers and hexadecimal mumbers ae more readable than binary ‘Siegler eed arepr to tants a SoHo pee ea inks Goal cauiteeed ee acces icy fercompt ten otpstem mtr. nen foe oc and ex rt ptr bel a nfo pat oF cal and hexadecimal constants are rarely used asi iil for & oon ‘Se used ape hve 10 ingers and ey ave generally uscd 9) Ottal nd hexadecal copa yore i ecu fo Stee renmieienetesen ace ah Fe acim from Ato For fromatotwhere Aar ateprese™ — prample; 19.25 or -17.5 10, B orb represents 1) and soon (1B orb repisents 1 4 oon and Por feprcgenia IS. This sequen sscoms warnings ® S} Fae point notation re two nottions forstoing real const string Literal A sequence of characters enclosed within double quotes is known a8 ang Sy we tao 4) Pardpaintetaton a pps tie, | A ieee earn deine rect pants" “IS7, "C000 MORN tw ae eu” ST ptaton. We may have a numberof ie ee at or afer x, Alphabets, numbers, spaces oral special characters can be included within double cee lem oe oars ne SoS Star be ote =. ne cs 79s Bangle 2555, “There area few characters that are used to separate [Link] 8 rersed in exponential notation. This numb, the feparetors that are weed in Java, ‘real suber Pal een ad the exponential part. The mantisen and SSIES ft mtn dh —_— sae -_ ‘exponential par are either separated BY parenthesis. v "+ Used to contain the list of parameters Sonim Banca emer airy on + Gent enterion change he umber egret ind foil netation or ee Bi cea hu meen opbrel so is ie 2 Bee cating er ter etapa cts solace eae fT Se Poles 25009 Ded de, 155, 2603 3 Undiemy iateieston | Fad nnn atl or repsenig weber tat areas org [eae TTT it ar ts or ocanmawe * Hee m= tet Stine RE xsl Too08 . = +e regres are sa eT gowomes 36E7 1 ete Sowden a, 1 segechonstr Lite : 7 S-Ueste spe pce en ey cacao ser oa special el nhided thin igh quote siopesgoted cate Soom ecgs cain oat + Dede spate ee meted se ion new mupenes: ‘ariables: co mag ‘aralege the vs that change ding xeaton ofa program The name i ae been m estes the forte wate Aveabe eae etoed = ay fame ven to sn mesry oni order toa dae Te vanobe sald e ae ica ata pe, The sacle date ean sted depenon eee et vari Keywords cannot andar aac nee vane soe et Tio Fe 15 programmer shouldbe mennngl en fers he epee = Single quotes ee = neem ud yan X12 Anu ne tmnt, ant ar ae empuier arabes ae nothing raced mermeryfocton aed by @ siven name. seo soo Pogatning 634 cease STi eterna Bednar ele 1 ete Sc tao ecaraion of rales ‘Once a suitable warble Sis toe comps I ala becomes witha number. aaah) i ot allowed. to declare the variay tia necessary to ‘ aren dec rode ta pe tote comm ee aig tre tho eta, When avaiable care Cathetenough mea res el oer e. It also specifics wh, Soa ae es a Seren nS ae : oe of moat be dele when it used in program, syntax Dette vera, variable, sane to bededtzed maybe int, ost, char or double The Hts of varie Irecepratedty commas, Borie 1) tex: 2) ims: 3) Sate, 2) douse ra 3 dare Int represents inteer type of ata, fat represents single precision Noating dt ‘ope double representa double precision datatype, char represents characie anaore, In examgle | variahex isdeclaed us byte type, hence reserves 2 bytes of memot ‘aserethedai. In cample2,alistof two variables xandy are declared ae int type and bytes! -iemnry i reerved i each arable In example, variates idee aa oat type hence reserves bytes of ment tostorethe da In example 4, variable toi ecard ws double type hence reserves @ bytes? ‘ematy/t store the data {nexampl variable cf declared as charter type hence resesvea 2 bytes! memory toatare the dat. vats ‘Asslgning values to variables Once a variable is declared, then «suitable do variable. Assignment of data canbe made using Syntax + ‘variate_neme=censtant; constant can be assigned to « ‘he assignment operat (4) ato=5.28057;, cea ules for defining varlables. 1, Varishles area aoquence of letters and lt 2, Letters may be capital or smal. Uppercase and lowercase ia diferent, Example: RATE, rate and Rate are difereat 23. Aneniner should stare with a letter oa (underscore 4, Rahould not start with adit, ‘5, Keywords should not be used as a name for variable, 6 rt Whitespace isnot allowed ‘Variable names can be of any length But for eur convenience very big variable ames ave ot ured. Scope of Variable: ta voriable defined inside a block, the s2ope of variable is inide the block. The tmomentwe come out ofthe bis, we gp out of spe and ito life ne false over ‘hiss trie for local variables. However if we define a gloel variable the scope ‘oie tine ofthe variable i throughout the progra, Such variables are Gelined before main. In Java, two majer scope are defined. One in clans aeape and second isthe method scope, However, thie dltngusehing ie atiiral, Ia variable defined within a scope, we are localizing the variable and protecting i om ‘unauthorised severe, [Broadly speaking java variables canbe classified as fellows 2) Instance variable 2) Cass variable 3) Local variable Instance variable: Instance variable fa declared inside the class. I is creed when an abject is instantiated and therefore associated with object. Dillrent values are taken for dlerent aboot, (Class variable: Clase vaviables are global og cin and belong to he entire stot ‘objects thatthe class creates, ee Se bee. Te OMEN ECO fai ne a0 roe eS a acta thin oth Sern epe taco ve cps 20 ST eek Fae eco shine Dots Scone oF Ee abieh pes ume fo cannot be alae al vg the ack Deca eter del sare ter blk ie avaable in all the three Sof tn Uock2 ie lea to block? and ie ‘tse a the end of bel ‘eps wie declared in he Eee tee reste buch Is decor eine eyin Wo and ges st. Suntec, theyre ein blskd wil Eebove in the same manner as Datatypes In va ¢ Fac auypein sen ores * “A datatype should be assigned to each variable. deciles the ape and Gy of {Gata abe stored. Java nar rich data ype. Jara has basically two datatypes namely primitive and non primitive Primitive Type 1) fntegor type: integer typo has the eopabiltyofholaing postive ne well ae negative ‘shole numbers Integer Wipe has four sub types numely byte, bert, nt and Tong ‘Java does not support unsigned ype. Leathe integers hove to be ether positive ‘rnegative Sralier datatypes require loser memory space for storage Therelore {tis edvised thar appropriate datn type should be ehoven to store the dats. For example, f we want fo store the dita #5, chen the datatype shuld be selected 3s byte as cis just suicient to store the data a bigger data typ ie selected for ‘erample in instead a yer then memory wil be wasted. The allowing table shows the type, its size, Range and use yr [Se Rae I tee ‘ere | TBye “a8 to 127 etal when working wi rae ‘inary deta. Enample steam lorvta rom network re Sart | Foes | SAFEST SR TET | Lest used va data vat] = byte “LLW7aa348 [Bost commonly weed ° datatype. General used for : patra ope and index 2.147 983647 ange, Tae | Soe | OAT STEG RSA TISSS | Ueed when al dats Ge 2 fot suficlent co hold” the Aesieed data, Ii uefa when 9.223,872,036.854,795,807 | bigger whole numbers ae 10 bev steed Kor example fhumter of mes the ght tants Depending on the range ofthe digs used, integers are divided into four types” Decimal i, Oat |, Hexadecimal Js. Binary ote: In case ofmixed expression, the variable flower datatype are promoted to her datnype nud then hey partelgat a the eleatons 2) Floating potat type: This datatype is used sehen itis required t9 store real numbers, There fe two kinds of foating point pes 9} Float: t represents a single precision nummer 1. Double: It represents a double preciion number orng ea constants pegs ww strns o 0 psn bce an re pots soon e = digits with decimal point: eer Sete SEES ep eer ve the seb oa oeaed ta ed place sown 2 amber; at rd Pt bette ne decal point Secoal pat or alert 29e5ete “2 85, 225, $5, amaeinoee Armco a et SS ema a Seer eee Sees oe aces st ni pet fe at in Deen eo ee ra ta ei Seana ne meee fae = Me i asiinasid = ee 3) chester ope: try mot ore hn Sh atte char ued Jak uses Unicode! Ieper chs Ue an mena vai se ia charectrs om al ran eavas suchas at, ed Rae Helo © lor te ceedpecarvs ie tench sential actation. This num 150 35807 ‘ble: Comparison between C, C++ and Java a Cade red cree [1 Bye | 1306 7 ASCH coe wed oethe or negative Tan 7 [PBs [ote ossi6 nicole weet Only posse characters Note:The same decimal [Link] weed in ASCII as wells unt-ode for Enis character, 4) Boolean type: “Tis datanpe is introduced in java burt was not present in the eavlerlangunges Tike €, Cer, This datatype can store only two loge! valies namely true o lee ‘This type is returned ty all relational operstors. For example, A>B, ifthe value of {ArSand B10, then ae value will be returned by this expression. This datat2 ‘Fequees only one byte to store data, Noa-Primitive Type 1) Classes: Clas i 4 userdleGned datatype which consists of data members and fnethods (tnstons| wrapped together. These methods ean only access the data ‘This provides security to data Arrays: An array can be defined a8 0 nemed, nite, homogenous, data stored in {onocculive memory locations ofa computer, An arrayis an exellent example of ‘Eohved data type. Aeraye are aloo lmown ax subecripted variables and the Ginsneions of te saray ave determined on the number af subscript Ke uses (0 ‘deny single element 23) Interfaces: Classes having certain retrictions on it with respect to variables and rrethods ave known as Interfaces. This fs used for mulipie Inheritance. _ a 1/ Program for sum of two numbers using assignment of two numbers. impor java lang.*: Impor [Link]"; clossAdton ¢ publ stati void malatrng argst)) « Inta=5,=10,Sum Sum-at yamming -4 ava Pros a ur unre a see m (argettypejvalue; _system.[Link]( The adcitior Example1: Conversion of integer into byte type. sence A Reete {PE and Bis of byte type, then type casting wil be necessary ys ata to convert A into B, : ? ovens OUT B= (bytelA; ‘Bxample2: Conversion of floating point to integer type. multiplication and Floating point data consists of decimal point, whereas as storm adition, sublraction, multip contain adecimal point so if we perform i ich will perfo ‘The addition i:15 teger type does not igits after the decimal is of float type and D is ‘NYC, then the value 2.56 will be rounded up 2 ry this yoursell Write a prograa wh ‘Brision and display the results. VERSION: another. There are (,2xample3: |. TYPECASTINGAND CONVERT sata from one type to anoth * Let be offoat type, bbe ofbyte type, | jon means converting type and d be of double type. result=(*b)*/ | In the above exam higher data typ TREBSteubexpression Mb, Bis it werted to higher ‘YP compatible The resi sic al ‘data type is converte innihen 11 idening Conversion: hens ike data types are compatible, then such ty, Geng conversion takes Pace. ciecrcementtenae be of char type, s be of short type, i be of int Conversion mead rypesof conversions. Widening Conversion. Narrowing Conversion. 3 Promoted to float as floatis a higher datatype and term is float. 'eger type and cis of char type as iis a higher datatype result which we get is of int type, Inthe third term, dis of dob type and ais of short type a dis higher datatype short int plong—>float> double rca donc ere ands of shor yp es of double ype byte—sl Kow, the sum of results of frst term and second term will be floct as'float fe a > ‘igher datatype. The sum of theae two ferme wll bedded wit Ne she oe widening the final result will be of double type, is jeratore For example, a byte type can be converted to int type. pera ‘An operator isa token that makes the compiler take some action. Java has atich an int can be converted to float tyPe. Set of operators. These operators can perform operations on data and ete | ote: Char and Boolean aze not compatible with each other. data type it THE" ate diferent types of operators ‘Rarmznng Comvenston: a higher datatype is converted lp Jowes Gala VP re soeratora a Karrowing Conversion. This type of conversion does not t Raidtloaal cccat Rea ane cenen ies This is achieved by, Relational operators casting: To create a conversion between two incompatible types, type casting Logical operators Gtemal Assignment operators double—float—long— intsshort—sbyte _Bitwise operators Conditional operator SS new operator Narrowing tte yet at peo athe 4 piston (/) operator ve tetoe that wot bia ars ar ES re operators that work) os operator petforme division works on eo operands and hence it. ny ir mea Ore ean antl MEST miners wpa este et eperand by the aeeond andes the SueLEDL #28 nee cron ty Se Ue See Seige ester Ae . Fvamples: FA10 and BS and we perform OvA/B, the eeu willbe 2. se called 5 ne table bel Session oper sno 5) Modulus (86) operator Jreenae vere ‘This is also a binary operator. It ives the fiat operand by the second and finds The remainder as aresult. ample 1: 2%5 gives the result as? ‘Beample 2:1{A+9 and Bea then APB ges the result 281. Relational operators ‘his operator comparea two quantiis or variables and decides whether the “Gules are equal or on ales thanor greater then the oes et. The expression {Bice te rerulta caer fae, ie expression itu, then the value of elation ETand ifthe expreseion sale the value of tie relation i 0, These expressions Tolp us fo take Gecisina” All he relasonal operations have lower precedence tSenthe adam opertore 1 ros or aiden (2) OPEN serait ama o werkon on [OREN | MAEEE Teas | a Ts a snares and aes the ata posi RES REWSER Te Tata We checks Whether | 1030 Te compares segue namie es ve the fest expression | whether 10 eee —" ‘rte than the than 20. an ipcedeemsecopenirk en ANE AREATAS Seeding.” |seoe te ea 1 EAS Tabu and we pv ats onthe to umbers and cee 54s = a aT | a TO — Fy Earp cieBant beeen the fis expression | compares, wheter Sess than or eg | 10 ees than ot sehracon or mas () operator 2 ct fas ataye by ~itwrks ns unary - mele ines testa feel fe anal Bestia anesthe, iter nto eran esubtet Sesion ‘Ste the rent he fu eras clean tent seus | foie a a 1 F6-Send nay minus mds on then the vale ofA Becomes 5 the fee expreion| whether 10" ie 2. WA-SandB-IDandnepefors CDA S eeaer tam the | gar than 20 rhe opemor-nwareng oma opeand a tea anny pe secmndeapreatin, [and returns the sndpresticrcatan. setts 3) Matipication (+) operator This epeatr sulin peas an exten was on two opera ‘soit isa binary operator. or 7 Example: 1A 5 and B-10 snd we perform C=A°B, the result willbe 50. ——a | mar nee { a — SreaaT I agensin [compar whether ust te | reson she cond | | efile. 30 © congas! whet sed returs the Berean i apa evahe or das wa be there ey te qin eremorns te See etums fe. THOT compas sshether 10 is not gual to 20. and Tape oe rsiabie ed wits ti oer. hey ace Tic cqun ft retana | returme the resutt true elee it returns | a8 fle pie | tepid Operates: tagcalopeaars ae those, which can combine two or more relational expressics (Sinem menmprund epresin. The lege peraiors that can be wsed in. Js aD 8s 30R I gnor 1) AND(&S) operator(Short Cieult AND) AND opsrater may combine two or more expressions and is true ifthe resul each fe expression itu, anyone ofthe expression fale then the £2 ofthe compound expression wl Ye fle, This aerator is also known a sh Creu AND because the fi expression ease ten the cate expressio® ¥ be al respecive to whether ie remaining expressions are trae or fal. © ‘ere is no point in checking the emsningeapreseion Tis ses Une ‘BapresslonT | Bipresaiond [Revolt ° 2 ° fo to gener th 7 T 7 or equal to 20 and fenvime he reste T 7 ° t 7 T Beam pereentage>=45 ff percentage <60 “me above compoiind expression fs true sf @ student obtains vhe percentage [Betneen 45 and 60 ke, both the conditions percentage>=<5-and percentage : hedasea atta ) ccantsenmnartguinonainst tj tween Inher cm actos Phil eee rs RECN SSIS EE rare ett | tt ete ee | : i ung mot Amgen tet Reaenecatsmaince Sci nD agynantestome ay Seionetenae a ead Seca ‘e semi colon (i). sa atonal ten o a ening cman sane ra aes aan ee casera De : ming ck can ue loa ear noaertamng = ‘identification. t renting a new object ‘reang a caus mean cresting anew datatype, A class tees: Goce a dust created, an objec of his caso can be ‘along ag Syntax Casrameotpamesren Cassname() wer, 1+ Classes the clas whose jet we want to ereat, + obinane tthe aame(aser dined name) ofthe abject which we want 10 3 * new is the operator whic dynanicallyallocies memory for an object ot ay have a numb defined in! 2 « ) Sesemoutrntcre eerie stented) loss Area Dube static void main(String args(]) Reccangle ect=new Rectange(3; rectisplay(; je of the nes. Ars, va pronarimina 435 wr? ee rreaeader branew BuffereaReader(ner InputStreameader(System.e))s system out printin( Enter the velue of er ngth and breadti= 5 emnwmemmtuntrity secret ahs ep nine sth pee enegecparseiereant Ponca and SB aga einen atnesgeeporsetntonreaatineO)3 eves memyeitrabemaPtametce em) Seat aa eet rear ygthe comma; system out pitino , Rectanole rectenew Rectenale(); [Link](); ‘ream rect. calelate 0; ‘System out. prnencarea of rectangle="+ Area): ater the value oflengts and breadth 5 10 ‘rea of rectangleS0 explanation: In te above program, we have included ihe API packages fo and Tease have inchided io Deeatse we need the BulleredReader clase and IE gttouslReader for this package and we need the System class and String class from the lang package. Inthis program, two classes Rectangle and Area are used , out of which Area is the main class ‘Class Rectangle contains the data members length and breadth and contains 10 fnethode getdsta) and celeslats), Tre method getdata is a parameterized method {D which fo parameters lenah and breadth are passed and are assigned to the dala membe-" of this class, The method calculate) will calculate the area. of estangle and will return the result to the main class. > ‘The class Area will ead the length and breadth through the keyboard using the FeadLine) method whieh sil be converted into an integer by using the method parselni) parselnis the method defined in the wrapper class. publetaticworemsigstiog ars) ‘The object rect ofthe rectangle class is created using the command, hntlobe9Arean0; Rectongle rectanew Rectongle() yt 2 « vate et retary Senta: rea ty the abet rect oty me RecanleCast ss. icalated pamned 10 ‘class Overtoad Tent ite en ceo Eee pointer os) ote: be converted into an ebject Spe BY USINE wrAPBer denble=0: primitive datatypes can Be o> BufferedReoder brenew BufferedResder(new TET Smear ERE pene tt my SrpuStreamReader(Srstem.n)); 2) the inp eomsmand 6 sain reading the data the catch by try * rerun ne Ror uit moe etal « sptemut print(terthe valent oe Ir Integerparseint(brreadtine()); Method over jaown as a method. A number of meth: te aca ewe ae to A Rriletscn—_grlenostynincenute vetoes - ‘wath the seme name cat DE. sore These methods can have dite ‘betntegerparsett{bereadLine()); Serta hh he a pe my aloe eiferee eam etna ne eleentpeime —_sptemeutpdhyEne th te cat esc cemee eee icra ergot mee ei ‘[Link]. printin(“Enter the value of side of square: pager tron fthad oveaadns | enced casi t . sre xt nie > Cae aresnen re Feipaae |) Shumate etre sare axl) eiieatiat ete Spamoct pint areast cesar Avot La: | Beta hate A) ) Beate) : retun(sie'sdey 2 It rea(n length, int best) « a {ater the value of enathes ler the value of bres Inter the value of radivseS ses seroma, exc fel fetes eects me OS Overloading fe ae acer en tn OP CE eerie tas uty cated thei st Seana | ot parenele arom Fgpe able andthe ren renin nis se eee It i not noeeseary to manually call Unis objec Se ogo ection oh constrictor a same athe cas9 A= : pesmi saandterctumy, Anumbe ofcnstracars can dened ie © Gon, TS Sor Con have et cg men vgn ae LOT RU re afte parnmetere, Tete conerscors 25 ee Be er et 0 en oc “Ts is known as constructor Poa jmapnatin pees ee siren numb of Fassel one othe ways in Which Jara PPOs revnteoeen pobmorphien Berean enone tcmebotreineman TY rogram forasation fconsraer oes ser teant eps en .y rogram forlustraton of constructor overloading, 3 vem an cpendingn evapo nei obese tented Spetsavalena*: rescont etrectangeere cea Fe oe spent ning este Be eee nating ite) 4 Ine, eat, rend sextet ee ets: y rapldocler) weal t recuse: tats, oem ren re of cle"are Acai ) “Te met rte aac eda) rnin) u sees sump Winder mo , retin i ae eatin) Inthe stent, Stet pint Treo it age) eee + t ole aslyrectt setuid 4 ' Srotem out pint Area b jiteArea of rectangles" length“ breadth); il be calle, Fry thie yourself Weve a program toc Nein method overloading slate the perimeter ofa rectangle, aquare and tangle sso! 4 £ potest id mating 50) eet 5 sfereeadert ne ener . wast Reader([Link])); Tnpusreer yy © eit prindn(tEnerthe valve ef enath="); acpesome(read re he eeepc eve ret) Sepesmetntcatine: Syren rer hve of 08 ingyen) Symone no ict qr Pracjugovliedne) y ‘cieneeeptin ox) « , emote ‘rea ereretone nent); rea arecteennev ken), ‘re arecquesrey eal) sreret ply brecce depose) aresqure dove; Enver the value of lengttr2 [Enter the value of breadihe3 ater the value of radius Enter the vale forse af squares ‘prea of recangle~6 [area of ercle-60.24 ‘aro of aquare25 ‘Explanation: In the above program, we have defined three constructors with the fame Arcafsome as elasaname having diferent parameters. Ie should be noted that aconstructor does not have a return EYPe ‘The fiat constructor Area) has one parameter radius of type double, ‘The second constrictor Areal) haa one parameter sie of type int. ‘The thnd constricter Areal) has two parameters length and breadth both of type ‘Soon the baal ofthese parameter, these three constructors with the name Area can be differentiated. In this ease, the constructor Area is averlonded and depending on the parameters the required copy of Area is called when the abject is created, ‘We use constructor to initialize the data members. ‘We can pass the values for parameters atthe lime of object creation as follows. ‘Area arerectenese Ared(b: ‘Area arecreleonow Area(], ‘area aresquare-new Azea(] ‘The result willbe caleulated and displayed using the following methods. For calculating the area of rectangle and displaying the result, we use the feloring method, void displayed ‘ ‘System out printn(Area of rectangles“ length'rendty; } For calculating the area of crcl and displaying the result, we tse the folowing abe playing t, we use the folowing void displaycirctep ‘ ‘System out printin(Arca of crclw® 3.14*radiuetradi , For calculating the area of square and displajing the result, we se the f or cleang a piping It, we use the following ‘id displaysquared ( a Proamnning., ve: Troan hacia awewantto create noth © netengths cise ean na torah seo ng) Rot) ee ogame etter a oe evel oaresrine ie a 1 erie tin oot aD jis not necessary cane interes() tree, Meer + esting 1068 is Knog 3) see anew class om AF CBSE hen refem — ¢ eer eating 0 new CASE OT per class (often. ree, retuin(lngth*breadth); ne cen te can get caine nt Km y | ts seuss pom 8 Gus nesta ence EET edu Genel att OF gable Me URES nc extend | age es alte wre esi ett tags oe ith nepaacistame extends SUPT BedRoom(int xn ysnt 2) 1 ‘ pas centers ven super pi , feo 1 tau 6 5 (Hrpsetaentaen Tia "Sage ibrar reurneninebresaththelo 2) eel nese > 3) owe rte , ; boon . dato age rare eny one vin ited om the super st c of single inhe ny abel = ‘public static void main(String args{]) * ‘ taper ttoom cane BedRonn(t41210) waren od} areds (resume ohana: Eyaemai pin aREAt="areat), 4 Benatar umetnn ame ) [ss] Same imams 02S hrnce Volumei=+i680 ost s ware Ththia pe ofnheritance a subcina is derived fom th aie derived ror the super class. This subclass Eected an an intermediate superclass. Another subclass Is derived frem this Spm Fae intemoite super cass, vee mans pans Bao THE vara, ff rogram ocelot ing aetnbestanes co en a ac on ne subs Be oom 5 ccm et nO Bl as tent) ss, as constructors, § . wpm acssreenmsttngilS | sytmutth esc arate in ep the Besos lags, 18, etion i dene pass the ale 20 y se the felon i Foe conairic, HOE YOEVeNSETVEEO segs BY e fetter syste out pint Voice Type Cer; sci dational met eronmands th eer eet ei cle tale cn Reon hen Sut eens oe ciate nin clas, we create the object obj oft ‘BedRoom Class and the construc on ‘Maruti seme i rete ine foo, ih the lp ofthe variable ob cr a efi Bde cas wih nels Teele em 7G 3 eo 2 Mate tsberadee ‘ tera set > leds Maat ereds Hon pei aratsoo9 Ssemeuponth oa etl 0; Pier spent © S Semone eke La Fee TSaRes Pee sav msingstng as) wo "i hee rat ram forH 6 came Fast WaredTinigi Seveneevoe> reper Jovato."; inheritance, oi! be Sees: aot yi a —_— ¢ Vouk tee Brand: art Smartt mete) ome t Lesposadss ener ran cnr nim a | Mara, Tae eos ofthe superclass C2 superted by the intermedia W833i Skt eouecgiesaeraratene.: uemacnn Sees teem oreceg tara: fe einen 6 ie ne ey be cla (a Med stom t sylerbia tabertace ar ope of nherince, Amumber of subclasses are derived ffom a si soperclt. a Gop) a c D asetasy | | cutelasy | | (ubelas) Fire 22:hertelinerance System .cutprintn'subject mors print subject marks); lass C extends A inti; vedaetabemty > hey void show) ‘System cut printo( lab marks are"); ‘shire a 38 wipes ) a ‘ ie Esai > foisasniov0 y neo { scinjrto0 sysem ute supere="¢e Ce Systema gin Supery="9): Ue a > aoe ee diss overeat eb asks are 50 « fate supers and B24 C27 estat vld maln(string arge]) the shove proms A erate tome nt tae — ene ‘Subs1=new Sub(100,200); a ercietne amethodin the sublass whichis defined int sL.p0¥0; ea we ned ted © ige pahavior of the method. Under $0.) . tegen Tel change the bah of SE Saeed name ofthe meted, the parameters Gracy be sue, In thal cane, the method in the subeass wil metre a ava support rantime E00 nd the return QP) ‘be lene 1p eregrmtormathodoveriing Super y=200 gissioe [Bxplanation: Inthe above program, the method display ie oversidden. Iie defined es {nthe subclass as wel a super class, This method lias exactly the samme syntax r inborn the classes, When we give el tothe eixpiay') nethod through dhe object Supertiet3) + A which isan object of the subclass in main) the version of eleplayt) in the t subclass Is inroked, this is 8 pointer which is pointing at Uve current object ol Current cbject isthe one Unrough which the method is invoked Lainey . finalize) method ‘A Umes an objexe may held 2ome resource and it may be destroyed due to some faction, in that case, it ix necessary to fre the object before itis deatoyed 29 Sinlize) method wil Randle auch A stuntion and ensures thatthe resource ie Syitenautprn'Supr win ape at ime tie pub ae vols maintrng 292) Vaisie only ia heey same clas ad Number_Objectsobjt = new tlumber_Obsects(; ponte subelasses ofl Auber Objects obf2 = new tmber_ Objects); packages ‘Number_Objects obf3 = new Alumber_Objecte(); | anc oni Number Objects obj = new Rumber_Objets); me eT pT Ta ene, Stemubprntn Number of bets created count); | asses of the st —--OUTPUT= we eee 1: \Program Files \Java\jdk}.6,0\bin>java Number_ Objects. lumber ef objects created: # —entrol structures Often iis required to control the exccution of « program ina particular way and it becomes necessary to pe he control eifleren parts ofthe program, Ths Static ‘can be achieved using control structures. ig package: ‘A sate asia it. arial which belongs a alas and doesnt belo objet. tis sntiaaed oni one its ale oot loser every eal, Ne ae atte ute eine Po 2 aang Ed 9 MANE etions depends, rurnber=tntegecparsetatbereadLine)): if number > 0) _systom out. printin(Number is postive | * Somengeeg te ge fe ein 2 tmaut prin esatamentsavays vec Sea Sexist pen eect Sta out printer: | Bee ) oe Bier ete ie mer 1S seo stent ese pt re sotto Pine is le etockot sateen then the set of oe exes ii Ce Sa ay econ to Be pate be Spine ‘enon egress) ( , _reroyramtochackoietner the entered uberis postive, | trvonprass Pipe gs cts Check « ble vida Steg rst) ‘ iematere ‘erect beaut : outstremeade Sy em in syremeutpntieataraueon ere Shick ove witen ‘Slipped. If oni his statements always executed. mead bt bowrewer ithe Me them seit th cae we the parent Ue n Jav program to check the elgitility of person for voting: bras Try thle yoursel [este Incas, condion a checked iit is rae then single statement or eet of cena era fit ae Ucn tne steno osc of Rtemene Senin eve lock we ceutede Suntec [Link] ‘ ion) | sateen ( , Program to check whether the num! Tomato chek nhatnerth nimble poatvernepntve, Jortfvalana.t: |scheckpos uberis pasive! © aan et tn > 2 eaeretin 8) © semen: pence steretizay =e > et eee | imeem ‘0 Sener ite a teal” ul ‘Matron progam to checkwbeter the entered umber i eve OF © Need tanifeteoent iewrten inside notherifetaiement then iis known <8 {fetatanest Ts flowing variation ia nested atatements, are alow? syneax: . 1) iftatemen within fk ‘eondona) ‘ Heanaona) 2) irstatement within else block iljconaitiont) ‘ statement; , else ‘ isfeondition2) statement2; ) 43) statement within if as well a else Block Mfeondition ‘ infcondition2) statement]; , ele ‘ conditions) statement2: ) 4) a elas statement within if block ‘fleondition!) ‘ itconaltion2) statement}; ene statement2; statement enti " seonion2) statements 7) ifs ack nin icon wells lee ble sient; eoadions) este Meandint) eanationa) ( statement statement; | ) | ' lee ' itfoneltions) ‘ statementl; statement? , else ( statementt; satement2; ’ ) Mote: We have to be very careful about braces in nested ifelse otherwise we may not et the desired rem | Progromto check whather the number is positive, negative or zero using nested lirstatement. Import javado." Import java lana. cs Cedars ble sate void main(String ares) Intmumber=0; Buttered bre ne Bu fereReaer( ne’ nputsreamReader(Systen.n): ‘[Link] prntin( Enter the value for number foode to be executed iFeondition2 is true |e inconditional enpression3) ‘foots tobe executed itcondition® ie true 1 ase ( I foode tobe executed ifall the conditions are false 7 programtoillustrateelse-ifladder statement. eats, Ee eea , soa See >see) eae”, ube tte main sting sos) |v sier tran ufereRend nips SEM. reopen te savetork= per tbe value for number” | w c xsIntegerparseint(brreadLine();, fetes ret) ' Try this purse fet Tan ncaa gee ang enh F smartest 4) chelate stemeats ‘lee M(x ==20) “hie mus branching statement and depending onthe condition the = Hstementa ae ested system outprint ("Value of X20"); sytaic + condnal expres) ‘else W(x == 30) i < ‘fendeia tn cod Pein Etre 5, aoe burrs ste , lee tose ieondons)expestion2)

You might also like