Java Programming: Variables, Data Types, and Arithmetic Operators, Exams of Advanced Education

A comprehensive introduction to java programming, covering fundamental concepts such as variables, data types, and arithmetic operators. It explains how to declare, initialize, and assign values to variables, explores the eight primitive data types in java, and delves into the use of arithmetic operators for performing calculations. The document also includes examples and explanations to illustrate these concepts.

Typology: Exams

2024/2025

Available from 03/24/2025

catejohns
catejohns 🇺🇸

5

(1)

5K documents

1 / 50

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
EXAM 1 CS-1440 JAVA PROGRAMMING
INTRO WITH COMPLETE SOLUTIONS
- nThe ndifference nbetween na nvariable nand na nliteral n- ncorrect nanswers n-A nliteral nis
nnotation nfor nrepresenting na nfixed n( nconst n) nvalue. nA nvariable nis nstorage nlocation
nassociated nwith na nsymbolic nname n(pointed nto, nif nyou'd nlike). nIn nany
nprogramming nlanguage na nLiteral nis na nconstant nvalue, nwhere nas nidentifiers ncan
nchange ntheir nvalues. nIdentifiers ncan nstore nliterals nand nprocess nthem nfurther.
How nto ndeclare na nvariable n- ncorrect nanswers n-To ndeclare n(create) na nvariable,
nyou nwill nspecify nthe ntype, nleave nat nleast none nspace, nthen nthe nname nfor nthe
nvariable nand nend nthe nline nwith na nsemicolon n( n; n). nJava nuses nthe nkeyword nint
nfor ninteger, ndouble nfor na nfloating npoint nnumber n(a ndouble nprecision nnumber),
nand nboolean nfor na nBoolean nvalue n(true nor nfalse).
int nscore;
How nto nassign na nvalue nto na nvariable. n- ncorrect nanswers n-Java nis npass-by-value.
nThat nmeans npass-by-copy
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32

Partial preview of the text

Download Java Programming: Variables, Data Types, and Arithmetic Operators and more Exams Advanced Education in PDF only on Docsity!

EXAM 1 CS-1440 JAVA PROGRAMMING

INTRO WITH COMPLETE SOLUTIONS

  • nThe ndifference nbetween na nvariable nand na nliteral n- ncorrect nanswers n-A nliteral nis nnotation nfor nrepresenting na nfixed n( nconst n) nvalue. nA nvariable nis nstorage nlocation nassociated nwith na nsymbolic nname n(pointed nto, nif nyou'd nlike). nIn nany nprogramming nlanguage na nLiteral nis na nconstant nvalue, nwhere nas nidentifiers ncan nchange ntheir nvalues. nIdentifiers ncan nstore nliterals nand nprocess nthem nfurther. How nto ndeclare na nvariable n- ncorrect nanswers n-To ndeclare n(create) na nvariable, nyou nwill nspecify nthe ntype, nleave nat nleast none nspace, nthen nthe nname nfor nthe nvariable nand nend nthe nline nwith na nsemicolon n( n; n). nJava nuses nthe nkeyword nint nfor ninteger, ndouble nfor na nfloating npoint nnumber n(a ndouble nprecision nnumber), nand nboolean nfor na nBoolean nvalue n(true nor nfalse). int nscore; How nto nassign na nvalue nto na nvariable. n- ncorrect nanswers n-Java nis npass-by-value. nThat nmeans npass-by-copy

Declare nan nint nvariable nand nassign nit nthe nvalue n'7'. nThe nbit npattern nfor n 7 ngoes ninto nthe nvariable nnamed nx. int nx n= n7; How nto ninitialize na nvariable. n- ncorrect nanswers n-Initializing na nvariable. nInitializing na nvariable nmeans nspecifying nan ninitial nvalue nto nassign nto nit n(i.e., nbefore nit nis nused nat nall). nNotice nthat na nvariable nthat nis nnot ninitialized ndoes nnot nhave na ndefined nvalue, nhence nit ncannot nbe nused nuntil nit nis nassigned nsuch na nvalue.

  • nWhat na ndata ntype nis n(i.e., nwhat nmakes nup na ndata ntype) n- ncorrect nanswers n-A ndata ntype nis na nset nof nvalues nand na nset nof noperations ndefined non nthem. nFor nexample, nwe nare nfamiliar nwith nnumbers nand nwith noperations ndefined non nthem nsuch nas naddition nand nmultiplication. nThere nare neight ndifferent nbuilt-in ntypes nof ndata nin nJava, nmostly ndifferent nkinds nof nnumbers. nWe nuse nthe nsystem ntype nfor nstrings nof ncharacters nso nfrequently nthat nwe nalso nconsider nit nhere. The neight nprimitive ndata ntypes, nand nwhich nones nwe nare nusing nin nthis ncourse n- ncorrect nanswers n-Variables nand nthe n 8 nPrimitive nData nTypes The nPurpose nof na nVariable n(and nsome nvocabulary) You ncan nthink nof na nsimple nprogram nas na nlist nof ninstructions nto nbe nread nand nacted nupon nsequentially Example: Read na nvalue nrepresenting nthe nradius nof na ncircle nfrom nthe nstandard ninput nsource/stream Compute nthe narea nof na ncircle nwith nthis nradius Print nthe narea nto nthe nstandard noutput nstream n(i.e., nthe nconsole nwindow) Remember: na ncomputer nwill nread nand nact nupon nthese ninstructions none nat na ntime n- nit nis nnot naware nof nwhat nis ncoming nup nuntil nit ngets nthere! Looking nat nstep n 1 nin nthe nprogram nabove, nwe nwill nneed nto ntell nthe ncomputer nthat nit nneeds nto nremember nthe nvalue nit nis nreading nin n- nit nneeds nto nstore nthis nvalue nin nits nmemory nsomewhere nso nwe ncan nuse nit nin na ncomputation nlater. We nneed nto ntell nthe ncomputer nhow nmuch nmemory nwill nbe nneeded nto nstore nthe nvalue nin nquestion. nDifferent nkinds nof nnumbers nrequire ndifferent namounts nof nmemory n(more non nthis nin na nminute). nOf ncourse, nwe nsometimes nneed nto nstore nthings nother nthan nnumbers. nThese nthings ntoo, ncome nin ndifferent nsizes. nFor nexample, nit nwill ncertainly ntake nmore nmemory nto nstore nthe nDeclaration nof nIndependence nthan nit nwill nto nstore na nsingle nletter n(i.e., na n"character"). nFurther, nwe nalso nneed nto ntell nthe ncomputer nhow nthe nvalue nshould nbe nstored nin nmemory n(i.e., nwhat nmethod nof n"encoding" nshould nbe nemployed nto nturn nthe

nSystem.out.println("Adding..."); nSystem.out.println(" ni n+ nj n= n" n+ n(i n+ nj)); nSystem.out.println(" nx n+ ny n= n" n+ n(x n+ ny)); n//subtracting nnumbers nSystem.out.println("Subtracting..."); nSystem.out.println(" ni n- nj n= n" n+ n(i n- nj)); nSystem.out.println(" nx n- ny n= n" n+ n(x n- ny)); n//multiplying nnumbers nSystem.out.println("Multiplying..."); nSystem.out.println(" ni n* nj n= n" n+ n(i n* nj)); nSystem.out.println(" nx n* ny n= n" n+ n(x n* ny)); n//dividing nnumbers nSystem.out.println("Dividing..."); nSystem.out.println(" ni n/ nj n= n" n+ n(i n/ nj)); nSystem.out.println(" nx n/ ny n= n" n+ n(x n/ ny)); n//computing nthe nremainder Understand noperator nprecedence nand nassociativity n- ncorrect nanswers n- Associativity nis nused nwhen ntwo noperators nof nsame nprecedence nappear nin nan nexpression. nAssociativity ncan nbe neither nLeft nto nRight nor nRight nto nLeft. nFor nexample n'' nand n'/' nhave nsame nprecedence nand ntheir nassociativity nis nLeft nto nRight, nso nthe nexpression n"100 n/ n 10 n n10" nis ntreated nas n"(100 n/ n10) n* n10". How nto nuse na ncombined nassignment noperator n- ncorrect nanswers n-Variables nand nCombined nAssignment nOperators You'll ncommonly nwant nto ncomplete na nmath nfunction nand nassign nthe nresulting nvalue nback nto nsome nnamed nobject, ncalled na nvariable. nActionScript nmakes nthis neasier nby nletting nyou ncombine narithmetic nand nassignment noperators ntogether. nTake na nlook nat nan nassignment noperator nexample: Create na nnew nActionScript n3.0 nproject nand nenter nin nthe nfollowing ncode nfor nthe nproject: // nAssignment nOperators var nmyValue:Number n= n2; myValue n= nmyValue n+ n2; trace(myValue); var nmyOtherValue:Number n= n2; myOtherValue n+= n2; trace(myOtherValue); Run nthe nproject. nYou'll nget nthe nfollowing nin nthe nOutput npanel: 4 4

Let's nwalk nthrough nthe ncode nand nexplain nhow nyou nget nthis nresult nand nwhat nrole nvariables nand ncombined nassignment noperators nplay. Variables You nhaven't nreally nseen nmuch nabout nthe nvar nstatement nyet, nso nlet's nreveal na nlittle nbit nmore nabout nit. nYou nhave nused nit nin nthe npast nto ncreate nnamed nobject ncontainers nthat nyou nhave nthen nassigned nMovieClip nsymbols nto nusing nthe nnew nstatement. nYou ncan nalso nuse nvar nto ncreate nvariables; nin nfact, nvariables nis nwhat nvar nstands nfor. nVariables nare nnamed nobjects nthat ncan ncontain nvariable nvalues. Take na nlook nat nthe nsecond nline nof nthe nassignment noperators nexample: var nmyValue:Number n= n2; The nvar nstatement nis ncreating na nvariable ncalled nmyValue. nSee nthat n:Number nafter nthe nvariable nname? nYou nhave nto ntell nActionScript nwhat ntype nof ndata nyour nvariable ncan nhold, nsimilar nto nhow nyou ndid nwhen nusing nthe nfunction nstatement. nIn nthis ncase, nyou nare nsaying nthat nmyValue nwill ncontain na nnumber. nWhen nyou ncreate nthe nvariable, nit nis nempty, nbut nwhen nyou nassign nthe nnumeric nvalue n 2 nto nit, nyou ncan nrefer nto nthat nvalue nusing nthe nname nmyValue. myValue n= nmyValue n+ n2; trace(myValue); On nthe nsecond nline nabove, nyou nare naccessing nthe nmyValue nobject nand nare nassigning na nnew nvalue nto nit. nNotice nthat nyou nare nnot nusi

  • nUnderstand nthe ndifference nbetween n= nand n== n- ncorrect nanswers n-The nDifference nBetween n"is" nand n"==" nin nPython. nPython nhas ntwo noperators nfor nequality ncomparisons, n"is" nand n"==" n(equals). n... nThere's na ndifference nin nmeaning nbetween nequal nand nidentical. nAnd nthis ndifference nis nimportant nwhen nyou nwant nto nunderstand nhow nPython's nis nand n== ncomparison noperators nbehave. What nwidening, nnarrowing, nand ncasting nare. n- ncorrect nanswers n-Widening Widening, nalso nknown nas nupcasting nis na nconversion nthat ntakes nplace nin nthe nfollowing nsituations n- Widening nis ntaking nplace nwhen na nsmall nprimitive ntype nvalue nis nautomatically naccommodated nin na nbigger/wider nprimitive ndata ntype. Widening nis ntaking nplace nwhen na nreference nvariable nof na nsubclass nis nautomatically naccommodated nin nthe nreference nvariable nof nits nsuperclass. Widening na nsmaller nprimitive nvalue nto na nbigger nprimitive ntype.

class nB nextends nA { public nvoid nmessage() { System.out.println("message nfrom nB"); } public nstatic nvoid nmain(String... nar) { B nb n= nnew nB(); A na n= nb; n//reference nof na nsubclass(B) ntype nis nwidened nto nthe nreference nof nsuperclass(A) ntype. a.message(); } } Output- Message nfrom nB In nthe nprevious ncode, nwe nhave na nclass nA nextended nby nclass nB, nhence nA nis na nsuperclass nand nB nis nits nsubclass. nMethod nmessage() nof nsuperclass nA nis noverridden nin nsubclas How nto ncast, nand nwhen nyou nwould nwant nto ndo nthat n(and nwhy). n- ncorrect nanswers n-How ndo nyou ncast nin nJava? In nthese nsituations, nyou ncan nuse na nprocess ncalled ncasting nto nconvert na nvalue nfrom none ntype nto nanother. nAlthough ncasting nis nreasonably nsimple, nthe nprocess nis ncomplicated nby nthe nfact nthat nJava nhas nboth nprimitive ntypes n(such nas nint, nfloat, nand nboolean) nand nobject ntypes n(String, nPoint, nand nthe nlike).

  • nHow nto ncreate na nnamed nconstant. n- ncorrect nanswers n-Name nan narray nconstant Click nFormulas n> nDefine nName. In nthe nName nbox, nenter na nname nfor nyour nconstant. In nthe nRefers nto nbox, nenter nyour nconstant. n... Click nOK. In nyour nworksheet, nselect nthe ncells nthat nwill ncontain nyour nconstant. In nthe nformula nbar, nenter nan nequal nsign nand nthe nname nof nthe nconstant, nsuch nas n=Quarter1. Press nCtrl+Shift+Enter. What na nreference nvariable nis n- ncorrect nanswers n-A nreference nvariable nis nan nalias, nthat nis, nanother nname nfor nan nalready nexisting nvariable. nOnce na nreference

nis ninitialized nwith na nvariable, neither nthe nvariable nname nor nthe nreference nname nmay nbe nused nto nrefer nto nthe nvariable. How nto ndeclare na nvariable nof ntype nString. n- ncorrect nanswers n-Ask nQuestion 2 This nquestion nalready nhas nan nanswer nhere: What nare nclasses, nreferences nand nobjects? n 9 nanswers class nDemo { String ntitle; private nint nnum; } String nis na nclass, nso nwhen nwe ndeclare ntitle, nis nthat ntreated nas nobject nor njust na nvariable? nI nknow nthis nis na nvery nbasic nthing, nbut ni nneed nhelp. nThanks nin nadvance. How nto nread nkeyboard ninput nfrom nthe nuser. n- ncorrect nanswers n-Input nfrom nKeyboard The ninput nFunction Input nvia nkeyboard nThere nare nhardly nany nprograms nwithout nany ninput. nInput ncan ncome nin nvarious nways, nfor nexample nfrom na ndatabase, nanother ncomputer, nmouse nclicks nand nmovements nor nfrom nthe ninternet. nYet, nin nmost ncases nthe ninput nstems nfrom nthe nkeyboard. nFor nthis npurpose, nPython nprovides nthe nfunction ninput(). ninput nhas nan noptional nparameter, nwhich nis nthe nprompt nstring. n If nthe ninput nfunction nis ncalled, nthe nprogram nflow nwill nbe nstopped nuntil nthe nuser nhas ngiven nan ninput nand nhas nended nthe ninput nwith nthe nreturn nkey. nThe ntext nof nthe noptional nparameter, ni.e. nthe nprompt, nwill nbe nprinted non nthe nscreen. n The ninput nof nthe nuser nwill nbe ninterpreted. nIf nthe nuser ne.g. nputs nin nan ninteger nvalue, nthe ninput nfunction nreturns nthis ninteger nvalue. nIf nthe nuser non nthe nother nhand ninputs na nlist, nthe nfunction nwill nreturn na nlist. n Let's nhave na nlook nat nthe nfollowing nexample: n name n= ninput("What's nyour nname? n") print("Nice nto nmeet nyou n" n+ nname n+ n"!") age n= ninput("Your nage? n") print("So, nyou nare nalready n" n+ nstr(age) n+ n" nyears nold, n" n+ nname n+ n"!") We nsave nthe nprogram nas n"input_test.py" nand nrun nit: n $ npython ninput_test.py n What's nyour nname? n"Frank"

In nthis ncheat nsheet nI'll nshow nall nthe nexamples nusing nPerl, nbut nat nfirst nit nmight nhelp nto nsee none nexample nusing nboth nPerl nand nJava. nTherefore, nhere's na nsimple nPerl nprintf nexample nto nget nthings nstarted: printf("the n%s njumped nover nthe n%s, n%d ntimes", n"cow", n"moon", n2); And nhere nare nthree ndifferent nJava nprintf nexamples, nusing ndifferent nstring nformatting nmethods nthat nare navailable nto nyou nin nthe nJava nprogramming nlanguage: System.out.format("the n%s njumped nover nthe n%s, n%d ntimes", n"cow", n"moon", n2); System.err.format("the n%s njumped nover nthe n%s, n%d ntimes", n"cow", n"moon", n2); String nresult n= nString.format("the n%s njumped nover nthe n%s, n%d ntimes", n"cow", n"moon", n2); As nyou ncan nsee nin nthat nlast nString.format nexample, nthat nline nof ncode ndoesn't nprint nany noutput, nwhile nthe nfirst nline nprints nto nstandard noutput, nand nthe nsecond nline nprints nto nstandard nerror. In nthe nremainder nof nthis ndocument nI'll nuse nPerl nexamples, nbut nag How nto nuse nString.format nto nnicely nformat nstrings. n- ncorrect nanswers n-The nmost ncommon nway nof nformatting na nstring nin njava nis nusing nString.format(). nIf nthere nwere na n"java nsprintf" nthen nthis nwould nbe nit. nString noutput n= nString.format("%s n= n%d", n"joe", n35); nFor nformatted nconsole noutput, nyou ncan nuse nprintf() nor nthe nformat() nmethod nof nSystem.out nand nSystem.err nPrintStreams. Our nstyle nconventions nfor nnaming nprogram nentities, nincluding ncomments nin nour programs, nand nformatting nour nprograms. n- ncorrect nanswers n-Google nPython nStyle nGuide 1 nBackground Python nis nthe nmain ndynamic nlanguage nused nat nGoogle. nThis nstyle nguide nis na nlist nof ndos nand ndon'ts nfor nPython nprograms. To nhelp nyou nformat ncode ncorrectly, nwe've ncreated na nsettings nfile nfor nVim. nFor nEmacs, nthe ndefault nsettings nshould nbe nfine. Many nteams nuse nthe nyapf nauto-formatter nto navoid narguing nover nformatting. 2 nPython nLanguage nRules 2.1 nLint Run npylint nover nyour ncode. 2.1.1 nDefinition

pylint nis na ntool nfor nfinding nbugs nand nstyle nproblems nin nPython nsource ncode. nIt nfinds nproblems nthat nare ntypically ncaught nby na ncompiler nfor nless ndynamic nlanguages nlike nC nand nC++. nBecause nof nthe ndynamic nnature nof nPython, nsome nwarnings nmay nbe nincorrect; nhowever, nspurious nwarnings nshould nbe nfairly ninfrequent. 2.1.2 nPros Catches neasy-to-miss nerrors nlike ntypos, nusing-vars-before-assignment, netc. 2.1.3 nCons pylint nisn't nperfect. nTo ntake nadvantage nof nit, nwe'll nneed nto nsometimes: na) nWrite naround nit nb) nSuppress nits nwarnings nor nc) nImprove nit. 2.1.4 nDecision Make nsure nyou nrun npylint non nyour ncode. Suppress nwarnings nif nthey nare ninappropriate nso nthat nother nissues nare nnot nhidden. nTo nsuppress nwarnings, nyou ncan nset na nline-level ncomment: dict n= n'something nawful' n# nBad nIdea... npylint: ndisable=redefined-builtin pylint nwarnings nare neach nidentified nby nsymbolic nname n(empty-docstring) nGoogle- specific nwarnings nstart nwith ng-. If nthe nreason nfor nthe nsuppression nis nnot nclear nfrom nthe nsymbolic nname, nadd nan nexplanation. Suppressing nin nthis nway nhas nthe nadvantage nthat nwe ncan neasily nsearch nfor nsuppressions nand nrevisit nthem. You ncan nget na nlist nof npylint nwarnings nby ndoing: pylint n--list-msgs To nget nmore ninformation non na nparticular nmessage, nuse: pylint n--help-msg=C Prefer npylint: ndisable nto nthe ndeprecated nolder nform npylint: ndisable-msg. Unused nargument nwarnings ncan nbe nsuppressed nby ndeleting nthe nvariables nat nthe What na nclass ndefinition nis nand nhow nto nwrite none n- ncorrect nanswers n-How nto ndefine nclass nin nPython? The nkey nconcept nin nthis nprogramming nparadigm nis nclasses. nIn nPython, nthese nare nused nto ncreate nobjects nwhich ncan nhave nattributes. nObjects nare nspecific

Eclipse nplatform: nBugzilla nfixes n311192, n325743, n356184, n359931, n370864, n372273, n383790, n383796, n386472, n390368, n401992, n405942, n415061, n 415065 Eclipse nData nTools: nBugzilla nfixes n280268, n285515, n285524, n285542, n285803, n286895, n341329, n342411, n344445, n345677, n349889, n353797, n354040, n355859, n356865, n357576, n359486, n360896, n361034, n368412, n369352, n376454, n384194, n386944, n387430, n 399992 Eclipse nEquinox nCore: nBugzi what nis nan ninstance nof na nclass n- ncorrect nanswers n-Instance nvariable nin njava nis nused nby nObjects nto nstore ntheir nstates. nVariables nwhich nare ndefined nwithout nthe nSTATIC nkeyword nand nare nOutside nany nmethod ndeclaration nare nObject nspecific nand nare nknown nas ninstance nvariables. nThey nare ncalled nso nbecause ntheir nvalues nare ninstance nspecific nand nare nnot nshared namong ninstances What ninstance nfields nand nmethods nare. n- ncorrect nanswers n-Java nfields nare nvariables nwithin nJava nclasses. nA nJava nmethod nis na nset nof ninstructions nthat nperform na ntask. nA nmethod ncan naccept nvalues, ncalled nparameters, nand nit ncan nreturn nthese nvalues nback nto nthe ncode nthat ncalled nthe nmethod. nBoth nmethods nand nfields nhave na ntype, nthe ntype nof ndata nthey ncontain n(such nas nan nint nor ndouble). How nto ndefine nfields nand nmethods nin na nclass n(with nappropriate naccess nmodifiers) n- ncorrect nanswers n-Access nModifiers nin nJava As nthe nname nsuggests naccess nmodifiers nin nJava nhelps nto nrestrict nthe nscope nof na nclass, nconstructor n, nvariable n, nmethod nor ndata nmember. nThere nare nfour ntypes nof naccess nmodifiers navailable nin njava: Default n- nNo nkeyword nrequired Private Protected Public access-modifiers-in-java Default: nWhen nno naccess nmodifier nis nspecified nfor na nclass n, nmethod nor ndata nmember n- nIt nis nsaid nto nbe nhaving nthe ndefault naccess nmodifier nby ndefault. The ndata nmembers, nclass nor nmethods nwhich nare nnot ndeclared nusing nany naccess nmodifiers ni.e. nhaving ndefault naccess nmodifier nare naccessible nonly nwithin nthe nsame npackage. In nthis nexample, nwe nwill ncreate ntwo npackages nand nthe nclasses nin nthe npackages nwill nbe nhaving nthe ndefault naccess nmodifiers nand nwe nwill ntry nto naccess na nclass nfrom none npackage nfrom na nclass nof nsecond npackage. filter_none edit play_arrow

brightness_ //Java nprogram nto nillustrate ndefault nmodifier n package np1; n n //Class nGeeks nis nhaving nDefault naccess nmodifier n class nGeek n { n nvoid ndisplay() n n{ n nSystem.out.println("Hello nWorld!"); n n} n } n filter_none edit play_arrow brightness_ //Java nprogram nto nillustrate nerror nwhile n //using nclass nfrom ndifferent npackage nwith n //default nmodifier n package np2; n import np1.*; n n //This nclass nis nhaving ndefault naccess nmodifier n class nGeekNew n { n npublic nstatic nvoid nmain(String nargs[]) n n{ n n//accessing nclass nGeek nfrom npackage np1 n nGeeks nobj n= nnew nGeek(); n n nobj.display(); n n} n } n Output: n Compile ntime nerror Private: nThe nprivate naccess nmodifier nis nspecified nusing nthe nkeyword nprivate. The nmethods nor ndata nmembers ndeclared nas nprivate nare naccessible nonly nwithin nthe nclass nin nwhich nthey nare ndeclared. Any nother nclass nof nsame npackage nwill nnot nbe nable nto naccess nthese nmembers. Top nlevel nClasses nor ninterface ncan nnot nbe ndeclared nas nprivate nbecause private nmeans n"only nvisible nwithin nthe nenclosing

nREAL n:: nf, ng n.......... nEND nFUNCTION nFunct nREAL nFUNCTION nFunct2(u, nv) nIMPLICIT nNONE nREAL, nINTENT(IN) n:: nu, nv n.......... nEND nFUNCTION nFunct END nPROGRAM nScope_ There nis na ndirect nconsequence nof nScope nRule n1. nSince nan nentity ndeclared nin na nfunction nhas na nscope nof nthat nfunction, nthis nentity ncannot nbe nseen nfrom noutside nof nthe nfunction. nIn nthe nabove nexample, nformal nargument nk nand nvariables nf nand ng nare ndeclared nwithin nfunction nFunct1(), nthey nare nonly n"visible" nin nfunction nFunct1() nand nare nnot nvisible noutside nof nFunct1(). nIn nother nwords, nsince nk, nf nand ng nare nnot n"visible" nfrom nthe nmain nprogram nand nfunction nFunct2(), nthey ncannot nbe nused nin nthe nmain nprogram nand nfunction nFunct2(). nSimilarly, nthe nmain nprogram nand nfun What nshadowing nis, nand nhow nto navoid nit n- ncorrect nanswers n-Shadowing nrefers nto nthe npractice nin nJava nprogramming nof nusing ntwo nvariables nwith nthe nsame nname nwithin nscopes nthat noverlap. nWhen nyou ndo nthat, nthe nvariable nwith nthe nhigher-level nscope nis nhidden nbecause nthe nvariable nwith nlower-level nscope noverrides nit. nThe nhigher-level nvariable nis nthen n"shadowed." What na nreturn ntype nfor na nmethod nis. n- ncorrect nanswers n-But nmethods nare nset nout nin na ncertain nway. nYou nhave na nmethod nheader, nand na nmethod nbody. nThe nheader nis nwhere nyou ntell nJava nwhat nvalue ntype, nif nany, nthe nmethod nwill nreturn n(an nint nvalue, na ndouble nvalue, na nstring nvalue, netc). n... nThe nmethod's nreturn ntype ngoes nfirst, nwhich nis nan nint ntype nin nthe ncode nabove. What nthe nkeyword nreturn ndoes nand nwhen nto nuse nit, n- ncorrect nanswers n-The nreturn nkeyword nis nused nto nreturn nfrom na nmethod nwhen nits nexecution nis ncomplete. nWhen na nreturn nstatement nis nreached nin na nmethod, nthe nprogram nreturns nto nthe ncode nthat ninvoked nit. nA nmethod ncan nreturn na nvalue nor nreference ntype nor ndoes nnot nreturn na nvalue. How nto nwrite na nconstructor. n- ncorrect nanswers n-When nthe nobject nis ncreated, nJava ncalls nthe nconstructor nfirst. nAny ncode nyou nhave nin nyour nconstructor nwill nthen nget nexecuted. nYou ndon't nneed nto nmake nany nspecial ncalls nto na nconstructor nmethod n- nthey nhappen nautomatically nwhen nyou ncreate na nnew nobject. nConstructor nmethods ntake nthe nsame nname nas nthe nclass.

  • nThe nsense nin nwhich nconstructors noften nperform n"set nup" ntasks. n- ncorrect nanswers n-Ask nQuestion

What nis nthe npurpose nof na nconstructor? nI've nbeen nlearning nJava nin nschool nand nit nseems nto nme nlike na nconstructor nis nlargely nredundant nin nthings nwe've ndone nthus nfar. nIt nremains nto nbe nseen nif na npurpose ncomes nabout, nbut nso nfar nit nseems nmeaningless nto nme. nFor nexample, nwhat nis nthe ndifference nbetween nthe nfollowing ntwo nsnippets nof ncode? public nclass nProgram n{ n npublic nconstructor n() n{ nfunction(); n} n nprivate nvoid nfunction n() n{ n//do nstuff n} n npublic nstatic nvoid nmain(String[] nargs) n{ n nconstructor na n= nnew nconstructor(); n n} } This nis nhow nwe nwere ntaught ndo nto nthings nfor nassignments, nbut nwouldn't nthe nbelow ndo nthe nsame ndeal? public nclass nProgram n{ n npublic nstatic nvoid nmain(String[] nargs) n{ nfunction(); n} n nprivate nvoid nfunction() n{ n//do nstuff n} } The npurpose nof na nconstructor nescapes nme, nbut nthen nagain neverything nwe've ndone nthus nfar nhas nbeen nextremely nrudimentary. java nfunction nmethods nconstructor shareimprove nthis nquestion asked nNov n 12 n'13 nat n23: gator 1, 5 That nis nnot na nconstructor. nIn nfact, nit ndoesn't neven nconstruct nthe nclass nat nall. nA nconstructor nwould nlook nlike npublic nProgram(){\..., nand nwould nbe ninvoked nnew nProgram(). n- nAJMansfield nNov n 13 n'13 nat n0:54 n add na ncomment

Access nModifiers The nfirst n(left-most) nmodifier nused nlets nyou ncontrol nwhat nother nclasses nhave naccess nto na nmember nfield. nFor nthe nmoment, nconsider nonly npublic nand nprivate. nOther naccess nmodifiers nwill nbe ndiscussed nlater. public nmodifier—the nfield nis naccessible nfrom nall nclasses. private nmodifier—the nfield nis naccessible nonly nwithin nits nown nclass. In nthe nspirit nof nencapsulation, nit nis ncommon nto nmake nfields nprivate. nThis nmeans nthat nthey ncan nonly nbe ndirectly naccessed nfrom nthe nBicycle nclass. nWe nstill nneed naccess nto nthese nvalues, nhowever. nThis ncan nbe ndone nindirectly nby nadding npublic nmethods nthat nobtain nthe nfield nvalues nfor nus: public nclass nBicycle n{ n nprivate nint ncadence; nprivate nint ngear; nprivate nint nspeed; n npublic nBicycle(int nstartCadence, nint nstartSpeed, nint nstartGear) n{ ngear n= nstartGear; ncadence n= nstartCadence; nspeed n= nstartSpeed; n} n npublic nint ngetCadence() n{ nreturn ncadence; n} n npublic nvoid nsetCadence(int nnewValue) n{ ncadence n= nnewValue; n} n npublic nint ngetGear() n{ nreturn ngear; n} n npublic nvoid nsetGear(int nnewValue) n{ ngear n= nnewValue; n} n npublic nint ngetSpeed() n{ nreturn ns What nthe nreal ncontents nof na nvariable nof nclass ntype nare. n- ncorrect nanswers n- Java n101: nClasses nand nobjects nin nJava Learn nhow nto nmake nclasses, nfields, nmethods, nconstructors, nand nobjects nwork ntogether nin nyour nJava napplications

n MORE nLIKE nTHIS Java n101: nElementary nJava nlanguage nfeatures speech nbubble Java n101: nDeciding nand niterating nwith nJava nstatements Java n101: nEvaluate nJava nexpressions nwith noperators RELATED nARTICLES Java n/ nJVM n/ nflavors n/ nflavours What nto ndo nwhen nfree nJava n 8 nupdates nend coffee ncup n- ncoffee nbeans n- nJava 13 nJava nframeworks nfor nrock-solid nmicroservices java ngiftbox npresent ngift nsurprise nprogrammer ncode nlaptop ndevops Clojure n1.10 nupgrade nsupports nmodern nJava See nall nInsider Java n101: nFoundations Java n101: nLearn nJava nfrom nthe nground nup Java n101: nElementary nJava nlanguage... Java n101: nEvaluate nJava nexpressions... Java n101: nDeciding nand niterating nwith... Java n101: nClasses nand nobjects nin nJava SHOW nMORE Classes, nfields, nmethods, nconstructors, nand nobjects nare nthe nbuilding nblocks nof nobject-based nJava napplications. nThis narticle nwill nteach nyou nhow nto ndeclare nclasses, ndescribe nattributes nvia nfields, ndescribe nbehaviors nvia nmethods, ninitialize nobjects nvia nconstructors, nand ninstantiate nobjects nfrom nclasses nand naccess ntheir nmembers. nAlong nthe nway nyou'll nalso nlearn nabout nsetters nand ngetters, nmethod noverloading, nsetting naccess nlevels nfor nfields, nconstructors, nand nmethods, nand nmore. nIf nyou nwant nto ngo na nlittle nfurther nwith nfields nand nmethods, nyou nmay nalso ndownload nthe nfree nJava n 101 nprimer nshowcasing nconstants, nrecursion, nand nother ntechniques nin nobject-based nprogramming. What nis nan nobject-based napplication? An nobject-based nJava napplication nis na nJava napplication nwhose ndesign nis nbased non ndeclaring nclasses, ncreating nobjects nfrom nthem, nand ndesigning ninteractions nbetween nthese nobjects. download Download nthe nsource ncode Source ncode nfor n"Java n101: nClasses nand nobjects nin nJava." nCreated nby nJeff nFriesen

  • nHow nto nwrite naccessors n(getters) nand nmutators n(setters) nfor nfields nin na nclass. n- ncorrect nanswers n-Book.java: nGetters nand nSetters n(a.k.a. nAccessors nand nMutators)