[go: up one dir, main page]

0% found this document useful (0 votes)
44 views118 pages

OOPJ All 5 Units Ninad

The document provides an overview of Java programming, including its syntax, features, and principles of object-oriented programming such as encapsulation, inheritance, and polymorphism. It discusses Java's advantages like platform independence, security, and robustness, as well as the Java compilation process and naming conventions for files and identifiers. Additionally, it covers the basics of classes and objects, along with examples of methods and variable declarations.

Uploaded by

Ninad Lunge
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)
44 views118 pages

OOPJ All 5 Units Ninad

The document provides an overview of Java programming, including its syntax, features, and principles of object-oriented programming such as encapsulation, inheritance, and polymorphism. It discusses Java's advantages like platform independence, security, and robustness, as well as the Java compilation process and naming conventions for files and identifiers. Additionally, it covers the basics of classes and objects, along with examples of methods and variable declarations.

Uploaded by

Ninad Lunge
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
You are on page 1/ 118
Usrt T: TetRomuctreny To SAvA Doteoe /o9 / 22 —+||_ A simple Tava param * [class “Test f public _otwtic void main (shingt dargs ): ST -— t — I System out. printin (“Hello orld ’”)- ie ne - isa | class Demo x ! I t — Tava Development Ln bit | ,ieRe = tava “Huntiwe Oavivenns ti i Integrated Environment TIL functions are called _‘«| 2 in Sova. = ||_ System out pvintln CéHelle World) fer “ciges ybjpect | li = 2 = Mies Es =| oc 3 le i912 Cre jarne Shoushup 1985 Tava res Goelhon 1995 Ret 6 Guide Nan Rossum {491 @ Sukh Fython3 2008 = Shrikrupa i eee ee <5 Eoterpreter ‘8 Compiler a Dateo¥ /29 /2a SLT - Sust in time _ — Components ef lava Fecha g IDK (-se —— ay ed va APIs / | T Claas Hbvevies Scanner Fath dightbuton of va technology provided E J y Oracle Corporation. ) es > ¢ Tava “vital ane Cadb) anil the fave Ptatares (Javac ) | a working S| Ivet: : ! OI consists of either interpreter lay 2 (class file) sha byte code 3 f an TET crrmpilev @Thet ‘6 ¢ oa ia tipi ot the: Slava canal : + lava comp! S an IP __llexecutabte Ber IS Oe Shrikeupa . = |» Compilation is faster than Interpretahion I> Platform independent , architec tural! Sete oh meuta Dote A veel tnghu chon, desianed te thes executed: + SUMS. Z S || Tava yebim ventime system which is called aS 7 | @) Byte code ts a highly optimised) Seb lof In Tre . | I @ wer is also Rnowiitilas the interpreher sof the 1 | bape code i =| aRe 1 @® Re is a software package that previd jove I | Tiglacs~ librovies|TNiet and obey Componenteuvnae Tt are reguired 7S run java application aly fo run, a ) | mot te develop =7\| Teva Compilabon cucle Example java class Test aaa Bi <'7dsers > Ca Documents | I i =e 61/0923 /Decumentsy Tava Bameles, J _ Ee H oleceeter, ==> ¥jave: Tesh Ive Tt cernp ile Native Ne code Sheimr(s java )loadey —» (<0 )—> Output. — || Advantages of Java - Qsime Eh tsa simple lenquage: Because Tay (Simple s f Fi ntax and many of ‘the object inherits C, cht Syntex a ny od — — ieaied feahves of C++, vnost safe ve : | prog vammers have little trouble learning Tava. j Piece Everything ip an object in Jay s | thats why Tava the purest _ef object orientedy _ iT J a io . I lanes The object model im Java is Simple Grey ie t ; : | easy extend a = awfe-@) Secure : Tex T+ is Secure because in dave , T¥M Paes the execution of the Byte codeal @ Plotfhiem independent / Architecture ¢leutval compile once | yun anywhere feat i pee thyeugh a _preqvam Called Selve problem Page No.. Date 7 Sum of dit digits: Hinclude int main ©? { ink num ,sum , a; scanf (“7d Enum); CU pater anu Iheqesan a) printf © he’ M 7 1 l mums num/io ue 4 post f Uf %d MY, cur) hie. hegoverd Page No,__—___ vs lecal os static Dotet2 Joa /aa Tnstantiating — in Object + Poa 5 a two _ctep process must declare a variable: of class type @ You @ You must accguive an actual physical copy ; en ae cae mm 7 of the object and assign ik te that variable using Peet oncra tons : ‘ The ‘new? operator dynamically _all cates yoement ect and _veturn _@_ reference to tt Exit Box by - b= new Box Coys12) Setters and Gettevs: © Setters and Getters are Tava Bean Standaeds @lestance Nay cet through setter methids! 2 xample clas ad outa b Getter Methods! Shrikrupe Page No. Date 16/0 9/ == Rules fer naming a Seva file 2 F 3 q F @le can have atmost one public class in one java file. If public class is present then the file name ‘should wealth with the public _class Be class Circle §... 4 ic class “Frectonle Ff - -~- 4% class Square { ~~~ L Get. Rectangle java should be fle name | @UH no public class preséat’ ; Hyen lithe I enany n with any ma St | be nee ne ards | @© Cain method con be Sn any class — | teva naming standards / cade conventions * || These are the Sun's ~ecemmendations fer moming classes _, interfaces, variables and metheds. Being a _pyoqvammer, we muet adher to these standards ww || eua (a) Closs name ghould typically be nouns. = first letter should be Caphiblised ancl if lett werds are there then follow Camel Case Ear Printulsiter System ct et ethods: Ss = @® TW must be lo Verb -neun form Bat creditBalancec ) Geld Constant declaratien ivate state final i. double PED SI bate @fixt lettew should ee in lowercase then fall, les. iorraal ceamel case vu f- & : geteslanse’ ie ele late Aveat?, char At he €e> Varials! es : “i @fivet letter should “be in lowercase and then — follow Camel Coase style a Ex customer lame, permanentAddress, balance, S) Constant * © Sava constants are created Navieble state and final Tt ) = @ They should be namec ising _Uppertace oo lel x hou ; tet ai underscove as ber | x: private stute i 3 clouble taht ee. i =| keyword | CResewed ovda). | @In Taq 1.5 there awe 50_Weyoords @ They hore a special meaning enon Compiler. thats caihy folso Know as resem } Words ‘ @ They comme be cased as an Identifiers Shrikrupa rest aignificant Att + 44a — Compil Page No. Mantentest cleniticane nas nd LSB ‘Least signif cant bit: Dete. dentfers : = Gane gen Ba PEGS Classes, interfaces, metheds and Siaviables need identifiers. [nomes and these Tames are called a = ~Sules | @ Identifiers must start with a # lether [ gnderscare ove $217 i+ Sconnete Estar t meena || number chavacter, jdenti fiers Can a rn of \etbers ‘aia S and are Case_sensi a . £ Hers eewords as identifiers. lull es | Caault —_ 2aun vaeT False? I a —_—_,, “Integers Fleating point 1 at £ Y [ | = fleat cleuble Lyte short int long char | Shrikrupo | Every operntor posses pricrity Cprecedanee? end acseciativily: Only Assignment eperntor — PageNo—2 as right te Left asscciahvily, tee [= Rimitive type [they axe Se boolean || Hook , double te B) They cam hold excietly one Value of i : declared + ah 7 ; 3 @becal variables are net _initialiged by de foul y det at a time. wiheveas instance Naviables are inibalized to © | eve) and bool ean false. ___ | = Reference Hype _s @AI_ non-primibve data-h are hnowh as xe fe ae the address of an | Qperators + don en tonkl Unany © Single a ethich hy folat operaters ™ Compound Assi except aalgnment a operates ave. ment oat Dote__/_/ _ Claesificaton 2 | eenbry | Asithme He Reistional eNet j [neat | aS age oA Fi C2 e557) ee) ~ T I | 5 : + oT Unary Legical BbNise Assignment : s 4 | es eae Exe thel) hye ee - i | 3 Ja ¥=,71=) é svatetxanpie | gtaliel Gisidcnain (3 Sting 1 on s3)j 1 a i | = +G@+b)), = 22 T —t I = + Ca-b)) = 1 pi | Cobh = 785) = Caves > 3 | =) Cai eres = ! A operaleys 2 ” M py awed a als > AS bet Buse Co net att) —> 1 be lL syso (“2205 + =-0), 18 S ak hee ae MGieys Ig syso (“ras + Hal, ae _ Bca pee Gass epee): ais Soe — bo Neon fla = BERLE) =o Galne ——— ayso ( Hike =" 4 flag), —* fale Shrikrupa ~ % %. ce aligned left shift Cmulply by 29 ! y > signed agne shlf emer aN Zc PI Urs} ged SsAvias it betel | HS opevater tt | ee ee: eg F | Pen ones + Caine -5 Bee esc a> =!) Cole) tae 5368 T6909 | MRelatonal Operator rere __syso (“oc b =" + 6aeb)) L Il syso(“arb =" + Carb); | i sysoC“' a<= + Cos=b)) + Car= by + (a==b)), = Tit ¢ eee ter sysoC“tue & & tr syso(*S tue && fal => o + Gry k 6& false): eee | syso (‘false RK tue =e = 7- f Rey tee Aolse iS tue), oF } sysot“folee 66 fal © Chaise 66 Clee al Syso 66 teu Hetwe? = 9! — _— Ben S ae ; hue" = 0+ heed tue nn ee I false = ''+ Chel) false), = sxg0_( tse Lay : false t| hue = 4) Calon il ducj) ale “( telse IF =a a SYso fae | false =") 4+ false raise x cs) Sok Page No, Defeat Il 7 Conditisnal perotor [Ternary operator Syso Cif great Cayby =)! Carb ZarbI), it ae + =e _ I Aasiqnimnent= peevator We operator FT Shrikrupa Page No. 20/09 /aa : i } ill Conditional stabements | pecision” makin stotem en Simple if! (a) Syntere £ Cenpression) ae Ubody of \£ @ wlvite a | 57 diseeust on _if Cpucchase 22000) w Aiscount purchase # 0.05 = 5 a t Purchase ~= discoust; stemout. println 2 (cane =] %). (“Bil amount =" puschageae pot? Bill amount = S35c06 aa Page No, Date ea ae _clze statement: ) syntax! he) Flewchart = || \$Coxpression? ae i : ie ZF bloc ts J 3 Lig week | ae Se W TT Heise loc [text of | iL | xample? Write a Tava pregran for a elall eihich is giving 5 J. discount on any thase and additonal y 4 < discount on a purchase of fs-20006 onal above f Cpurchase >< 2000 ) seount = purchase & 0-06, discount = purchase & 6.1 acount Bill amount ="? + purchase): Shrikeapa Co) Example Write a the shident based || Barks SI-\00 = — ‘Sout C7" Pasay, | || Page No,__ Dote 241 /089/2 2 Slested_ifrelse + Synton if Cexpression 1) (sore st if Cexpresion 2) i 4 |] else body of inner if | Ee i I eody ef innerelse VE Compvession a i bedy of 279 if else i ! 24 else 2 Shrikrupe \ a Shrikrupa Page No Dote__ family is allocated Only integer eres NG Sap reaston ane) Inside seviteh cases \se f pebreys 2 ee among the three fumbers is!! Si tase) | ersy sevitch Cio ich Case Statement ntox - 3. ev_ expression? f a ¢ constan x nbegey ae x tbedy ef case! ongtant 2: [ of _case2 Hbeak optional default “body of default Hopkena) Shrikrupa Break’ is optional, If ete den't put break aa jftoe the cases match ail the | subseguent cases SAN. Ge executed one by _one..C falldoeim 02 Check) Junem either break oy end of the seritch cas encountered. 5 te_accept the @ avo _preqvam jks season adex and print TU, tn for fang feop —> Leop Page No.__ Date 28/09 /2> Counters r | @ Inside the switch expression the ve must be an expression cathose —vesult evil bev byte ebemtemeians long or char, | @ Im place of case Values there must be bute shoyt int, Ipnq or chav Constants =| Be chile Leopin: @ Default nec eae ac place “Tt les! the lasts. casen statements « TT O} foc loop |_cars 1 { forCjsitiali zation: expression q State me } a increment /decrement) Is te the vepeated it ig be ther to Shrikrupa 7a Top (Outre per Page No, — frocess SCS __mecision C) Oa System. outiprintin (“74 ; 3 vt clull statement —- 5 Conly 5 for @ Stateme Dag Dote__/_/ Qait= Ini HalizatHon) Navionls of fer loop + Absence of imit | condition [increment ! decrement po: Che cle can leave Snyene ov any tb ov all ther theee parts of fer “empty fot 7 fort 54) Sustemout. priatin Cis | if Ciee to break Use ef comma w for(int i265 j=5 5 lei Ayetemout peintin Ce statement in ons of the for the next by a 5 ¥F Can be osefat in linear seaoh System. out. prinin Csum ) 5 Shrikrupa —~==epending ponte output , we use © ASSEN loops , — clo. of itteraton fixed —» for loop \ + Date 27/09 = wink zed —> Wlbil® loop. ~ J (a) sybrtax: for ( type cee ein an eC } tu Seee eas to be repeated @l uhile trop: (2) Syotan : 2 athile Cexpre: nf 1 Statements te be nepeated ext st. | } Pant \ te 10. usia whi Print te Le. using whi ith while Cizsto) System out puintln Cp a res Doteaai eae do-while loop" @) Syntax : clo /l_ statements +e _be = 4 euhile (b) flowchart’ -— i | Stats. repeated xpression), 4o be| repeated Co) Bat jax import java uhl Scanner, Test { public static void main(String LA args 4 Scanner _sc_= net! Scanney(Systemsin), boolean = hue dof System. outsprintin (“Enter 2 operands |") —double as double b= co. next Doubled) so netDoubledcd, Sy stem.outprintin (‘4 Enter operator Cr, = Se MD) Cex SC- next C). char AtCo), 2 Cheirene: Shrikrupa Page No, 1 eae = é Sag i double vesult = 0 | sui teh (choice) y tr case '¢! : yeguit Sark y ta break cage {-!' : result sack, break, | case '*! 3 vesult =a tb} break, 1 Of + vesult =a 7. b; breats; chem. out. printin Cf8aq Tnput lJ} Sout (“Result = "+ result) [ SoutC Be you wort tf proceed (4/n): U)e | choite = seynexF¢). charAt (o)- te Ceheice == |“ milasi se haieer== Seed, = flea = false . 4 while (faq) v0 a pb Juctp STATPAENTS: (a) break | ©) countinue (ec) ‘return Shrikrupa # break ’ eill break The nearest leop ¥ “Cogntinue’ ent Continues crith the next iteration: ola | slava__supports a these three jump statements | Gach sintement transfers conbe! te another | it part of your pregwam , _| \:| break + Ck Geen | OT terminates a gfatement seq ueneo lone | seitch statement, | @ Tt can be used +o exit out frem alesse) f 2. | wnkoue : Sometimes te continue yunning the [eocibutreh= processing the vemainder of the code in ih body for fis portialay ttealion (eo meet nace coment performs Such an action] 3.) veturn: + is used pa veturn fem the method and i+ causes program canbel +s back te the caller of methed Pent | te 10, except the multiples of 1, fic Cink = I [Z= 70 5 jew) Count nue System - out. printin Ci) Shrikrupe Some crasstcat ExAciPLES* for prime numbers Dae 4 class Tesh f boolean _isRime€ inte p | Aeose Text int find Peetitals Cink n df fono) d=nvhio rev = yey #1O +4. nen /io j return vey: Shrikrupa Page No. Date = public static veld main (string £4 args) § Test t= new “est © _| System. oud printhn C t. reverse umberC3 87601)},| 5 ] | Acrosheae clurmber=s a. Was iatotlona clath fe Test f s si Doplens Dedemahaes Geen | Toh den = ny egush = 0 peaeeeenees | while (nro) | ude, | n= v/ie; Seis eshileCn? o)f d =n Alo sum = Sum + Unt) claths pow Cd , count); m =n/io - if (eum == temp) f océfarn tres 7 4 else f veturn false; Shrikrupe atic Noid S aleiseans) ae axqs)t Tegt t= new Teste), 0004 itt) Pagers, f <2 ee id ati che 8 Gy) Syso Ci), Slane calulate sum of series: Ree. an eee ee st = etre int find factorial (int if (y <0) aol else ak int fact = for Cint i=1, actin Ue —_public_static Test “ = new Tasks zig int ; Shrikrupa — Outer loop decides the number of lines. Toner leop are responsible for Page No. bs pristing | the limes Dote a ———_ -deuble sum = 0 7. for(int fal, ice ny iste Sum += Cdouble) i/t. find factor al Gi); Sysosur), —7|| Pattern C# dt eh ee RE t = ak < i int n= 5 a | for(int Fo 1, teen 4 is4)f ies wi pee 0g eke, Fattern Ci23) lena <2 eet ess ae at 7 ie = int nas for Gxt jel, Kee my lee) for(int jel, j<= 6-7, jr) System.out-print Cie % 7), Sysod) q s Shrikeupa fe public state void mein (shinai a angst we on = 5 forGint t=, P<=n 5 i++) foxtrot j= 1, fe= nal, jah) f es out print (ee). ( forUist [=ly pee ty j++F : System. oul.print Cehav) Grea) “ 77)5 i Sysot) ; ly Z ethods + A_rethod isa block of code or collection of sintements grouped fogether tol petuven Glee f specific task. — Advantages of letheds+ Vy Reusabrlt thy = The main advantage is) code reusability we can write method once ame ik moltala mes. 2 Readability — Syntax cHethed cle = Preretype ao re access _medifiey return type. Gonethod naive )Cpareenetete | a ee Vet User-defined Built-in methods methods | Tex: printine) nextInto) [Bat igheimet ), find facts pow (a,b) ete] Library, methods are the metheds that are already defined im java class libwary giheveas, methods qiitten by the user are Known as user-defined methods. — || Fecursion+ eihen a methed makesa call to itself , this [prcess is frown as veursian. Bie ncn!) peepee” lass Test ) public_sintie vetd int factsGni p i if (n- t System-out printin (t+ facts) J 4 Y Fibonacci Sevres’ PonyS ey tecos =): AAP te Fibona ce} Series using Feewrsion class Test { public int fibe Cnt ia aa if Gne=o) veturn 0 else if Cn==') return |. else yeturn Fibdn-1) + fibo (n= 2)+ public state veid main anaes args) 4 Test t= new Testo): for Cint i= ae) Jo Syctem-out printho Ct. fibo Gi) )5 Gite aq java aa to solve “Tower of Hone j prtblem | Tower of Honei Hono Céi Bic ste = attono Am Cie pam am ove Ca, 8,1) Honoi (B)A, Syne)? closs Test f— Goid henoi Cint A, int 8, inh Cy inh if Ceount <5 69¢ System: out printin CA + 9 post bye Package® Felder Poge. javiac. -d+ Clescclame? «Java tates public static eid main Cetring Ef args)t Test t= new Teste, tehonsi€ 23,3) a + Hono (1)3, 35) —Henei Cy 2d) “eae Hone 33,0) Ses _P Henei (3,2), op + Henel (3/1) 2,17 - 3—> a 4 —Honei(. am zero ts ot Anchor, FRE vecarsiony kage in Tava ts used to - group rel te avoid name conflicts package a_better maintainable code fackages can be divided tnlo 2 categeries ) Built >in packages = Ui) User defined pactages | User~ defined Packages: H OTe <- create oy Own package oie have fe | follow following eteps: i. ~ g Shrikrupa SS Page Ne. Date exant te inclu statement at the into _our og Use package dop of the ff Specifiy pachage mame. Step) Gite the classes that you J le ; + J Step 2! Save the file and compile it following coromand © J [Step 3: Compile the package using 2?_javac -d + rine rs javeed ? javac ~-d- Arey ee java et “This ferces the compiler te create the aa Were =a speafics the adeshini onal ite eaves the class files +’ sian yepresents the Girectovy oF _You_can prowl ane ae =a £ the civects my fx! Create a Daelx power and include square ana Cuble _ o fle tnd Squawe ened Cube respec tively = Square. java package pect Power public” class Square public lot _qivetle Square Cint nj J xeturn nk 5 t a : Gite java | package Power; public class Cubef te int g¢vecletube Cint Tr publ veces e Cin n)} Shrikrupa = 'vetuvn NE DEN, ss a lasses tT Lanquage auppert elas: = ean ed Poge No. al ukl: ablity classes awit: abstract cilndoe 84 £2 = >y javac od i || -_ 7% javac soci G (| _ el — I ——— — -_ | [import Power. Cube x 7 ner. Square + empert Power. Square , class Test { public static Noid main (gtring 3 29s) ‘ G t Square S$ = ne APT factwages / Tava class \ | a Foe _javaslang 0 ect AN_the classes in Java PY ox Vindirest URES nhecrbed os all” ether classes Shrikrupa ehasclexte). —* Heit snare Dote IS/10 /2 2 GI java. utils Scanner! Scanner class Gan be Used) Ste react linet aes the console, a fle, a string, ete, that reads Following line 3 creates a Scanner | from the standard input which is keyboord by default | Scanner $c = new Scanner CSystem-1n); 1 ©) ova. util . Random + ay Ke wandom class 1¢ @ senerator Gey Uimaae cant te generate | eseude vendom numbers. DF you C 7 J VapCerest sequences, you can specify lipreecemeess s d + a Nalues. One way +o. do thie ie fo use the Gervens time 4 te_seed a Random objects 1 @)|_ joxia- lana elath 4 asl pe uiste a pya pregame implement ‘a dice r j | import java. util. Random | import jova. Uh! Scanner, | a | || class Test i Al ae) } I public static g | Random rd © new Random ©? y {| Seanney Ses new Scanner Caystem.in)) | while Crue) ft ant moves atheabs Crd-next Inte) Te) +15 ie System out. printhn move)» Shrikrupe Poge No.__ Date. 3 | + peintle (fe clext 2(y/n) 2). - beice Ve se.nedt- cys CharAt (os ehar af Cohoice == “ i) ae H continue j else pen break; 1 a 2 =| java: sath java. laa: Math | mport java- Math, | dass Test: {| _public static veid main(stingtd ams)f rer Syso CiSin of 45 degree =!) + dath.sin athe [fo-Tom-. Sysol“Coe of 45 deqree =" + Clath-cos (Matte is Suse (“tan of 45 deqree =” + Clath. tan (Oath ¢ > 7 Syso(“Sin inverse_of le!’ + clath.asinci)), Syso(“Ges inverse of 08} lath. ace scone tim Syso(*Tan inverse of 1+ ath.atem (0): Me Syso (pia =" + hath pt/2), 74.5108 7 Syso(“' pil4 =" + hath Pla) 77 9-13984 ne ea - . Syso( @ =" 4 Hothee ), 72 11828 a —— = a Syse (* Shrikrupa = > Stings are Immutable Page No, bt Syso (CE = + clath- exper), Syse Clea ef Be! + Hoth .toa Crarth-P)), Sod"! 2 “ynised to 3 = Syso(“ | HAWN 82S + Chath epew (2,8); Square eet of 49 ="+ ath . gqrt(49)), 170} M20 72:04 SysoC* Coueinedh of 272 !'4 cloth, cbrt(271)), 6 =] 4 a 4 Aathiabe ts 8), ASR SusoC’* ceil of S38 =!'+ lath ceil 30) | ae ee 7 4 Ly Sy8o “Pleor of §3 ="! + Clam. floer(s.s)); M50 SByso Cf yeund ofS Mt ctath. round S-3)), 5-0 =) 3 = 4 Syso(“abs of 5-1="' + eath.abs (5.99), 3.3 | ry + lath. ceil (9.7)). HEO + Aath-floor (5-7). WS: Ds ath! round ¢s4)). ws & D2. iI) = "+ dath-abs(-5:7)) A579 + Math. ceil (5-7) ath. floer 6-8-7) =) + datheround (5:79) | wi | aye metheds are returning double U yound +nethed except Shrikeupe Java lang Sting es @ In Tava 2 Sian a a pnelased by double quotes G : i Bcuicets! of type —striss axe immutable eee ak ect is created ontents cannes iii ob sc q oO | altered. 3 | (@ te you need to o__ String set ae always create a new one contains i F modification or Tava defines to peer cle called ieee @ There i a__ shin bject a | o> By ‘sting? litexal j Meme olinad i G) By us fq fnew Key word rh [ & ahi gure ey String Cfelinad UE Shrikrupa vay Page No.. Date 15/e10/22 = || String Demo o aa class Test] + | eubliic gtibe void wats (Shingts aay si Shing sl = “amit” Sting 82.5 new String ( famit ) J 2 String 83= SSamit”? P| fring 5 t : SringI sq = Deo string Or a farmit ) 33) s4)- vintln Ehar%es + Kabel) Hp _printin B17 Piprt Glerdha™. comparele C# BIT clavelha’?)); | | Shrikrupa Pt ant P in tava to cheeks quhether 9ven Picepelce vot: Nmport java.util. Scanner + lass Test ublic static void main(Stringt} args) Scanner _se¢_= new Scanner(System in) Sugtem.outt. print (“Enter any string te che fring ght = Sc.nextO). char] chayacters = new charllol, int ten = at--lengtha). i en ee | chaactersljl = str chav At GJ- yCint jeten-1 5 j=0. Sting retSte = new String Ghamaters). 8 em9-ouh printnGnew. Shy frie elena thors if Gio equals Gev_Shr. Hin), System outorinth (Te else s is folind-ame™); tem out .println (C4 mapa Ct is neh 9 Paling Page No___ a Dote ade eee alste a java pregram _te te gale the case ‘of qiven string v ia) } class Test t public skkbe void main Cstingld args) 5 : Shing str = new Shing CRIT Wlardha@442001™? [ Int = she lengthy, | Shing Builder sh= new Shing Builder > forCint i=0; ic fy Trt 09 ar At Ci) char ch = she 5 &% ché= SO) st Cch ch +232 “ £ (ch>=97 88 cha l22) ch -= 32 sb- appendcen), em. Out printinCfOviginal, Shangie | phe Je Shrikrupa. | 3 Shing Builder { \n(stina Ll arms b public static vo main( sting L ao df gb = nec StinaBuild er Cpe La ShangBuilder. 7 sb: append (**Glardha”? 2 a System ntln Cb), ¥ - ri sb. delete (2,5). ra System. out. print in (sb) i ; i sbereverse C) Z Ml | System outs print Ch) j a i - 5 a if Quipat) BIT Wardha iad 1 ! Blacdha al es 7A avai | | aad a hdl ie Shrikrupa gi Page No, ET : Arpays Date) /1o/22 is Mae | = Declarchon f Ee Teidvalten aon = IE Teversa! 5 1 al i Avray ig teen ag guh-seripted Nartable a I = 40 i Subscript a [An array is a group of similar type elements a that are referred ~ by a common Rame. v = ay Avrays of any type can be created and may have one or Hore dimensions ment in an array is accessed b and it stovts eith Zeve. aA si its index More ferred $n Java type arto namely, / c-shyle at emery Allocation = Y : et Systo= aevsame = new Aype [size OR rename new elsize} x: daublelJ rnarks = new double [55], Shrikrupa Doibalization* en keood Initialization fot CJ voll. nes = {201 202, 2084. OR Reena Gabalizaho Jot CI vell-vos 5 welluves = new Intls] yellonosfol = 2el- VellenosCi] = 202, yell-nosf2j = 208 oR Ue fora ettingbivalues: fom pean nt user pee olla s.length . Tae ies iwelesce net Ey S) Reavam to. fad sum and elements: average o> array “lass Test f oo yeid main (string LA args )t int £1 are =e 26 30 Ga int_sum = 0. double avg - 4 forGint ele: avr dF Sum = = Sum tele. Shrikeupa avg = (sum & NO) fare. length + System. outs printin( gum 77-4 sum), System. out. printin Cfhveaae =" tong). x J i ? Te find the lowest array element J max) max = arr (il: | j Systero. out. print In (Clam selene nen =m or roe ane { To Find the second largest array, element + class Test f public _stuitic Nota _main( Shingf 4 args) i iabLiose= $40, 20, 50 30,504; iot_g) shy Shrikrupa = i lated» avy ba f —_— ee = aye) rc | rope f a | else { at Le - I fi = ove Cr a — “sr = ary Lely _ | 4 = i } focint 1225 1 ést 46 arr ti] = £0) } iL siz arr (il: * tL j ’ t Shrikrupa a “There Save only S ( —~- a —— S| || Searching 2 search aleeeithmas (@)Lineax Search = Ben) complexity = fob? Binary Search = “OCheig.» ) complexity — Avray must be sorted a = Corks like dictbnavy seavch Te implement Linear Search + bd import java.util Scanner ; class Test tae public stale void main Csting £1 args) e t Scanner SC = new Scanner (system -1n), . System out. printhn (‘Enter no. of elements! ") | fnt_size = _sc.nextInte) a i intl avy = new int [size], oJ), : System -outsprintin (finter ariay element -”’); SS oof) Cint ¢=01, eeize y toh . oar UJ = seenextTote ), ' 4 A - System. out-printin(*Pnter Seach element?” ), i int ele = sc.next into, Shrikrupa usta int ty for(t=0, lesize if gf (arbi == clef Systemoutsprintin C“Blement found e “ie f break; i { if G==size) . Systers - out, printin (‘Element not found ay To imple ment Binary | =lsSe] 50[ 60] Spaecs | Case-I: ele=4o Gane @ 420 hes Cussatee ——# m= 2 @ l=3, h=s ie ne ma 0 @ Asap @Asza, 28 m= 3 m=3 @ Le 4 yes arrCimidd ==40 = : > >Y Success | Shrikrupa lass Test : public static void _maln Cerrina args) § int L 4 arr = $10, 26,30, 40, 50)60, 70, 80, : = int low =O) high= avr .letath SVS int ele =40, hile Cow <= high) f int mid = (loaithigh) /2 - if Cele == arr Enid )f System. out. printin (Element: found at index + mid). byeals , t lse It Carv [nid] < ele) low =mid+l; else high= mid -\, q A $f Clow > high) System .out. printhn (“Element net found "), J f Es nee? 4 bare Fats Page No,__ date —_/ thine i Aeeeio sgexting < ge = Ea a i @® Twerton Sort __— 2) Cm) OG __6(n*) 6G OC) P-Olnloan)s Olean) 0 Clean) i T @a Guick ser odnlegn) OCnlean) lm i |_ © _ Radix Sort | 3 4 Bidens sort O(mlean)? _OCn!eqn) _O (lean ) S CG — @) Bucket Sort eo tmplement Bubble Sort: class Test f blic static ott) are for(int i= ;_icarvelength-1s isd i ___forcint feo, j carr. length-1-1, pao) a ome eraly arrt)f a i S int_temp = ary E71 } l + -arr[j] = avy [fei] J e avy {i+i] = temp —s i { _ a ge a — ae Syoter. out. =print/n (Sevted_ = a? foctint i= 0. icarv.lenath: Tet < Sy eter. out j 7). sprint Carr i cena Bh a clo Uae elements are alltaed ina seb Page No__ public styic void main (shingl 1 os) § int £1 arr) = $ 86,50, 40, 26 N03 intll arr2 = {so 50,60, 70 80, 24, Int nls arvvlelength | 12 = arv2-length g int ld intersecton = new int [ath.min (nln2 int index =O, rCint 1=0, I nly HHS © forint js0pjen24 jeep ttCenr Ei] = = ae 2004 <_intersee Hon [index) © arel Lil 5 index tty breaks break; iciodex , i++) f maul. print In (inhersecHon Cid )y dy bo} Shrikrupe given gray Roane fo reverse : $ $ =| class Test { a args) 9f f Systeroutspyintin CS Raber caahex 21): forrCink j= 0. jee dy ine Df for Cink fete een as mot@i lly] = scsnext Inte), Shrikeupa forCint 1204 fends ite) soc Ceeyee jec2s Yee? ‘reoult DIL] = matt ii Cia + mot Oa, Systemseub printing stem outs 5 5 Shrikrupo Page No. find hranspose of aes acre class Test public stake void roain (St ving £1 _avgs) a 7 Sint. Ex Test obj = ne ee ee eee is Sighemaauh priatla Ca x before henspese mmm aby. printMat(mat , 2,57 icf + - cs on pose (mat 2: 30) intlata hans = = Gyalemauk pvintin( “Haix after transpose J ehjuprints 2) . f veld print Mat(int LIT] 9 | int +, int ©? for(int 1=65 ieyy 14+ F a _foilisafeoly Gee hea e 5 syso(aGiIti ¢ “Ven, 5 latin dul tplication® Rage for [impact Jovauutil Scanner; class Test { publtc static veid_ma'r String (1 age f t te inti fi @ = fatlI D1 b=j{fh2 4 + t 4 int Ws zypel=3 5 02 int LILI mul = nee viNe2], I puis : forint I= 0, Tew! ist )f ie i bi for (int f=0- 1 hers Hy a I for(int K=04 & final modifier indicates that the date me cannot __be modified. cc = A Navidble decloved os fal has te be iniHalize at_the Hme ef declaration, ~ Ex! final _pevate double pis 3.14. Se? final method + — final method Canned be over- vided in S3Gy! Anal pablic avoid BmeaNce t : é z Systetriout. prinths CL am in class A"), a Ce) tinal class= S, ela-class declared _as ‘final’ canmet be nherited eee) finel_ class AT 3 FBedy of A x closs 8 extends Af // ERROR ABody of B Q@) static Keyotord Tt has 3 uses ~ a) Te declare static variable 2 Lee) _~» The difference betweem instance vartable and stable Variable is that the Commoim memory stabe verieble is shaved ameng all cbiects. = Te access sintic variable clout! class_name. Variable name. b) To declare stahe method + simple Page No,_ date ff for calling a gtatic method, tostead we ue omtos in auniax 8 class-name. methed. name 7 ©) Ts define a static blectr + a cless Bex f private double 1, byb Utnstance Naviables is state ntOfaores; // static variable ie. clase Sams gt Naviebt, 4 G sino’, Mt static bloctc Count OF Boxes =O fino-ors conshuctr Bi double h)F “parameterize constructor this-b= & thigh= A Count OF Boxes ++ ‘ = state veld veel axe © Current Count? static ba WN + b Ds Sys ers, If class Test § | Mp metat } public static veld Box -givetleCurrent Count) ‘ Box bi = new Boxe) i. . ‘1 srrentCounte ) - = Outpuk? @ Cieveshs box. Coust £6 10.0 1.0 ti nb Cuccext box dount to0 20.6 30 Io Current bee Count = 2 Shrikrupa

You might also like