0% found this document useful (0 votes)
315 views28 pages

CHPTR 4 N 5 Compt 16-Jun-2021 13-32-15

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)
315 views28 pages

CHPTR 4 N 5 Compt 16-Jun-2021 13-32-15

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/ 28
Types of operators: Arithmetical (Forms of and Prefix operators), Binary and Ternary), mbers of class using dot operator, Output statement: System.out.print() and System.out printin(), Java Programs on assignment statement Hierarchy of operators. INTRODUCTION Incomputer programming, you often need to perform some Basic Operation arithmetical or logical operations. In such circumstances, you need operators to perform these tasks. Thus, an operator is basically a symbol or token, which performs arithmetical or logical operations and gives meaningful result. The values, which are involved in the operation, are termed as operands. Let us consider an expression as: ARITHMETICAL EXPRESSION An arithmetical expression contains variables, constants and arithmetical perators put together, to produce a meaningful result. For example, x+y . (i) m-15 (ii) atas 2*a%b + b*d (®) b*b — grate Se eee ned to a variable then it is know, t ‘Who an arithmetical expression is assigned re ‘ath Arithimetical State 2¢a*beb'b; nt, an ‘ (i) pe m= 1S a-3*a*atb+3%a*h*b-b*b*b; wie 7 1) debtb = date moutprintin(’The va (ii) ne at av 20th + bY (iv) deb t.printin("The value of first expression = “+ans1); System .out.println( "The value of second expression « “+an42); TYPES OF OPERATORS f Tsically, there are thwee types of operators to perform any operation in Jayy ) programming, They are 1. Arithietical Operator 2. Relational Operator 3. Logical Operator Ouputs 1, Avithmetical Operators ‘The value of first expre: . The operators which are used! to perform arithmetical calculations in a program ‘the value of first. expre are known as aritliwetical operaors, Some basic calculations like addition, subtraction, multiplication, division and modulus (to get remainder when a ‘nuinbor is divided by the other number) are often needed during programming, You can use the arithmetic operators like +, = %, / and % respectively to carry cout these calculations, When you write a program in Java, tts necessary t6 represent the arithmetical pete: eee ae can be esprasice nto « jeva epee it baie ATE. perform some Mathematical tasks. They are Here, few examples are illustrated as how mathematical expressions ae» UNM Operator written in Java. i b. Binary Operator ©, Ternary Operator fegorized in the following ways to 4 Unary Operator sebG a An arithmetical operator, which is used to operate on a single operand, is known as the Unary Operator, For example, +, =, +4, ~~, ete. It is further categorised in two ways. ata btb = ote 2Uyb) ptevso0 * Unary (+) Operator ‘This operator is used before the operand, simply as a pointer to a variable, which : 1.030%0% + 1.02.0%%0 results in the same value of the variable. For example, If a © 8, then + a will result in 8 } If a= 10, then + a will result in 10 ‘A sample program to find the value ofthe expressions { Lat + lab + be é 1 ii, a= Sab + Bab? p> mae (-) Operator //-A program to displa 8 Operator is used in the same way as Unary plus (4). It is also used before a Bapresiong nM Yel of expreestons the operand, Unary minus (-) operator reverses the sign of an operand, { For example, Ifa» 4, then = a will result in =A | } __ fre state void main(String args) | Ifa © 0, then ~ a will result in 0 (It is sinless value) 3 | Ha = 3.6, then = a will result in 3.6 Unary increment and decrement operators Unary increment operator (+ +) inereases the value of an operand tn slecrement operator (==) decreases the value of an operand by une Uy Examples Leexed BY Using increment operator it-can be written ax c++ oF +N fi pspet By using decrement operator it ean be written as p= or =P This increment of decrement is used in two different forms. * Prefix When increment or decrement operator is used before the ‘operand, it is 48 prcfis operulor. This operator works on the principle of ‘CHANGE BEFO} ACTION’. It means the value of the variable changes before the ‘operation “i Se Tia aS x remes + Postfix This unary operator i used an operand (whose value is to be increased or decreased by 1). This works on the principle of (CHANGE AFTER THE ‘ACTION’ vans that the operand will be affected after performing the ‘operation " gxample of postfix increment pe5 cu pret 4 ‘nia! Vaio. ————e Final Vakie ———e Counter and Accumulator Counter The counters are numeric variables, which are used for keeping a record of the number of times a process is repeated. A counter is initialized with a numeric value and it increases as the process starts repeating. For example, c= 1; c=ct lorcet; Here, the value of ‘c’ will increase by ‘I’, the moment statement ¢ = ¢ + 1 of c++ is executed. Hence, ‘c’ is referred to as a counter. Accumulator An accumulator is a numeric variable, When defined within a program, it keeps ‘on changing or getting updated with the counter or some other values supplied through input. An accumulator should be initialized to avoid getting garbage value during execution of the program. wie ee) For example, » = 9% al upto of a exch ese Ti: Wn = Hi ed trae se ake te a Saas wi ch tne mies the statement » = 6+ 8 19 Hence,’ in nelerted to as the accra AN eae tions es Shorthand operat! cs Je Cand Cos ngage lw he we EEE ‘of shorthand binary operations, aa txample 8, I a= 12, bb; find the value of a* = 444/64 b44 % I acach shown in the given table. esced A shorthand expression can be written me m0 mt 10 only when a variable is used as an go ap goad accumulator/counter in the expression, ie, ig 9 . the same variable is to be used both after ** * ew ae and before the assignment sign. 12"(++4/6 + b++ % 3); 12 *(13/6 + 8%3) Ans. eta Wa = 48; finda=atetesa, = 12%(242) a= ast tsa ea = 48 48+ = 98 Example 3. ic = 2; then find d= ++c + c++ +4 datictces +4 =3+3+4 _=10 12; then find n = m++ * Example 9. If x = 4; find the value of x+ = x++ * ++x % 2; ‘Ans. Xt = xtt t4K % 2; = 4+ (46) %2 = 4+ (24%2) =4+0 =4 pad fast +b; 48+ (13 15)/48 +14 48+ (65 / 48) +14 =48+1+14 =8 b, Binary Operators a : ehich deals with two operands, is known as, the Bonary Arithmetic Operator. For example, +, -, *, / and %, etc. A table is given below to illustrate Binary Arithmetic Operators: ‘Addition ‘ asb Returns the sum 27 ‘Suibvraction 2 a-b Returns the difference "7 Mulkipbcation atb Returns the product 110 Division afb Returns the integral part 4 ModulusRemainder % ——afeb—_Returns the remainder 2 A sample program is illustrated as: class Result { public static void main(String args{]) System.out printin("The su System.out-printin(“The difference Ha) System out printin(“The product="+(a*b)) System.out-printin("The quotient="-+(a/b)) System.out printin(“The remainder="+(a%b)) The Output: ¢. Ternary Operators (Conditional Assignment) ‘Ternary operators deal with three operands. It is also called tiie condition sssignmientslatement because the value assigned to a variable depends upon a logical expression. Syntax: Variable = (test expression)? Expression 1; Expression 2. The variable contains the expression 1 if the test condition is true, expression 2 otherwise. For example, a=5b=3; Max = (aby? a:b: Here, the value 5 is stored in Max, Min = (b>a)? a: by In this case, value 3 Now, rewrite the snippet using Ternary 1. iffa>b) { d= (a-b) else d=(b-a); ) ‘Ans. d = (aby? (a ~b) : (b =a); 2. iffoasic>100000) { tax = 0; else tax = 1000; 1 Ans. tax = (basic>100000)? 0:1000; 3. if(@+b)><) ( k=15; System.out.printin(k), ) if(atb)c)? 15 : 30; System.out printin(k); as a>b is true. is stored in Min, as b>a is false. operators: Canes ‘The temary operator is equivalent to the ‘itelse’ construct in Java language. You can convert a ternary operator into ‘if-else’ construct and vice- versa by using the illustration, given below: ‘boolean x = (a>b)? tue: false; Output * A sample program is illustrated to find the greater of the two numbers: // A program to display the greater of the two numbers class Ternary { Public static void main(String args{)) Output: int a=42b=56 gr, gr=(a>b)Pab; System.out printin("The greater number = “+8 * A sample program is illustrated to find the greatest of the three numbers // A program to display the greater of the two number class Ternary ( public static void main(String args{)) { int a=42,b=56,c=88,max; max=(a>b)?(a>ca:c)(b> Greater than tue <= Less than or equal to false >= Greater than or equal to true Equal to false Not equal to tue // A sample program to illustrate relational operator class Result { public static void main(String argsl]) { int a=22,b=5; ‘ System out printin(’ Answer when ab :"+(a>b)); System.out printin(” Answer when a<=b:"+(a<=b)); System.out printin(” Answer when a>: System.out printin(“Answer when a System.out printin(“Answer when a!=b:”+(al=b)); Compilation and Execution: a Output: Answer when ob Answer when aceb, Answer when a==b Answer when a! 3. Logical Operators Java uses logical operators AND(&é), OR(| |) or NOT(). These operators yield true or false depending upon the outcome of different conditions. The different types of logical operators along with their format are shown below AND && BIEL) on = =b)fas =<) NOT ! Maz =b) Precedence of logical operators is NOT (!), AND (&&) and OR (| |) ie. if fa statement contains all the three logical operators then NOT is operated first boolean b = (a>b) && (b>c) | | (b>a) ! (cob) } y ' 2 3 ¢ Order of the operations is; ———> 1 ——* 2 Here, b will result in either true or false depending on the cumulative outcome of all the conditions. Logical OR (|) This operator is used to combine two or more conditional expressions. It will result in true if any one or more conditions (expressions) is true, otherwise in false if none of the conditions is true. The action of logical OR (| |) can be unds table: jerstood with the help of the following, Condition 2 eNEM Remrs CTT) FALSE FALSE FALSE. FALSE ‘TRUE TRUE ‘TRUE FALSE ‘TRUE ‘TRUE ‘TRUE TRUE en Od shown above that the result of logical OR fy when all the conditions joined with it are Faisal ‘or more conditions is TRUE. + Results in true because 5>4 is true. ; + Results in false because both the express, are false. 'essiony zIt will result in true because the secon expression is true. =9 It will result in true because all the expression, are true. 20 | [2<12 3<5] [1258] | Logical AND (&&) ‘The AND (&&) operator is used to combine two or more conditional expression, ‘such that it results in true if all the conditions are true, otherwise, in false. You can understand the action of logical AND (&&) with the help of the following table: FALSE ‘TRUE FALSE, FALSE FALSE TRUE TRUE It is evident from the table shown above that the result of logical AND (ell operator is TRUE only when all the conditions joined with it are TRUE. The result is FALSE if one or more conditions is FAL! For example, 5>3 && 3<5 Results in true because both the expression are true, Results in true as both the expressions att true. 6 == 6 && 3>0 5ia5 && 4 == 4: Results in false as first expression is false 8 > 4 && 9 >= 12 : Results in false as second expression is flit Logical NOT (!) } 7 The Logical NOT operator is used when you want to reverse the result of conditional expression. It is a unary Note Relational operators have highet _ ‘operator because it uses a single operand, Precedence over logical op AND and OR. Hence, while us Let us understand the action of logical aN and OR operators you operator NOT (!) with the help of the pot enclose the operande wit owing table: parenthesis, NOT () operator ‘The table shown earlier illustrates when the condition associated with ft = given condition is TRUE. For example, ! (8>3): False, because 83 is rue ' <7) : False, as 5<7 is true G0) : True as 30 is false, Indicate whether the following statements result in True or False () 4>7| [7215 (i) 350] Joc a4 (ii) 5 +327 &&7>=443 (io) 320d be () (5<3) Ans. (i) False (i) True (ii) True (iv) False (0) True The dot operator In Java programming, you need invoking the system pactage o perform : system package to prfom inpat/ output operation. This canbe done by using he kepnonl impo te arohang facilities contained in the system package. The dot operator facilitates invoking members of the class to carry out the tasks. The process of importing Java packages are illustrated as: import java. io. 4 \4 | Dot operator Input-Output package ‘The new Operator In the previous chapters, we already have discussed that the class is a representation of data and functions. When an object of a class is created, it contains the data member and member methods deseribed within the class. To create an object of a class the keyword ‘new’ is used. For example, ResultNum nk = new Result Numi ); Here, ‘nk’ will be an object of the class ‘Result Num’. ‘The keyword ‘new’ allocates space in the dynamic memory for the storage of data and functions belonging to an object. Let us understand the concept with the help of a program. // A program to illustrate the concept of ‘new’ operator class Result_Num_ { int num=50; String gr="A"; Public static void main(String args{]) Result Num) ber scored : “#mk.num); The Output: OUTPUT STATEMENT ‘The output statement in Java programming produces the result of an executial (on the screen. The values to be displayed on the screen must be enclosed withi the braces ie. (). However, it is also used to display a message while enterin, a value into the computer. It makes the appearance more user friendly, System outiprintingy ‘The output statement can be written in two different forms: This statement is used to shift the cursor to the next line of the screen after 1. System.out.print( ) 2. System.out printin( ) | producing the result. In case, you use multiple print statements by using printin() | _ then each value will be displayed in different lines. System.out.print( ) a Hence, the word ‘In’ along with ‘System.out-print’ acts as a line feed that will When you use this statement, the cursor" Vihen a message is to be display take the cursor to the next line. remains in the same line on the screen ith a variable, then they are to Syntax: System.out printin(); after producing the result. ( be used together with ‘+’ (called The above program using System.out printin( ) statement is illustrated as: Syntax: System.out.print(); eee A sample program is illustrated as under: // a sample program on displaying output // a sample program on displaying output class Result i class Result Public static void main(String args) : { { Public static void main(String args{]) int a=22,b=5; { i ‘System.out.printin(“The sum of two numbers = “+(a+b)); int a=22,b=5; System.out printIn(“The difference of two numbers = “+(a-b)); System.outprint(“The sum of two numbers = “+(a+b)); System.out.printin(“The product of two numbers = “+(a"b)); ‘out;print(“The difference of two numbers = “-+(a-b)); } an tou ‘ int(“‘The product of two numbers = “+(a*b)); ‘You have already studied in the previous chapter, the use of “\n” escape sequence (backslash character). It is also used to skip the line white displaying result on the ‘Screen. Let us see the application of “\n" along with System.out.print() statement 10) ‘produce result in the ame way as shown above: ‘System.outprint("The sum of two numbers="+(a+b)+"\n"); System.out print(The difference of two numbers="+ (a-b)-+"\n _ System_out print(“The product of two numbers="+(a*b)+*\n"); , The output will appear as shown below: | The Sum of two numbers = 27 The diference of two numbers = 17 The product of two numbers = 110 You need not use “in” inthe last line of System.out print) statement because ts the last ine ofthe output to be displayed, 3 Lab (activity Predict the output of these snippets: 1. System.out-printin(“India won Ici System.outprint(“against”); System.out printin("West Indies”); System.outprint(“in the year 1983"); Output: ‘C Cricket World Cup”); 2. int a=34b=45, Systemoutprint("The sum of two numbers = ") System.out printin((a+b)); 3. System.outprint(“India won ICC ‘Cricket World Cup”); System.out print(“against”); System.out printin(“West Indies"); System.outprintin(“in the year 1983”) Java Programs on assignment statement This is one of the ways to lear fundamental construct of Java programs. By Using an assignment statement, a value is stored to a variable to perform various tasks. It means that you can execute the program only when the value is readily available. Moreover, the program using assignment statement is relevant only When user needs to work on a fixed set of data values. In this segment, you will learn the basic mathematical operations viz. addition, Subtraction, multiplication, division in Java programming, Write a program in Java to assign and display Name, Class, Subject, ‘School and City of a student. // A sample Program Public class Bio_Data ( pubic state void main (tring asl) { System.out printin(’Nam System.out printin(“Class:”+std); ‘System out printin(“Subject:”+sub); ‘System out printin(“School:”+sch); ‘System.out printin(“City:"+, 33>, << Bee aoc ou (©) What is the output of the following ‘char x='A’ int m: ma(x= ='a')) Asa! 18 Program snippet? by another number. (integer part) when a number is divided For example, in Sb=7.6 The output: ow 2 The’ eperstor results in remainder when one number is one umber is divide by othe. For example, int a=3,b=7,¢; sh The output: c= 1 (@) What will be the output of the following code? kes kee - +4) +e System.out.printinke"+k) System.out printin(“j="4) [icsE 2011) Ans. Ic =10 (©) Write an expression in Java for 5x! + 2yx + {Ucse 2011} Ans. z= 5°x"x°x + 24°K+y (© Give one point of difference between the Unary and the Binary operators {ICSE 2012} fon. The unary operator used opraem petites Sola ae The binary operator performs operation on two operands. ef 4, (@) What are the values of x and y when the following statements are executed? rast be ooclea ines ocean ese 2012 Ans. The statement given below is wrong. It will produce an error Incompatible type’ tevlean tre: ais be Ieoleanelstpe :alo tha Per ya50 (and %, x after evaluating the following express... (@) Wha will be the rest stored in i ise NCSE 2p ectave (een Ans. x= 20 ena {ICSE (What do you mean by precedence of operators are used fOr OPEratiON is kn! ‘Ans. The hierarchical order in which ‘as precedence of operator. For example, « Brackets, Exponent, Multiplication Precedence of arithmetical operators = Division, Addition/Subtraction, Precedence of logical operators: Not, and, or (, && and {) Rewrite the following program segment using if..else statement, - ‘comm = (sale>15000) ? sale*5/100 : 0; LICSE 2013) ‘Ans. Snippet by using if..else statement i if(sale > 15000) ‘comm = sale * 5/100; i fond : ‘comm = 0; t (Write @ Java expression for ut + }.at ‘Ans. Java expression for the given mathematical expression: urtsloaoraret o ‘Opecitcs wit higher procedeuce are Sviliatil AEM MEN NRE WIR relative TICSE 2013) ; @ && (iil) >= i ‘Ans. The correct order of O + . (i >= iv) && {m) Rewrite the following program segment using if-else statements instead of the ternary operator. String grade = (marks>=90)?*A": (marks>=80)? “B": “C"; ‘Ans. if(marks>= 90) grade =°A"; else iffmarks>=80) grade="B"; else grade=*C*, (n) Give the output of the following method: able state void maining args) int a = 5; (o) Evaluate the value of n, if value of pa5, qui int n = (-P) > (@-4)? (@-p): (p-q); Ans. n =l4 (p) Write the Java expression for: a+b? ~2ab ‘Ans. (a’a + b°b)2.0°a*b (@ If int y =10 then find int z = (uy*(y.e45)) ‘Ans, z= 11%(1145) = 176 (® Write down Java expression for: ‘Ans. t= Math.sqrt (a°a+ b*b+ e%) (6) Rewrite the following using ternary operator: if 2 = = 0) System out printin¢ Even”) else System out printin¢“Odd”, ‘Ans. (x%2==0)? System. out printin(‘Even”) System out prinIn(“Odd", (9 Give the output of the following expression: ats aust a + a+ a; when a = 7; Ans. 7+ (7+9+8 +8) =39 licse 2015 iCSE 2015} ICSE 2015) ICSE 2016) {ICSE 2016) {ICSE 2016} 1. Multiple Choice Questions ‘Tiek (V) the correct answer: 1, The staement n= seers ae ec (@ +n =! y : 2, what will be the output of 2 & b in the following Hit 910, bas, @ 10.10 @) 10,1 ou ; wi put of ave when int a = =10) else seb: System.out printin(’ a = "+a +"and b =" +b) 14, Rewrite the following using ternary operator. (@ iffincome<=100000) tax =0; else tax = (0.1"income); (©) if(p>5000) d = p'5/100; else = p'2/100; ralues of the variables are: ©) a Gs0)%e lucse-2007) [ICSE-2008), IV. Unsolved Java Programming: 1. Write a program to find and display the value of the given expressions @ =* 3 _ 28 +5: taking the value of x ) St b+ Staking the values az5,b=4,c=3 2. A perso is paid £350 for each day he works and fined 30 for each dy he remains absent. Write a program to calculate and display his monthly income i he is present for 25 days and remains absent for 5 da 3. In.a competitive examination, there were 150 questions. One candidate got 80% correct and the other candidate 72% correct. Write & program to calculate end display the correct answers each candidate 60% 4. Write a program to find and display the percentage di (@) a number is updated from 80 t0 90 (b) a number is updated from 75 10 72 ference, when: - fs 98.6°F. Write a program to ¢,, ante display the output, ven 5” 98 5:6. Write a progray in the ratio 3:4:5:6. FORTAM 16 fi, 6. The angles of « quadrilateral are f a quadrilateral ~ 34° ‘ (Hint: The sum of angles of a q 1 = 36 Input in Java Introdction about IPO cycle, Comment in ava programming Single comment “n,decumeriaion comment Vere ie ammen sing Function Argument; lava Programming by wing boat Sica Scanner Class; Import System Package, Creating Scanner Obren ny and Debugging: Types of Eros. Syntax Exor, Logis Err Rea ). multiline *, Java Programming by ime Eroe INTRODUCTION Data processing is an important aspect of computer operation. It includes accepting values from the user, processing data and displaying the result : Input —> Process. —» Ouiput | a The block representation shown above is the cycle | a of data processing called the 1? cycle. Whenever you want to write a program in any computer language, the initial task is to provide values to the computer for processing, | In this chapter, we are going to discuss the ways | of providing values (data) to the computer in Java language Before introducing input statements, let us focus on a non-executable statement | that enables the users to understand the program logic. Itis basically a statement | of remark called the Coy. Comment Statements in Java Programming fs | Sometimes, it becomes difficult for a user to eee, feb cee are especially when somebody else has developed it. In such cases, the programmer Should mention the purpose and the action being taken i ferent steps. This | an be made possible only by applying comment statements in the program. } i There are three ways to give a comment in Java programming, However users ; are expected to give a specific comment wherever necessary while writing a Java | Program. Following are the categories of comment statements: 1. Single line comment (//) t 2 Multi line comment (/* Z /) P) 3. Documentation comment (/** re & — a imgle Line Comment chen a comment can be o a ane cement is given in a program when a cOmMENt CM be eypy Vili iacttitlon Coesiaas A in cy be used asa separate line or in continuation of q Stateme! During the course of Programming, the user may need y Tee re acrmcgent starts with (//) followed by the message, bout himself and his program “The, documentation may gee isformation A single tine comment st ifastrated below: about the program logic but might serve some np aY Rot be a discussion Je line comment is illustra : is © some information tbe Yaewer An example of a single li users who may need to execute yous so wed by other oy eel Program. The documentation concent stars with (/") fllowed by the sto cannon eo = example is shown below and ends with (/), An //My first Java program class Sample /**My name is Akanksha Gautam, rl I study in RajendraVidyalaya in Class x p,| public static void main(String args{]) This is my first Java Program, Documentation Comment ( i : class test int int c=a‘a; //Square of the number ( System.out-printin(“Square of the number is”-+c); ae static void main(String args{)) ) int a=5; ! int c=a’a; System outprintin(“Square of the number is"*c); ) Multiline Comment "i Sometimes, the programmer may need to explain the logic of a program in deta In such a situation, using single line comments in the program repeatedly iss Now, we are going to discuss the various ways to input the data values to a tedious process. To sort out the problem, a multiline comment statement ox program. They are listed as follows: be used 1. By using a Function Argument (Blue] system) The multiline comment starts with (/*) followed by the comment lines ani 2. By using a InputStreamReader Class ends with (*/). i 3. By using a Scanner Class An example is illustrated below: 1. INPUT BY USING A FUNCTION ARGUMENT /* My first Java program . This is one of the methods to accept the value from the user at the time of It accepts a number (say, 5), ‘Comm ‘execution of the program. The variables whose values are to be input must be calculates and displays the square of the number */ | : Provided as arguments of the main( ) function. class Sample For example, public static void main(int a, int b) : { The above function will accept two nee cana oes ~ ad i of the ram is obtained on the screen after pt 2 Public static void main(String args{]) gua ii { the sum and average int 4 ‘Write a program in Java to find and display RSS int c=a*a; z function argument System.out printin(“Square of 5 is”); // To find the sum and average of three numbers by using funtion argu Public lass Average 1 Public static void main (int a, int b, int ¢) ona OF int sum=d: oat avg=00: sum): Sestem cut printin(“The sum =" +S save) ut peintin(“The average ="*3¥8 System Execution of the program: ‘Step 1: Compile and close the program 2 : Select the icon of the class Average and right click. A drop dow menu will appear. Select void main(int a, int b, int c) from dap down list ‘Step 3 : A small Method Call window will appear on the screen. Enter & values of a, b and c one by one and click ‘Ok’. eae —s EWE Wiite a program in a Java to find and disp amount by using the funct display the simple inte function angen PAY the simple interest aid To find the simple interest public class Interest public static void main(int p, int r int t) and the amou ount by using function argument double si=0, amt=$ si = (p'r*)/1000; amt=p+si System out printin(“The simple System .out printin(“The amount Write a program in Java to find and display the area and ; v y the a rimeter of 4 rightangled.tiangle by sing, ncn, angemeee toe perpendicular and base as inputs from the console / To find the area and perimeter of a right-angled triangle public class Triangle " ( public static void main(int p, int b) Math.sqrt(p*p+b"b); .0/2.0"p"b; iprb+d); System.out.printin("The Area System.out printin(“The perimeter ) Write a program to input a three digit number and display all the digits by using arithmetical operators ‘Sample Input: 472 ‘Sample Output: 4 7 2 // A program to display all the digits of a three digits number class Digits fl Public static void main(int num) i int hatud; Input by Using Class This Bs provides user-friendly environment to input the data : wa programming, The user may have option to change the data dy Trceuton of the program. This system uses a combination of to clases, yp ler’ and ‘BufferedReader’. The significance of these Classes , ussed below: ‘* InputStreamReader class The data given to the computer is converted into machine code, ic. binay form. This machine code needs to be transferred to the CPU in the form fj binary bit pattern. Hence, the system tries to streamline the bits so that thy do not get disturbed or hampered and cause any input error. The streamliniy of bits is done by using InputStreamReader class. ‘A computer system has a high speed buffer device (a temporary storag ‘device) in between input unit and processor. In order to synchronise the speat © 8f1/0 devices and processor, buffer allows storing of input streamlined $0 that the instant supply of data can be done to the CPU witht "any delay. Thus, the BufferedReader class is used. | | Process to Input Data by Using InputStreamReader Class (Include java.io package by using import java.io.*; This enables java.io package to be used in your program. Basically, _ package is imported to avail facility of using input/output functio ___readLine() or printin(). | (ii) Create class by using public class The class name may be any name normally selected and suitable operation to be performed in your program. 4 (iii) Declare main function header as: oe static void main(String args[])through IOException c: It is the keyword used to specify that the function fl n on being used anywhere throughout the system. Keyword states that the function does not void: It refers to the non-retumable not return any value. main: ‘As soon as the command to execute a pro default reaches to the mai function fr ie eae is w ‘main function is important, string args{l: This is an argsf ] ¢ the keyboard as a String data, oS ee ‘Throws IOException: Sometimes, the program experiences 1/O errors even if the programming, statements have correct syntax. It eliminates the 1/O errors (if any) that ereep in while programming. InputStreamReader read = new InputStreamReader(System.in); ‘This statement creates an object of InputStreamReader type (say, read) to accumulate streamlined bit patter from the input device. BufferedReader in = new BufferedReader(read); This statement is used to create an object ‘in’ of BufferedReader type to store the input data entered from the keyboard temporarily. ‘Syntax to Accept Numeric Data Values ‘© To accept an integer up to 32 bits: int n; System.out printin(“Enter a number”); integer parselnt(in.readLine( )); ‘© To accept a decimal fraction up to 32 bits: float n; System.out,printin(“Enter a real number"); Float.parseFloat(in.readLine( )); * To accept a decimal fraction up to 64 bits: double n; System.out.printin(“Enter a real number"); 1n = Double.parseDouble(in.readLine( )); Syntax to Accept a Character char ch; System.out-printin(“Enter a character”); ch = (chan\(in.read()); SOLVED PROGRAMS BASED ON INPUT STREAM READER ‘ = eaten of st RRS ete Be ombar of Sao “ae the percentage of boys and girls in the y the percentage of boys and girls Public static void main(String args{)) throws IOException atStreamReader read=new InputStreamReader(System in); BufferedReader in=new BufieredReader(read); int namb; Step 3: A Method Call w: "osiow will appear on the screen. Click OK” bution System out printin( “Percentage of boys Step 4 : Enter number of students and System out printin(-Percentage of girls 2 Step 5 : Press enter key to get the req number of girls quired output on the screen. ‘Wote a program in Java to accept the of ees ee diagonal of a square. Find and Perimeter by using Inpet seam ae // To find the area and perimeter by Input Stream ios import java.io.” Public class Square t Public static void main(String angs{Jthrows 1OEweption ( InputStreamReader read=new InputStreamReaderSystem in}: BufferedReader in=new BufferedReaderiread); double a par; ‘System-out printin(“Enter the diagonal of a square"); ‘d=Double parseDouble(in readLine)) import java.io.*; class Fund public static void main(String args) throws IOException { a throws IOException InputStreamReader read= new InputStreamRead ‘ pate static void main(String args ) BufferedReader in= new BufferedReader eae int sal; js int absyd; ae InputStreamReader(System in); ae rele : InputStreamReader read =new System.out printin("Enter salary:"); BufferedReader in =new eae ae sal=Integer. parselnt(in.readLine()); System.out printin(“Enter the number of : pf=sal*12,0/100.0; rsal=sal-pf; ed=rsal*20.0/100.0; ren=rsal*10.0/100.0; System out printin(“Amount cotributed in PF :"«pf) System.outprintin(“Amount spent in education :'sed); -4y); System.outprintin(“Amount spent on rent-"4en); ) a=Integer parselnt(in readLine(); y=a/365; b=a%365; =b/30; SCANNER CLASS Input by Using Scam The Scanner Class is the er Class latest development in Java, which allows the user to Tead values of various types. The Scanner Class is defined within a Java Package (Le. java.util.*). There are mote methods in class Scanner than you will need in this course. We only cover a small useful subset, which allows you to input the values from either the keyboard or file without going through any conversion system. Tt also does not require mentioning the limit of values in advance by the programmers. The end of values can be determined by a character or string. However, the Scanner Class necessarily needs JDK 1.5 or more along with Blue] Version 2.5 or more. The methods which are defined under this class don’t Support the lower JDK and Blue] version. In order to include Scanner Class in Java programming, you need to install JDK 1.5 and supporting Blue] version, Which is shown below: Output of the program: the amount spent on rent and education FOnce your system is equipped with the set-up files of 1k 4 Bla ea » execute Java program by using a Scanner Class, This! Yo, saree atrsaentyr ti non-numeric data, Hot a, tem, Lo PES are now h eric and helpful to input different types of numeric a rreyeen Shiterent remains the same ie. System.out.print( ) or g printin( ). The data values are accepted through the object as it hap, InputStreamReader. Import System Package ‘The scanner class is available in the system package java.util. You muse java.util package to avail the facilities available in the scanner class. The to import java.util package is shown below: import java.util. Scanner; impo Pro. egy ae. Package Dot Class rec Or, import java.util.*; Creating Scanner Object After importing java.util package, you have got the facili and create object which can hold a set of values of di to create a scanner object is shown belo ity to avail scanner cay ifferent types. The synia pes t= brs ee (System.in); Sclnner New Constructor Object Operator Declare an object of type Scanner say ‘se’ (You can use any object named your choice). = new keyword is used to have dynamic allocation of scanner object. ‘The scanner class has a special constructor which is automatically invokeds store values in the scanner object from console. + The parameter ‘System.in’ allows the constructor to receive data from keyboard. The Scanner Class basically works on the principle of Tokens’ in the ing A token is a series of characters that ends with a delimiter. Some delimies which can be used as token separator are comma (,), full stop (.), semi-colist® @), whitespace, etc. Scanner class uses white space as default token = .nextShort( £8, Scanner in = new Scanner(System in); short p=in.nextShort); Or, short p; prinnextShort); It means that the variable p will store a short type data through the Scanner object. ject which can be ex syntax ee Pree String = nent + nextintO; token from Tt receives the next variable. an integer and stored in integer PS For example, : canner in = new Scanner{System in tax: ‘ Scanne ) ier crarable> = canner Objece nena String strl= in.next0; For example, in): It means that the variable str1 will store the next token as a string through Scanner in = ne Samet PETS the Scanner object. int p= inneatint; tore an integer value through the Scag, nent.charAH0); egg. Java does not have a specific function to acept a character through a Scanner et class. The next() function is itself modified in order to accept a character, The + nextFloat0; essed as a floating ty nt() function receives a character asa string. The char seneeee as a floating type y ne s acter can be extracted | Br ieeeites oe hs Ae : eae: cS 2 by using charAt(0) function to be stored in the resulting variable Se Ee ee Syntax: char = next(.charAt(0) syntax ! 10 = ct>.nextFloat( ); For example, feo pmeapisen Baa | Scanner in = new Scanner(System.in); char c=in.next0.charAt(0); It means the variable c will store a character through the Scanner objec: . float p= in.nextFloat(); It et that the variable p will store a float type value through the Scame s_pextLine(; The application of next( ) method is to accept a token as a string from the ject. : oe Scanner object. When a line of text is input into the scanner object, the next( ) ‘This method receives the next token expressed. method will receive the first token. Rest part of the text line can be obtained as a long type value and stores it in a long type as a token by using nextLine( ) method. In case, next( ) method is not used before, the nextLines( ) method results in entire line of text variable. i Syntax: x6 Vee ae ble> = .nextLi oe : ena le> = nextLine( ); For example, byte os Scanner in = new Scanner(System in); Scanner in = new Scanner(System-in); mot String str2= in.nextLine(); long p= in.nextLong(); ~ Itmeans that the variable str2 will store a line of text through the Scanner object. It means that the variable p will store a long | long | 8 type value through the Scanner object. SOLVED PROGRAMS BY USING SCANNER CLASS Write a program in Java to input two numbers. Display the numbers + nextDouble); us This method receives the next token which can be expressed as a doutl Bs SEE value and stores it as a double type variable. £ after swapping them by using a third variable. apa Z Sample Input: a= 95, b=45 double = .nextDouble( ); eine Quint ete tee For example, / 4 program to display the numbers after swapping Scanner in = new Scanner(System.in); import java.util; double p= in.nextDouble(); bee Public class Swap Itmeans the variable p will store a double type value through the Scanne™ { + next(); sit: } Public static void main(String args{]) This method accepts the next token from the Scanner object a5 4 87 ju { token can be defined by a set of characters between two simultaneov Scanner in = new Scanner(System.in); int aby spaces or delimiters. A Program fo cla ro say oot java.util’; and Net salary, public class Esalary { public static Void main String arty { Scanner in = new Scanner int basic; double da,hra,pfgp=0.np-o, String name; System.out printin(“Enter the name ofthe a name=in.nextLine(); seo System out printin("Enter basic basic=in.nextint(); da=basic*30.0/100.0; hra=basic*12.5/100.0; pfbasic*l0.0/1000; je+dahra; DUE tem.outprintin“Employee's Names”sname); System outprintin(“Gross pay "gp, System out printin(“Net pay:Rs."snp) 1 (System in); salary”); ‘Write a program to display three rational numbers between any fy consecutive natural numbers, taking inputs from the console, ‘Sample Input: 7 and 8 Sample Output: 7.25 75 275 [Hint: Rational number between m and n can be calculated g m+n y 2 77 A program to calculate and rational numbers between two natu import java.util"; class Rational_Num { public static void main(String argst]) { Scanner in = new Scanner(System.in); int mn; double ab; System.out:printin(“Enter two consecutive natural numbers one by one:”); main.nextint(); .nextint(); al numba System.out printin(“Three rational numbers are :”) ‘System.out.printIn(b); System.out printin(a); ‘System.out.printin(c); Sample Input: 62 Sample Output: = 22 // A program to display result import java.util." class Result Scanner in = new Scanner(System.in); int abres System.out.printin(“Enter tens digit") in.nextint(); System.out printin(“Enter unit digit”), b=in.nextint) res=((10*a+b}+(10*b+a))/(a-b); System.out.printin("The answer :” "eres); TESTING AND DEBUGGING In general, testing is the process of making sure that the program performs the intended task or not whereas, debugging is the process of locating and eliminating program errors. Testing and debugging are vital steps of removing, errors from the programs. They are also time consuming steps. In fact, the time spent in testing and debugging often equals or exceeds the time spent in the creation of the program. If a program runs successfully with the test data and produces the correct result, its normally released for use Testing and debugging are two different tasks. You should not be confused between them. The differences between these processes are given below: 1. Testing isa process in which a program 1, Debugging is a process in which the is validated. errors are removed from the program. 2. Testing is complete when all desired) 2. Debugging is Gnished when se fe Verifications against _ specifica ‘no errors andthe program is Ine batt psittaci Oa e to be very careful while ¥ saul et ie dese result due to incoeel output. Generally, there are three types of “These errors occur when the rules or the grammar of the Programa Tanguage are not followed. Such programming errors typically involve incom ‘Punctuation, incorrect word sequences, undefined terms or erroneous use terms. Example: ‘A sample program which shows the syntax error at the time of compilatg, Here, you can notice that the variable a syntax error (cannot find symbqi ot declared. Thus, the data type of the variable ‘p’, it shoy oe P) and after decorine tre tax error’ Thus, the program is erfor free and ready to oxene Logical error ‘A logical error is concerned with an error in “ computer actually does not know that an erm eee rogram log. The the instructions and executes the results, but the output may oa - follows Me problem i that the logic being given does ot produce piles ccs Hence, a logical error is the error produced due to wrong logic in the Example: ne hee program. Write a Java program to take three numbers, Divide the numbers by the third and display the result. oie ae ‘can notice that the result in both the cases are different ‘compiled. It is because in first case, the user has ing ©. which yielded incorrect result according to the ¢ Differences between Syntax error and Logical error Ase is the grammatical error in the 1. Its the error in programming fog "2, The program is unable to give the 2, The program doesn't sive the desing © output. output. Run Time error Sometimes, you find the program is not producing the desired results, ey after errors (syntax as well as logical) are removed and the program has bey ‘compiled successfully. These errors may occur due to incorrect mathematig) ‘operations or by entering incorrect data values at the time of inputs. For example: dividing a number by zero or trying to find out the square mu of a negative number, etc. Example: [PobIES HES Wola wainisering araei1) The expression p = (a + b)/c; _ Here, you have defined the value of c = 0, then the result will come nite value, which is a run time error. (a) What is the use of the keyword ‘ans. The keyword import is used to inchon (0 Division by a variable that Gi) Multiplication operator (i) Missing semicolon. ‘Ans, () Run time error (i) Logical error (iil) Syntax error contains a value zero, ‘sed when the operation should be division, ltcsE-2012) (©) Complete the code below to create an Scanner sc=__Scanner ( . ‘Ans. The complete code is as follows ‘Scanner sc= new Scanner(System in}, (@ Name the method of Scanner class that: {ICSE-2013) () is used to input an integer data from the standard input device Gd is used to input a string data from the standard input device, ‘Ans. () nextInt() Gi next() of nextLine( ) (©) Name the type of error (syntax, run time or logical error) in each case given below TICSE-2016), (® Math sqrt@6-45) (@ int abe Ans. () Run Time ‘object of the scanner class. 1CSE-2012} i) Syntax (What is the difference between the Scanner class element nextQ and nextLineQ? (ICSE-2017] Ans. The next() function is used to accept a string as a word whereas the nextLine) function accepts a string as a text line (®) What is the need of input statement in @ program? ‘Ans. The input statement is used £0 accept values from the user for processing: ° (hy What is the advantage of the Scanner class over the InputStreamReader? ‘Ans. The Scanner class is latest development in Java language that uses Powerit functions to accept the user's input. It does not require BufferReader and: throwing exception in the program. (® Name the package used for the Scanner class: ‘Ans. java.util ‘ @ Name a default delimiter used in Scanner class, ‘Ans. White space or blank is the default delimiter used f0 {input through scanner class. ‘as character through Seanner object _~ Class oar number erough Scanner objet i ve integer token through scanner object the syntax with reference to Java Programming: 1. to accept an integral value‘p' through InputStreamReader Class to accept a fractional value (float) ‘m' through Scanner Class to accept a character ‘through InputStreamReader Class | “4 toaceept a fraction value'n‘n double datatype through InputStreamReader Cag “5 accep a word vd though InputStreameader Class ‘nextlnt() and nextFloat( ) methods _ 2 Syntax and logical errors - Answer the following: “1, What do you mean by the Scanner class? __% What are the different ways to give inputs in a Java Program? __& What is the use of the keyword impor”? (icse an) Bs ee! Giie on cxamsie i1CSE a to input an integer number by using function arguement 6, ‘Diagnostical messages detect only syntax errors”. Give comment 7. Write down the syntax to input a character through the Scanner class withi ‘example. __& What do you understand by ‘Run Time’ error? Explain with an example _® What are the diferent types of errors that take place during the execution 8 program? ‘time period of a Simple Pendulum is given by the formula: ; Te2n/L a “f ' Program to calculate and display the time period of a Simple Pem 2 length (1) and acceleration due to gravity (g) as inputs. [n= Ta 2 Program by using class Employee’ to accept Basic Pay of a los ons as given below. . A business man wishes to accumulate 3000 shares of a company. However he Finally, find and display the Gross Allowance/Deduction Rate eee Dares Allowance (DA): 29% of pe House Ret allowance (RA) too aS Pay Provident Fond @) "25% of ase ay asic Pay + Dean Gross Pay ~ Provident Fas nanet * Howse Rent Allowance A shopkeeper offers 10% discount on the However cone a o py ty a i program in Java to calculate and dena oe ene {aking printed price as an input, PY ‘Me @mount to be ‘A shopkeeper offers 30% discount on purchasin, shopkeeper offers two successive dischunte me a, article SS age he eae SA at a a a eas already has some shares of that company valuing & 10 (nominal value) which yields 10% dividend per annum and receives € 2000 as dividend at the end of the year. Write a program in Java to ealculate and display the number of shares he has and to calculate how many more shares have to be purchased to meet his target Hint: No. of share = Annual dividend*100 ‘Nominal value*div’s Write « program to input the time in seconds. Di them into hours, minutes and seconds, Sample Input: Time in seconds 5420 Sample Output: 1 Hour 30 Minutes 20 Seconds Write a program to input two unequal numbers. Display the numbers after ‘swapping their values in the variables without using a third variable Sample Input: a = 23, b = 56 Sample Output: a = 56, b = 23 ay the time after converting ). A certain sum is invested at the rate of 10% per annum for 3 years. Write a rogram to find and display the difference between Compound Interest (CI) and ‘Simple interest (SD. Take the sum as an input, Hing. st = BCROT A= P*UsR/100)" and Cle A-P A shopkeeper sll 8 calculators fr the same price. He earns 2% profit on one and suffers a loss of 20% onthe ter We progam Eo display his total cost price of the calculators by taking thetr selling price as Input;

You might also like