You are on page 1of 19
Introduction to Java using Blue) ABOUT BLUE) To Leam the Basic Construct of aj that Program BlueJ is a development environment allows you to develop Java programs quickly Fundamentals for writing a Blue} To Learn to Compile, and Execute and easily. Its main features are that it is: ¥ ple BlueJ has a deliberately smaller and simpler interface. Interactive BlueJ allows you to interact with objects. } BlueJ runs on Windows, Mac OS X, Linux and other platforms which # java. It can also run without installation from a USB stick. In the late nineties, Michael Kélling developed a pedagogical language and environment called Blue as part of his PhD work. BlueJ is a port of Blue to Java and was first released in 1999 Thanks to generous support from Sun Microsystems (and more ¢ fou can ¢ cently Oracle), BlueJ development and support has continued Buel a ince then, GETTING STARTED Blue] is an IDE (Integrated Development Environment). It includes ¥ an editor, which you use to write your programs a debugger, to help you find your mistakes @ viewer, to see the parts of your program ‘an easy Way to run Java programs an easy way to view documentation these steps to create a new project using BlueJ. © create 4 project, open BlucJ and select New from the Project menu (Fig. 6.1), ime the project, click on Create (Fig, 6.2). acclass, click the New Class button and specify the class name (Fig. Introduction to Java using Blue) ABOUT BLUE) To Leam the Basic Construct of aj that Program BlueJ is a development environment allows you to develop Java programs quickly Fundamentals for writing a Blue} To Learn to Compile, and Execute and easily. Its main features are that it is: ¥ ple BlueJ has a deliberately smaller and simpler interface. Interactive BlueJ allows you to interact with objects. } BlueJ runs on Windows, Mac OS X, Linux and other platforms which # java. It can also run without installation from a USB stick. In the late nineties, Michael Kélling developed a pedagogical language and environment called Blue as part of his PhD work. BlueJ is a port of Blue to Java and was first released in 1999 Thanks to generous support from Sun Microsystems (and more ¢ fou can ¢ cently Oracle), BlueJ development and support has continued Buel a ince then, GETTING STARTED Blue] is an IDE (Integrated Development Environment). It includes ¥ an editor, which you use to write your programs a debugger, to help you find your mistakes @ viewer, to see the parts of your program ‘an easy Way to run Java programs an easy way to view documentation these steps to create a new project using BlueJ. © create 4 project, open BlucJ and select New from the Project menu (Fig. 6.1), ime the project, click on Create (Fig, 6.2). acclass, click the New Class button and specify the class name (Fig. ‘The stripes show that the class "Drawing” is not ‘Compiled (ready to run) click the new class to edit it, 1: Terminal Wind class and then compile it. ss cannot run without an object. cate an object, right-click a class after ling and select a function having the ce name as the class name. rbject is created which appears as a ox below. To execute a program, this Fig. 65 has to be executed. click on the object and select any function that you have created (Fig. 6.4). sutput will appear in the terminal window. CHARACTERISTICS OF BLUEJ 2. Light weight code |. Write Once Run Any i rite Once Run Anywhere 4, Built in Graphics 3. Security 6. Support Multimedia Platform Independent DAMENTALS FOR WRITING A PROGRAM IN JAVA se, Java has some Unicode character set as a valid set of cha Java recognises the Unicode chara + nee tors that are used to identify and isolate the diff variable is @ name given to a particular location in the memory i can be stored, retrieved and altered during program execution A constant is a named data storage location in the memory where can be stored and retrieved but cannot be altered during program ex: a An express combination of constants, variables and operat A function is a piece of code that is called by name. Data can be pe a function and can be returned (return value) from itas well. It is a user-defined data type that contains data members and member functions together ina single unit. Objects are instances of a class The data type of a variable/constant refers to the type of data it can Each data type has a particular size and range of values that it can support. Java 9 ‘vo types of data types: Fundamental and Reference data type. Int, byte, short I float, double, Boolean and char are the fundamental d: ata types in Java, Class ob and various types of array variables come under reference data type EiPrint (“Welcome This 4s yee PER kag Rigas. v: n clisplays the following oupu ny first Program using Biyey ode in Bl ust have at Tt ). System.out.print() is a fy stcments displays “Weleom, la : i Fist Line states this class name *, ProBraM is written inside this Cursor to the next line hhese two functions also ) and System.out.printing) are. present 1we package). Java.tang is imported by program in Java, There are several Such functions that are being used, 1s are used to group statements belonging to one function or ‘program statement. parenthesis ({ ) should have a matching closing parenthesis ( }) ents can be included in the program by prefixing the statement with *//* for ymments. Comments add clarity to the program and make it readable and Sle by others. Multiple line comments ean be added by enclosing the statements id Documentation comments like author (your name) crsion (a version number or a date) also be used to clarify the details of a program: F the terminal window ' Ad Ject options from t clear any previous output in the terminal windaMsS° a tnd check the option ‘clear sereen at method call”. “(us try out a few programs in BlueJ: Program 2: The above program initialises two integers a and b with two static values 5 and 3 Fespectively and displays the sum of these {wo numbers, The integer variable sum is declared with the datatype int. sum stores the value of the a+b. Then, the System.out.print () statement displays the result with a proper message. The message is concatenated with the variable using the + operator. Note that this program assigns static inputs ait are declared within the program code if Inputs can be accepted from the user by Meters, using the BufferedReader or by Scanner class. The last two require immer to know the concept of Objects and related programs. We limiting our inputs to the parameter is chapter. Program 3: Program to divide a ang and remainder, display quotient and mint a, dae Here, int a and int b are the set off parameters that have to be given whe function display is called, Then, the will start based on the values that ha given. The two operators / and % are integer division and remainder, resj However, this program will fail to wo equal to 0 which will cause an exceptig Tuntime error as division by 0 isa math error. Progi A: atea = radius? and circumference = 2 mradius where x 3.141, aCi rcumference (double r) ne area ie”tarea), circumference is Aertese y; and cir have been initiali lised as double as they may hold fractional 'o swap two numbers Using 8 temporary vata able. numbers before’ ewaj i £: pping are "tnl¢™ “4n2) ; nunbers after swapping are “tnd * “4n2); jam to swap two numbers without using a temporary variable. (“numbers before swapping sre y tart 74n2)? nant * "402)7 (“numbers after Swapping 25° +nlt FLOW OF CONTROL h program statements are performed, order in whic ising following statements; Flow of control refers to t execution of program statement can be controlled « tatements in Blued ection control 2. IF ELSE statement 3. nested IF gf 1. IF statement 4. conditional operator 5, SWITCH statement iteration statements or looping statements in Blue 7. WHILE statement 8. DO WHILE 6. FOR statement Selection Control Statements in Blue) The selection statements allow to choose a set of statemi condition. The expression or condition is any expression built using relational oper either yields true or false condition. [fno relational operators are used for compar expression will be evaluated and zero is taken as false and non-zero value is taken} nts for exer 1. IF statement: \t is a selection statement, that is, an associated statement exe associated condition is true, The syntax is as follows: where, ifsyntax if : Keyword Condition Any arithmetic/logical relational express statement: Any BlueJ valid singh Program 7: "” Program 8: ) function accepts the age. If In this : case, sequential if statement Its are used an or equal to 18 years the one after visplayed. Otherwise 6 lm ae the other and test for the greatest and no output is a 2 x assumed o be he largest. Then itis SHR a siete. ren eae sequentially and the sx statement: This is also a selection statement, just Ii . just like if, but here i jjowed when associated condition i eee neue urse of acHot ion is false, that is, in both cas, it follows a ion) | ca if, else 2 Keywords sent | a , J Condition + Any arithmetic! nent logical/relational expression statementl,statement2 Any valid Blued single ‘or compound statement inple of Hf Else Statement i van 9: Program to display whether a number is even or odd, zvenodd ) display ( ant 9D) (ns2) ==10) system. out Peete aan Gis an even number”); er ‘odd number") ; er and divides it by 2 and if ats an integer from the user as a paramet otherwise as odd (ested by using the =), it displays the number as even, dded IF): This is a conditio er if or if else statement to check multiple conditions. wn where an if statement can be placed The syntax of Nested if statement isas follows, logical && operaton(AND) and || operator Qi can be checked using Syntax for multiple conditions 12)) the above example, statement! will be I the above example, Statement executed if either condition! or con be executed. will be executed if and ony if both conditions are false. Bplay (int a, int b i (b>c)) @ut.print (a+ i) && (b>c)) BOE print (bt ” is the largest number”) Print (St Oia etengeaae a accepts IhFee unequal integers from the ser and displays the largest inal operator: This is also called t "Mary operator and itis oti ment. The general syatax OFS cpersioe'Wasfolown ce np) ?Statement : Statementay 's any valid arithmetie/relational/ Logical Expression Any valid Java statement(s) Any valid Java statement(s) nil, executes when condition results in true otherwise statement? executes. MaxTernary play(int a, int B) x=a>b?aib (max) tem. out .print( the two cemary operator used intend of i ee ons . ee E phere into a variable called max, which is displayed. aoe ‘tional operator to find the greater of the three mum ramming tool. Program 12e ase Maxieenaxy voidiaammmmmmer® 2, int D) fe increase clarity in tne switeh stator ble and execute statements switch syntan on Stal The constant with the case is either integer or char type values. It cannot evaluate fldaiy 1 fring type values, Fach case should have @ break statement as the last statement Hatement takes the control out ofthe switch statement, The absence of the break stat 1, for loop st lise execution of staiements in the next case till the break is encountered. This is z For Loop 8 Syotem.out print ("\n Monday") break; out.Print("\n Tuesday") out Print ("\n Wednesday") out. print("\n thursday") ; out.print("\n Friday") out.print("\n Saturday") out peint ("\n Sunday"); out print ("\n Wrong Choice... Try again") ner is entered and put as a switeh variable: This variable is then compared Constants from 1 to 7 and acts seeontiBeHy ‘If this day does not match any va 7 then the default case is executed: ements or Looping Statementsin Blue) « loops are avaiable in Bluel tatement 2 While’ statement 3, do while statement Loop statement: This loop 18 basically used when the number of iterations is exactly tialization; condition sncrement/decrenent) tement oF anueseaazation a ment/decrement ) ‘ sratement ) cr A Program 16: Program 1 Programls. Prog (r01 2<=100 a ut. Pett na BSatement: This is also called Entry Controlled Loop. It means firstly ef Band ifthe condition is true then the associated statement run, saiement ents This is also called Exit eos trolled loo the associated condition i — the associ Suoee I associated statement > do while loop syntag int rao; do c ret; Syatem.out.printin(r) } while (rcs) ) ) rent: Break statement is an unconditional statement, it is used to terminate any J send the control at the very first statement following that loop. Syntax break; be used as an unconditional statement as well as a conditional statement . Unconditional Statement > // inside while loop —_/ im for Loop class WhileBreak class rorBreak ( ( id display () void display) ( int x; fox (R=1;x<=100;x1+) ‘ Gystem, out .printin (x) break “ss xt oak peintia() pwndle (x< Continue statement: This statement lets control imp on the conditional checking stater Well as unconditional statemer Example of Continue Statemen While loop ass WhileContinue Do while loop while (x<100) xtL if(x%21=0) continue System. out pri println (x) while (%<100) } } Bei 2 > 7!.1975507 nawure 2 quer 10 98 100 7i>1;i--) skip the remaining part ofthe loop ang ‘i, Continue statement can be used as cong For loop class Forconeinug void display () ( ant x for (x=1;x<=100 jig { System. out prince continue xe , getch() return 0 47: Display the factorial ofa number, The factorial of a number ‘N° (NJ) is equ BS . mn ( “Factorial of” 4 number+"is”+fact) ; oy sisplay whethes i j ther a number is prime oF not zesvit (int number) number is divis visible jcenumber/2 } ib) by any number from 2 to 3) ==0) (The number is a prinesnbaiesi)7 prime number"); orint (The number 35 RCE = the correct answer: lowing isa literal im (y+ Wich ofthe following isan example OF iteration? (b) Switch. (while (@ Break ich of the foll n Java? @r vif 3, What is us Jed when both the conditions of an expression must be (&& @l (by! 4, The following is optional in case of witch case construct: (b) break (c both aandb (a either of a and b @r (@) default 5, Boolean can support (a) ve () false (opeithera orb (a) both aand are ‘True or False: whether the following statements ing an object B. State 1 Ack 2. 185.0 can be stored inan int datatype jass can be executed without ¢ BA Swit condition cn support it datatype Break Defiu operands ators work on three 1 when the continued needs to be found 1 controlled and entry controlled 1oops + based on the number of operands they support. undamental datatypes with size he two functions of System. out printing’ A datatype that can store fractional values, 2, Aselection statement 6. Aconstn that uses default 7. Do while is this type of loop 8. A statement that prevents fall through, DOWN 1. Placeholder of the program 5. A finite loop 2. A fundamental datatype that can store only: bvumbers 3. Datatype to store one letter 4. An entry controlled loop, calculate the simple interest and amount where the principal (P) is Label th 5% and time (T) is 5 years. Name tl 3. What ig owing (show the 3. Write 0 program 16 aegept character ‘parumeter and display whether the elarweter ‘s atowereae vowel of not ising jwlich case statement, 4, Write @ program to accept the three sides of ‘wiangle, Diyplay Aho tangle exit oF Wo IEA sista dlnplay whether tequila, oveaten ‘oe selene, Hit dogs not exist thon dpi proper message, g- Which lass as etn he nae WH ywn above. j Sma a nave vor been compiled taba rosa ht VE por ° 2, Name with prog”? 3. What is being don ,

You might also like