1 / 57

Programming Fundamental

Programming Fundamental. W h at i s J A V A ?.  J AVA i s an O b j e c t Or ie n te d p r o g r a mm i n g l a n g u a g e a s w e l l a p l a t f o rm .  B y u s in g J AV A , w e c an w r it e v a r i o u s t y pe s o f A pp li c a ti o n p r o g r am f o r

wilda
Download Presentation

Programming Fundamental

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming Fundamental

  2. What isJAVA? JAVA isanObjectOriented programminglanguageas wella platform. By usingJAVA, wecanwritevarious typesof Applicationprogramfor any typeof OSandHardware. JAVA isdesignedtobuild interactive,dynamicandsecure applicationson networkcomputer system.

  3. History of JAVA JAVAwasstartedwithaproject(Green)tofindtowriteapplications forelectronicdeviceslikeTV-SettopBoxetc.Whichwas originallynamedOak.LaterrenamedwithJAVA. 1991 James Gosling developed Oak to program consumer electronic devices 1995 JAVAformallyannounced asapart of Netscape web browser. 1996 JavaDevelopment Kit (JDK)1.0 bySun Microsystems. 1997 JDK 1.1 launched with JAVAServlet API 1998 Sun introduced community source“Open”and producesJDK 1.2 for Linux 1999 JDK 1.3 released and J2EE,J2SE,J2MEappeared 2002 JAVAWeb Services Developer Pack released for Web Development. 2005 JAVAEnterprise System 2005Q4 released with integration of various features like monitoring, security etc. forSolaries, Windows etc. 2006 The Netbeans IDE 5.0 is released. Sun Open sourced JavaEE component as the Glassfish projecttoJAVA.net.

  4. Characteristics of JAVA Write Once RunAnywhere (WORA) JAVA Programcanberunondifferentplatformswithout changes. LightWeightCode Bigapplicationscanbedevelopedwithsmallcode. Security JAVA Programsaresafe andsecure. Built-inGraphics& SupportsMultimedia JAVA isequippedwithGraphicsfeature.Itisbestfor integrationofAudio,Video andgraphics& animation. Object OrientedLanguage JavaisObject OrientedLanguage,near toreal world. PlatformIndependent ChangeofH/WandOSplatformdoesnoteffectJAVA program. OpenProduct Itisopeni.e.freelyavailabletoallwithno cost.  any      

  5. Why JAVA is PlatformIndependent? A programwritteninHLLmustbeconvertedintoitsequivalentMachinecode, sothatcomputer canunderstandandexecute.Thisconversionisknownas Compilation.Generally,theconvertedmachinecodedependsontheH/wand OS platform.So,thataWindowsprogramwillnotworkonUNIX,or LINUXor Macplatformetc.SincetheyarePlatformdependent. A programwritteninJAVA isplatform-independenti.e.theyarenotaffectedwith changingofOS.ThismagicisdonebyusingBytecode.Bytecodeis independentofthecomputer systemit hastorunupon. JavacompilerdoesnotproducesBytecodeinsteadofnativeexecutablecode whichisinterpretedbyJavaVirtualMachine(JVM) at the timeof execution. Javauses both compiler and interpreter. JavaInterpreter(JVM) forMacintosh JavaInterpreter(JVM) forWindows Java Compiler Java Program JavaByte Code Program JavaInterpreter(JVM) forUnix

  6. Basics of GUI HowGUIapplicationworks? GraphicalUser Interface(GUI)based applicationcontainsWindows,Buttons,Text boxes,DialogueboxesandMenusetc.known as GUIcomponents.Whileusinga GUI application,whenuserperformsanaction,an Eventisgenerated.Eachtimean Eventoccurs, itcauses a Messagewhichsent toOStotake action. WhatisEvent? An Eventsrefers totheoccurrence of an activity. WhatisMessage? A Messageistheinformation/requestsent to theapplication.

  7. GUI in JAVA In Java,GUIfeaturesare supportedthroughJFC(Java Foundation Classes).JFCcomprisesallthefeatureswhichareneededtobuild a GUIapplication. PriertoJava 1.2 JFCcomponentswascalledAbstractWindows Tools(AWT).AfterJava 1.2,amore flexibleSwingComponents wasintroduces. A GUIapplicationinJAVAcontainsthreebasicelements.- 1.GraphicalComponent: Itisan objectthatdefinesascreen elementsuch as Button,Text field,Menus etc.Each componenthas certainproperties.Theyare source of theEvents.InjavaItisalsoknown asWidget(Window Gadget).Itcan becontainercontrolor childcontrol. 2.Event: An Event(occurrence of an activity)isgenerated,whenuserdoes something likemouse click,dragging,pressingakey on the keyboardetc. 3.EventListener: Itcontainsmethod/functionswhichisattachedtoacomponentand executedinresponsetoan event.In Java,ListenerInterface storesallEvent-response-methodsorEvent-Handlermethods.

  8. Basic Graphical Controls of JAVA (Swing controls) The palette ofcontrols inNetBeans IDE offers various JavaSwing, thatcanbe usedinApplication frames/ Window/ Form.Commonlyusedcontrolsare- jFrame:UsedasaBasicWindoworform. jLabel:AllowsNon-editabletextoricontodisplayed.       jTextField:allowsuserinput.It jButton:Anactionisgenerated jCheckBox:Allowusertoselect iseditablethroughtextbox. whenpushed. multiplechoices. jRadioButton:Theyareoptionbuttonwhichcanbeturnedon oroff.Thesearesuitableforsingleselection. jList:Givesalistofitemsfromwhichusercanselectoneor moreitems. jComboBox:givesdropdownlistofitemsornewitemcabbe added.ItiscombinationofjList+jTextField. jPanel:Itiscontainercontrolswhichcontainsothercontrols usingaframe.   

  9. Events Handlingin JAVA GUIApplication An eventisoccurrence of some activitieseitherinitiatedbyuserorby thesystem.In ordertoreact,you needtoimplementsome Event handlingsysteminyourApplication.Threethingsare importantin Even Handling- EventSource: ItistheGUIcomponentthatgeneratesthe EventHandlerorEventListener: Itisimplementedasintheform ofcode.It eventsthroughListenerInterface. EventObjector Message: Itiscreatedwheneventoccurs.Itcontains  event,e.g.Button.  receivesandhandles  alltheinformation abouttheevent etc. which includesSource of eventandtypeof event Event Source Event Listener Reaction Event occurrence Event object/ Message

  10. Commonly used Events & Listeners Java APIoffers numeroustypesof eventsandevent listeners. Thecommonlyused events are- ActionEvent: TheActioneventsoccurredwhen user completes an actionon componentslike JButton, JCheckBox, JTextFieldetc. TohandleActionEvent,ActionListner interface isused. FocusEvent: TheFocuseventoccurredwhen anycomponentsgainsor losesfocuson components likeJButton, JCheckBox, JTextFieldetc. TohandleFocusEvent, FocusListnerinterfaceisused. KeyEvent: TheKey Eventoccurredwhen a key ispressedonthekryboard on input enabledcomponents, JTextFieldetc. To handle Key Event,KeyListner interface is used. MouseEvents: When a mouseisclicked,enteredor leaveda component area ofacontrol then Mouseeventisgenerated. Anycomponentcan generatethisevent. To handle MouseEvent, MouseListnerinterfaceis used. WindowEvent: WindowEvent occurredwhenuser opensorclosesa Windowobject. Thisevent isgeneratedinternally by thesystem. To handleWindowEvent, WindowListnerinterfaceisused.     

  11. JAVA character set Characterset isa set of validcharactersthata languagecan recognize.It maybeany letter, digitor anysymbolor sign. JAVA uses 2-ByteUNICODEcharacterset, whichsupportsalmostallcharactersinalmost alllanguageslikeEnglish,Chinese,Arbicetc. In Unicode,first 128 charactersaresimilarto ASCIIcharacterset.Next128 characterequal toExtendedASCIIcode.Restare capableto supportotherlanguages. Any characterinUnicodecan berepresented by\ufollowedby4 digitHexadecimalnumber. E.g.\u0394torepresentDeltaSymbol.

  12. JAVA Tokens The smallestindividualunitin a program is known as Token. It may anyword, symbols or punctuation mark etc. Followingtypesof tokens Keywords Identifiers Literals Punctuators(;[]etc) used in Java- Operators (+,-,/,*,=,==etc.)

  13. Keywords inJava Keywords are the reserve words that have a special meaning to thecompiler. Key words can’t be used asidentifiers or variable name etc. Commonly usedkey words are- char,long, for,case,if, double,int, short, void, main, while , new etc.

  14. Identifiers in Java Identifiersare fundamentalbuildingblock ofprogramand usedasnamesgivento variables,objects, classesand functionsetc. The followingrulesmustbefollowedwhileusing identifiers. Identifiersmayhavealphabets,digitsanddollar underscore(_)sign. ($), They They They They mustnotbeJavakeywords. mustnotbeginwithdigit. canbeofanylength. areCaseSensitiveie.Ageisdifferentfrom age. Example ofValididentifiers- MyFile,Date9_7_7,z2t09,A_2_Z,$1_to_100,_chketc. Example ofInvalididentifiers- Date-RAC,29abc,My.File,break,for

  15. Literalsin Java Literals or constants are dataitems have fixed datavalue. that Java allows several IntegerLiterals FloatingLiterals BooleanLiterals CharacterLiterals StringLiterals Thenullliterals types of literals like-

  16. IntegerLiterals An integerconstantor literalsmusthave one+/-digitwithoutdecimalpoint. Java allowsthreetypesof integerliterals DecimalIntegerLiterals (Base10) e.g.1234,41,+97,-17etc. Octal IntegerLiterals(Base 8) e.g.010,014(Octalmuststartwith0) HexadecimalIntegerLiterals (Base 16) e.g.0xC,0xab(Hexnumbersmuststartswith0x) at least - L or U suffix can usedtorepresentlongand unsignedliteralsrespectively.

  17. Floating / Real Literals A realliteralsarefractionalnumbershavingatleastone digitbeforeandafter decimal pointwith+ or– sign. The followingare validreal numbers- 2.0,17.5,-13.0.-0.00626 The followingare invalid real numbers- 7, 7.,+17/2,17,250.26etc.  A realliterals mayberepresentedinExponentformhaving Matissa andexponentwithbase10(E). Mantissa maybe a proper realnumberswhile exponentmustbeinteger. The followingare validreal inexponentform- 152E05,1.52E07,0.152E08,-0.12E-3,1.5E+8 The followingare invalid realexponentnumbers- 172.E5,1.7E,0.17E2.3, 17,22E05,.25E-7 

  18. OtherLiterals TheBoolean LiteralsrepresentseitherTRUEorFALSE.Italways Boolean type.  A nullliteralsindicatesnothing.Italwaysnulltype.  CharacterLiteralsmustcontainone characterandmustenclosed insinglequotationmark. e.g.‘a’,‘%’,‘9’ ,‘\\’etc. Javaallowssome non-graphiccharacters(whichcan not betyped directlythroughkeyboard)byusingEscapesequence(\). E.g.  \a \n \v \” (alert), (newline), (verticaltab), (doublequote) \b(backspace), \r(returnkey), \\(backslash), \f(Formfeed), \t(Horizontaltab), \’(singlequote), , \?(questionmark), \0(null)etc. StringLiteralsisasequenceof zeroormore charactersenclosed indoublequotes.E.g.“abs”,“amit”,“1234” ,“12A” etc. 

  19. Data types inJAVA Datatypesare meanstoidentifythe typeof data andassociatedoperationsofhandlingit. Java offers twotypesof datatypes. Primitive: Theseare in-builtdatatypesofferedbythe compiler.Javasupports8 primitivedatatypes e.g.byte,short,int,long,float,double,char, boolean. Reference: Theseare constructedbyusingprimitivedata types,as peruserneed.Referencedatatypes storethememoryaddressof an object.Class, InterfaceandArray are the exampleof Reference Datatypes.

  20. Data Types inJava DataTypes Primitive (intrinsic/Fundamentals) Reference Numeric Non-Numeric Classes Interface Arrays Integral Fractional Character Boolean Byte float char short double int long String Datatype is also used inJava asReference datatype

  21. Primitive Data types Type Size Description Range byte 1 Byte Byte integer -128 to +128 short 2 Byte Short integer -32768 to +32767 int 4 Byte integer -231to 231-1 long 8 Byte Long integer -263to 263-1 float 4 Byte Single precision floating point (up to 6 digit) -3.4E+38 to +3.4E+38 double 8 Byte Double precision floating (up to 15 digit) -1.7E+308 to 1.7E+308 char 2 Byte Single character 0 to 65536 Boolean 1 Byte LogicalBoolean values True or False L suffix can used to indicate the value aslong. By default Javaassumefrictional value asdouble,Fand D suffixcanbe used with numberto indicate float and double valuesrespectively.

  22. Working with Variables A variableisnamed memory location,which value ofaparticulardatatype. DeclarationandInitializationofvariable- <data type> <variableName>; Example: int age; double amount; double price=214.70,discount =0.12; String name=“Amitabh” long x=25L; byte a=3; float x=a+b; holds a data   By defaultallNumericvariablesinitialized with0,and  character andreference variablewithnull,booleanwith false,ifitisnotinitialized. The keyword finalcanbe usedwithvariabledeclarationto indicateconstant. E.g.finaldouble SERVICE_TAX=0.020 

  23. Text interaction in JAVA GUIs In GUIapplication often we require to store the values of textfields to variable or vice-versa. Javaoffers three method for thispurpose- getText(): It returns the text stored in the text based GUIcomponents likeText Field, Text Area,Button, Label, Check Boxand Radio Button etc.in string type. e.g. Stringstr1=jTextField1.getText(); parse…….()   This method convert textual data Byte.parseByte(Strings) Short.parseShort(Strings) Integer.parseInt(strings) Long.parseLong(strings) Float.parseFloat(strings) from GUIcomponent in to numeric type. – – – – – – string string string string string string into into into into into into byte. short. integer. long. float. double. Double.parseDouble(string s) e.g. int age=Integer.parseInt(jTextField1.getText()); setText() This method stores string into GUIcomponent. e.g. jTextField1.setText(“Amitabh”); jLabel1.setText(“”+payment); 

  24. Displaying Dialogue Boxesin JAVAGUIs InGUIapplicationoftenwe requireto displayamessage in theDialogBoxescontainingOKbuttontoclose theDialog Box.The followingstepscanbeusedto display amessage inadialogbox. Firstly,youneedto importjOptionPaneswingcontrol atthe topofprogramcode,by typing- import javax.swing.JoptionPane; Whenrequiredyoumay displayamessageby following code inamethod- JOptionPane.showMessageDialog(null,“Hello..“);   Innon-GUIapplication oratconsolewindowyoumay use System.out.print() methodto display amessage. e.g. System.out.print(“Hello…”); System.out.println(“How are you?”); 

  25. A sample JavaProgram //Anon-GUIProgramto calculateareaofcircle// importjava.io.*; classMyProgram { publicstaticvoidmain(String arg[]) throws { final floatPI=3.14; floata; intr =5; a=PI*(r*r); System.out.println(“Areaofcircle=“+ a); System.out.println(“Bye…”); } } IOException

  26. Operators in Java Theoperatorsaresymbolsor words,which performspecifiedoperationon itsoperands. OperatorsmayUnary,BinaryandTurneryas numberof operandsitrequires. per Java offers thefollowingtypesof ArithmeticOperator Increment/DecrementOperator RelationalorComparison Operators Logical Operators Assignment Operators Other Operators. Operators:-

  27. 1. ArithmeticOperators + Unary plus Represents positive values. int a=+25; - Unary minus Represents negative values. int a=-25; + Addition Adds two values int x= a+b; - Subtraction Subtract second operands from first. int x=a-b; * Multiplication Multiplies two values int x= a*b; / Division Divides first operand by second int x=a/b; % Modulus (remainder) Finds remainder after division. int x= a%b; + Concatenate or String addition Adds two strings “ab”+”cd” ”abcd” “25”+”12” ”2512” “”+5 ”5” “”+5+”xyz””5xyz”

  28. 2. Increment& DecrementOperator Java supports ++ and-- operator whichadds or subtract1 from its operand.i.e. a=a+1 equivalentto ++aora++ a=a-1 equivalentto --a or a-- ++ or -- operator mayusedin Pre or Post form. ++a or --a (increase/decreasebeforeuse) a++ or a– (increase/decreaseafter use) Ex.Find valueofP?(initially n=8 andp=4) p=p* --n; p=p* n--; 28 32 Ex.Evaluate x=++y+ 2yif y=6. 21 = 7+14 =

  29. 3.RelationalOperator Relational operators returnstrue orfalseasperthe relationbetweenoperands. Javaoffers < <= > >= == != the followingsixrelational operators. lessthan lessthanorequal to greater than greater thanorequalto equalto notequalto Relational operatorssolvedfromleftto right. Ex: 3>=3 3!=3 a==b true false trueifaandbhave thesamevalue. a<b<c=> (a<b)<c true ifaissmallest.

  30. 4.Logical Operator Logicaloperatorsreturnstrueorfalseaspertheconditionof operands.Theseareusedtodesignmorecomplexconditions. Javaoffers operators. the following six (5 binary and 1 unary) logical Operator Name use Returnstrueif && And x&&y Xandybothtrue || Or x||y Eitherxoryistrue ! Not !x Xisfalse & Bitwiseand x&y Xandybothtrue | Bitwiseor x|y Eitherxoryistrue ^ Exclusiveor x^y Ifxandyaredifferent Ex:5>8||5<2 (false) 1==0||0>1 (false) 6<9 && 4>2 (true) 6==3&&4==4 (false) !(5!=0) (false) !(5>9) (true)

  31. 5.AssignmentOperator InJava=operatorisknownasAssignmentoperator,it assignsrighthandvaluetolefthandvariables. Ex:intx=5; z=x+y; Javaofferssomespecialshortened Assignment operators, which are used to assign values on a variable. Operator use Equivalentto += X+=y X=x+y -= X-=y X=x-y *= X*=y X=x*y /= x/=y X=x/y %= X%=y X=x%y Ex: x-=10 x%=y =>x=x-10 => x=x%y

  32. 6. Other Operators InJavasome otheroperators are also used for various operations. Some operators are- Operator Equivalent to ?: Shortcut of If condition (turnery operator) <Condition> ?<true action>:<false action> [] Used to declare array or access array element . Used to form qualified name(refer) (type) Converts values as per given datatype new Creates anew object instanceof Determines whether the first operatoris instance of other. <<,>> Performs bitwise left shift orright shift operation. ~ (compliment) Inverts each bit (0 to 1 or 1 to 0) Ex. result =marks>=50 ?‘P’:‘F’ 6>4 ?9:7 evaluates9because 6>4 istrue.

  33. Operator’s Precedence Operator’sprecedencedeterminestheorderinwhichexpressionsare evaluated. Thereiscertainrulesfor evaluatingacomplexexpression. e.g.y=6+4/2 (why8not5?) Operators Remark Associativity .[]() ()usedtomakeagroup,[]usedforarrayand.Is usedtoaccessmemberofobject LtoR ++--!~ Returnstrueorfalsebasedonoperands RtoL New(type) Newisusedtocreateobjectand(type)isusedto convertdataintoothertypes. RtoL */% Multiplication,divisionandmodulus LtoR +- AdditionandSubtraction RtoL ==!= Equalityandnotequality LtoR & BitwiseAnd LtoR ^ BitwiseExclusiveOr LtoR | Bitwiseor LtoR && LogicalAnd LtoR || Logicalor LtoR ?: ShortcutofIF RtoL =+=-=*=/=%= VariousAssignmentoperators RtoL

  34. Expression inJava Anexpressionisavalidcombinationofoperators,constants andvariable andkeywordsi.e.combinationofJavatokens. Injava,threetypesofexpressionsareused. ArithmeticExpression Arithmeticexpressionmay containone ormore numericvariables, literalsandoperators.Twooperandsoroperatorsshouldnot occur incontinuation.    e.g.x+*y and q(a+b-z/4)isinvalidexpressions. Pureexpression:whenalloperandsare of same type. Mixedexpressions:whenoperandsare of different datatypes. CompoundExpression Itiscombinationof twoormore simpleexpressions.  e.g.(a+b)/(c+d) LogicalExpression (a>b)||(b<c)  LogicalorBoolean expressionmay have twoormore simple expressionsjoinedwithrelationalorlogicaloperators. e.g.x>y (y+z)>=(x/z) x||y&&z (x) (x-y)

  35. Type Conversion in JAVA The process of converting one predefined typeinto anotheriscalled type conversion. In mixed expression, various types of constant and variables are converted into same type before evaluation. Java facilitates two types of conversion. Implicit type conversion Explicit type conversion

  36. Implicit TypeConversion Itisperformedbythecompiler,whendifferentdatatypes areintermixedinanexpression.ItisalsocalledCoercian. InImplicitconversion,alloperandsarepromoted (Coercion)uptothelargestdatatypeintheexpression. Ex.Considerthegivenexpression, wherefisfloat, d is double andIisintegerdata type. Result=(f * d) - ( f+ i) +(f /i) double float float double

  37. Explicit Conversion inJAVA Anexplicitconversionisuserdefinedthatforcesto convert anoperandtoaspecificdatatype by (type)cast. Ex.(float)(x/2)suppose x isinteger. The resultofx/2isconvertedinfloat otherwise itwill give integer result. Inpure expressiontheresultantisgivenasexpression’s datatype. e.g.100/11will give 9not9.999(since bothare integer)   Inmixedexpressionthe implicitconversionisapplied (largesttypepromotion) e.g.inta,mb=2,k=4thenevaluate a=mb*3/4+k/4+8-mb+5/8  = 2*3/4+4/4+ 8– 2+5/8 8 (6/4willgive 1) = = = 6/4+1+ 8–2+5/ 1+1+8– 2+ 0 8

  38. JAVA Statements A statementinJavaisacompleteunitofexecution.It may consistsofExpression,Declaration,Control flow statementsand mustbe endedwithsemicolon(;) Statementsformsablock enclosedwithin blockmayhaveno statement(empty). { }. Even a E.g. If(a>b) {……. ……. } Note: System.out.print(‘h’+’a’)willgive169 System.out.print(“”+‘h’+’a’)willgiveha System.out.print(“2+2=”+2+2) will give 2+2=22 System.out.print(“2+2=”+(2+2)) will give 2+2=4

  39. ProgrammingConstructs inJAVA Ingenerala programis executedfrombeginto end. Butsometimes itrequired toexecute the program selectivelyor repeatedly asper definedcondition. Suchconstructs are calledcontrolstatements. TheprogrammingconstructsinJava,arecategorizedinto- Sequence: Statements are executed into-p downsequence. Selection(conditional): Executionofstatementdepends onthe condition, whetheritis True or False. (Ex.if..,if…else, switchconstructs) Iteration(Looping): Statementisexecuted multiple times (repetition)till the defined conditionTrue or False. (Ex. for.. , while… ,do..whileloop constructs)   

  40. Diagrammatic Representation Statement 1 Statement 2 Statement 3 True Condition Statement (s) False Statement (s) Selectionconstruct Sequence construct False True Condition Exitfrom Statement (s) loop Iteration Construct

  41. Selection statement (if..) The if…statementisusedtotestacondition.Ifdefined conditionistruethe statementsare executedotherwise they are ignored. The conditionmay besimple or etc.)and mustbe enclosedin( complex ). (using&&,|| Expressiondefined True orFalse. as condition must be evaluated as if(num>0){ jLable1.setText(“Numberispositive”); } Syntax if(condition) { statement1; …………….. } if(ch>=‘0’&&ch<=‘9’){ jLable1.setText(“Itisdigit”); } In case of single statement inif…the useof{} isoptional.

  42. Selectionstatement (if..else..) The if…else.. alsotestscondition.Ifdefinedconditionis true else the statementsinTrue block are executed otherwise block is executed. if(condition) { statement1; …………….. } else { statement2; ……………. } if(num>0){ jLable1.setText(“Numberispositive”); } else jLable1.setText(“Numberis zero ornegative”); { } if(age>=18) jLable1.setText(“EligibletoVote”); else jLable1.setText(“NoteligibletoVote”); In case ofsingle statement {} isoptional.

  43. Nested if... Anif…orif..else..mayhaveanotherif..Statementinitstrue blockorinfalseblock.ItisknownasNestingofif(placingan ifinsideanotherif). if(condition1){ else{ } if(num>0) { jLable1.setText(“Numberispositive”); } else { if(num<0) jLable1.setText(“Numberisnegative”); jLable1.setText(“Numberis zero”); } Nested if..block if(condition2) {…….. } else {……… } else if(condition3) {…….. } else {……… }

  44. If…else…If ladder When aelseblockcontainsanotherif.. andthisnestedelseblock may have anotherifandso on. Thisnestingisoftenknown as if..else..ifladderorstaircase. if(condition1) statement 1; else if(condition2) statement 2; else if(condition3) statement 3; else if(condition4) statement 4; ……… ……… else statement n; if(day==1) else if(day==2) else if(day==3) jLable.setText(“Tuesday”); if(day==4) else jLable.setText(“Thrusday”); if(day==6) else jLable.setText(“Sunday”); jLable.setText(“Monday”); else jLable.setText(“Wednesday”); if(day==5) else jLable.setText(“Friday”); jLable.setText(“Saturday”);

  45. Conditionaloperator andif.. statement The ?:(conditional operator) maybeusedasalternative to if..else..statementinJava. Incontrastto if…,?:ismore conciseandcompactcode it islessfunctional. ?:producesanexpressionsothatasinglevaluemaybe incorporatedwhereasif..ismore flexible,whereasyou mayusemultiplestatements, expressionsand assignments. When?:isusedasnestedform,itbecomesmorecomplex anddifficulttounderstand.     Expression1?Expression2:expression3; Syntax if(a>b) c=a; else c=b; C=a>b?a:b;

  46. The switch statement Multi-branching selection can be made in Javaby using switch statement. It test successively, thevalue of an expression (short,int, long or char type), when match is found,the statements associatedwith constant is executed. switch(day) {case1:Dow=“Sunday”; break; case2:Dow=“Monday”; break; case3:Dow=“Tuesday”; break; case4:Dow=“Wednesday”; break; case5:Dow=“Thursday”; break; case6:Dow=“Friday”; break; case7:Dow=“Saturday”; break; default:Dow=“WrongInput”; } jLable.setText(“Weakday”+Dow); switch(<expression>) { case <const 1>:statement (s); break; case <const2>:statement (s); break; case <const2>:statement (s); break; ……….. [default :statement (s);] } 1.Notwoidenticalconstantcanbeused. 2.Default..isoptionalmaybeanywherein switchblock.

  47. Switch andif..elsestatement Theswitchandif..elsebothare usedtomake aselectionconstruct inJava,buttheresome differences. Switchcan testonlyequalitywhereasif.. Canevaluateany type of relationalorlogicalexpression. In switchasinglevalueorconstant can betestedbutinif.. more versatileexpressioncan betested. Theswitchstatementcanhandleonlybyte,short,intorchar variablebutIf..can testmore datatypelikefloat,doubleor stringetc. Nestingofswitchwithswitchorif..maybeused…. if(condition1) {switch (exp1) {……. ……. } } else { …….; } switch(exp1) {……. ……. } ………… {case<cont>:switch(exp2) }

  48. Iteration (looping) statements Iterationor loopingallow asetofinstructionstobe executedrepeatedly untilacertainconditionistrueorfalse. Asper placingofconditiontobe tested,aloopmay be Entry-controlled orExit-controlled loop. InEntry controlled loop, aconditionistested(pretest)beforeexecuting the statements.WhereasinExit-controlledstatementsare executedfirstthenconditionistested(posttest),which ensuresatleastontime executionofstatements. Asper numberofexecution,aloopmay beCounter- controlled orSentinelloop. Counter controlledloopsare executedfixednumber oftimes, butsentinelloopmaybe    stoppedanytimebygivingitssentinelvalue.i.e.number executioncannotbeforecasted. A bodyofloopcontainsablock,havingstatementstobe executed. of 

  49. The for.. loop In simpleuse,a for..Loop isEntry-controlledandcounter controlledloophavingfixednumberof iteration. for(initializationexp (s);condition;update exp (s)) {……….. ……….. Loopingstatements } for(int i=1;i<=10 ;i++){ System.out.println(“”+i); } //loop to find even nos. upto 50 for(int i=0;i<=50 ;i=i+2) System.out.println (“”+i); //loop to find factorial int fact=1,num=5; for(int i=1;i<=num;i++) fact=fact *i; System.out.println (“factorial=”+fact); //loop to get sumoffirst 10 nos. int sum=0; sum=sum+i; System.out.println(“”+sum); for(int i=1;i<=10 ;i++ ){ }

  50. Variation in for.. loop Multiple initializationandupdate expression A for..Loop may containmultipleinitializationand/or expressionsseparatedby(,) for (i=0,sum=0;i<=n;sum++,i++) OptionalExpressions In forloopinitialization,conditionandupdatesection omitted.Notethat(;)mustbepresent. for (;i<=n;) Infiniteloop  update  may be  For..Loop may beendless(infinite)whendefinedconditionis alwaystrueoritisomitted. for (;;) Emptyloop for..Loop may not containany statementinloopingbodyi.e. Emptyloop. If (;)placedafterfor..Loop thenemptyloopis created. for (int i=1;i<=300;i++); Variabledeclaredinsidefor..Loop can’taccessedoutsidetheloop. Sinceitisoutof scope.  

More Related