0% found this document useful (0 votes)
40 views

Computer 10 - Unit V

Uploaded by

Pravesh Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
40 views

Computer 10 - Unit V

Uploaded by

Pravesh Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
AEINALC a teeeetiac lacey Pe R LEARNING SCOPE a © Basic features of Java © Java Compiler and Interpreter © Java Libraries in JDK © Java Reserved Words © Basic Elements in J lava Programming © Output Statement in Java Programming © Java Programming using BlueJd and Execution Java is an object oriented programming language, developed by James Gosling along with his associates at Sun Micro System (a software company), USA Initially it was named OAK (a tree outside Gosling’s office), The name OAK remained only for some hours until the development team realised that another language is also available with this name. Finally, on the coffee table they decided a professional name for the language as Java. It was primarily developed to help users in web designing but later on it emerged as a full-fledged programming language in 1991. Java gained wide popularity among; the users due to its platform independence. The platform independence means the program in Java language can be executed on any computer. Java language allows writing a program in two ways. They are: + Java application or Standalone system Java application is a Java program that is developed to run on a computer without any help of a web browser. It is also known as standalone system. + Java applet or Internet applet Wa Java applet is a program written in Java language that can be included in a web page in the same way as a picture or a clip is included. Java applets are run with the help of a Java supported web browser. « G Features of Java Language Java language has the following features: 1. Java is object oriented language. 2. It is platform independent. 3. It uses compiler as well as interpreter. 4. It is a robust language. 5. It is case sensitive. The upper case and lower case letters are distinguished by the language. evision of Class IX Syllabus | 39 Java Compiler and Interpreter ructions only in machine Langa, Its a well-known fact that a computer unsderstands instructions O° TT vite > written igh : ay ; rograms are writle ith. (ie., binary language). The application p' auage needs to be converte level Tanguages. Hence, a program in high-level languate pee “Ving ages 3 7 execute. machine code for the computer to understand and ex See Java compiler is a system software that converts a program ; i eee mee co imto an intermediate binary form called Byte Code, Further, the by mene vn as Java Interpret into machine code suitable to a specific platform known as Java Intery . computer to execute a Java program as well as @ program written fe code, This is the reason, Java interpreter iy saig Java interpreter enables in other language compiled into Java byt to be Java Virtual Machine JVM). Byte Code, 4 Interpreter + +. ¥ 4 Ms-00S, WINDOWS UNIX Other OS ava Source Code. —> Compiler > It is important to know that Java machine code varies for different platforms such as windows (single user OS), UNIX (multi-user OS) including other operating systems, Packages in JDK 1.5 As you know that Java Development Kit IDK) 1.5 has a library called JCL (Java Class Library). It contains various packages. A package is a collection of classes such that each class includes different in-built functions. Some of the packages in JDK are listed below. Java.lang \\ Supports classes containing String/Character, Math, Integer, Thread, ete. / java.io Contains classes for supporting input and output statements | Java.applet Contains classes to generate applets. java.net Contains classes for supporting networking operations. Javaawt —/ Contains classes for supporting abstract window tool kit and managing GUI (Graphic User Interface) components. Javastext / Provides classes for handling formatting of text, dates, numbers and messages. Java.math Contains classes for supporting mathematical functions such as square roots (integer and decimal both). Using a Package During the course of programming, we often use functions of a class which belong to a specific package. It can be done by including the package in our program, A package can be included by g the keyword ‘import’ followed by the package name. eB import java.io.*; (easentiane aad import java.util; ea ase “sign denotes that all the classes of the package will imported “by éetaut ‘is be imported in the program. If you want to use only a 8/978 particular class of the package then mention its name in. place of ** sign, e.g. import java.util, Scanner; Keyword or Reserved word ‘There are some words that carry special meaning to the system compiler. These words can’t be used as variable names in the program. Such words are called as Keywords or Reserved Words. Some of the keywords used in programming are listed below. case switch else break static do const throws float char try int double void goto for while new import boolean long if byte package private catch short public class default Basic elements of Java Programming The basic format of writing a program in Java is entirely different from that of other languages. So, it is essential to know the following points while writing a Java program. * Class Declaration: It is the first line of the program. It uses a keyword class followed by a name called class name. Main function: The main ) function encloses the programming statements within opening and closing curly braces { }. As the main function is a part of class declaration, it is further enclosed within curly braces { } under class heading. Output Statement in Java Programming The output statements in Java are used to display the result of the program on the screen. They are written in two ways: * System.out.print( ): This statement is used to display the value enclosed within its braces. It leaves the cursor in the same line on the screen. Example: ; ut a message is to inpp = 25, 4.5 20; be displayed along with System.out.print(“First number is” + p); System.out.print(“Second numbe: System.out.print(“The sum of two nu ) using Outp A — oo | First number is 25 Second ni | | | | | | pot of the PrOSTAM on gy mrement act as 2 bine feed wis ¢ wo sumbers is” + (P+) noct printin(“The sum oF Ogee (First sumber is 25 Secoad number is 20 Java Programming using BlueJ _ : BlseJ version is Java platform for window based applications. It uses @ menu drivex zpprosch that allows the users to camry out different tasks by clicking the options Ee tenn ber Like IDK 15, BlueJ also uses compiler as well as interpreter aan ee ace code ingo machine code. A sample program appears on the screen ta provide assistance to new users. These features of Blue make it more convenient fee the progremmers in coding their programs. Java Program on BlueJ Platform The steps to write 2 first small program in BlueJ are as follows: Step 1: Double click on the Blue] icon. 7 Step 2: Click ‘Project’ and select “New Project’. ) 4 Step 3. : Enter the project name (say. Computer 10) in New Project window and click on “Create” button. Bi Lore) en Step 6 = Finally, click ‘Ok’ to create class icon. It a program file in which the user writes program. Step 7 + On double clicking class icon (First_Program), a sample program is displayed. This program acts as a template to the user. Step 8 : Erase the sample program and start writing the program on the blank screen, It is shown as below: (Class Eat Tools Options [Come [Undo [Cu [Gapy [Paste ‘Systen.out.printIn(*zhis is ny first progras in Java"); | Systen-out -printin(’ systen.out.printin("zhis language 4s developed by Janes Gosling"): \ Systen.out.printin("It was inttially called a= OAR"): Systea.out.printin("zhe program 42 written with a class nase"); printin("Java is a case sensitive language” appear as ‘Class compiled execute your program, Excention on BlueJ platiorr ew: The different steps to execute the program are BNE Step 1: Close the program window. Step 2: Right click the class icon ). A drop down ment appears, am Pirst_ Prog! ord main(int 108) restroom ((0__ Step 3. : Select the n ‘void main(Stringl | args)" aii screen. Click Ok. Step 4: A ‘Method Call’ dialog box appears on the Step 5 the output screen, ‘erminal Window’, i. This is my first program in Java Java ig an Object Oriented Programming Language ‘This language is developed by James Gosling It was initially called as OAK ‘The program is written with a class name Java is a case sensitive language Step 6 : Finally, close the Terminal Window. = — Insight ——____— Q.1 Name a menu based Java programming, platform Ans. Blue} Q2. What is the another name of Java Interpreter? ‘Ans. JVM (Java Virtual Machine) Q.3° What does the term language processor mean? Ans. Language processor is the term used for translators such as compil QName the person who developed Java language Ans, James Gosling Q8~Define the term byte code, [ICSE 2010) _7&s._ Java compiler converts source code to an intermediate binary code, This code helps generate machine code and is known as byte code. Q.6 What is meant by a package? Name any two Java application program: \ = packages. [ICSE 2014) Ans, Packages contain logically related classes together. Each package defines a number of classes which can be used in the program by importing a single package. Two Java application programming interface packages are: interpreter, etc. 1s interface 1 java.io 2. java.util Q7_Name the package that contains the class: [ICSE 2015] (BufferedReader (if) Scanner ‘Ans. (i) java.io." (i) java.util Q8 Name any two library packages. [ICSE 2016] Ans (i) java.io. (i) java.util Q9 Write a statement in Java to display: Best of Luck for ICSE 2020 Examination Ans. System.out.printin(“Best of Luck”); System.out.printin(“for”); ‘System.out printin(“ICSE 2020 Examination’); Q10 Given: System.out.print(’BEST “); LICSE 2018] ‘System.out.printIn(“OF LUCK"); Choose the correct option for the output of the above statements. () BEST OF LUCK (i). BEST OF LUCK Ans. (i) BEST OF LUCK Qu1 How do€s'a byte code gets executed? Ans,_Ja¥a byte code is converted to machine code with the help of Java interpreter and gets executed on computer. Q.12 Write two features of Java language. Ans-“(i) Java language is platform independent. (ii) Java language is case sensitive. 2. System.out printin("This is my first Java program”); System.out print("Display the messag System.out.print(“Have fun!!!”); 3. System.out printin(“India got independence”); System.out.printin(“on”); System.out.printin("15th August,1947”); 4, System.outprint("The factorial of 5 is”); System.out printin(120"); Wrile’Short answers: . 0 any Name a Java package which is imported by default. (J * * Explain the significance of the following Java library packages. (@) javalang (®) java.io (©) javamath 3. (a) Java interpreter is called Java Virtual machine. Explain. (®) Name two ways of writing Java programs. Define the terms: (a) Source code (b) Machine code () Byte code [ICSE 2010} 5. What is BlueJ? What are the features of BlueJ? ‘Write down the syntax of output statement in Java with an example. iat is meant by Java reserved words? Name five Java reserved words which are commonly used in Java programming. LICSE 2011] 8. Differentiate between the output statements System.out-print( ) and System.out.printin( ). 9. A Java program uses a Compiler as well as an Interpreter. Explain. 10. Write a package that is used for input/output operation in Java. LEARNING SCOPE ming trea Class © Input ty © Input by using Pametion Argument © typut by using Stve a LE oe " by using Scanner Claws © Input using Command Line Argument Types af Error, © Syntax Crror © Logical Error © Run Tine Error © Comment Statements in Java Iypat means to provide data to a computer for processing, While writing tise NPUL statement fo accept date from the user, Hence, input sutement ¢ enter data at run time (.c., during execution of a program), ‘The different computer languages have different syntax to input values, Java allows users to enter data for processing inthe following ways: PIOPTAM, Ye ables User jy NE pe 1. Using, Function Argument 2. Using InputStreamReader Class 3. Using Seanner Class 4, Using Command Line Argument 1 Usin retion Argument This is one of the methods to uecept the value from the user at the time of execution of the program, The variables whose values are to be input must be provided as arguments to the main( ) function, Example: public static void main(int a, int b) The above funct progi progi on will accept two integer numbers from the user, ‘The output of the Wis obtained on the screen after execution, Let us have a look on the sample ns. Sample Progra Prog. 1 Write a program to input princip: fe and time, Calculate and display the difference between Simple Interest (SI) and Compound Interest (CI) by using function argument, (Hint: Cl = A- P; where, /To find the difference between Compound Interest and Simple Interest public class Difference { public static void main(int p, int r, int t) { double. ‘O,aumt,diff=0; si=p*r"t/100,0; System.out.printin("The Compound Intei '+(float)ci); 48 | Understanding Computer Applications with Bluel—X stem.outprindn(Phe Shnple titerent &Rn.49h); System out printine'Phe differcnee between Chand SE Rn." (oad, ! ) Excention of the program ond amin tt 4) | the Compound Inveremt: tin. 1660.0 (ee shi sse J Phe Staple rnterant en.1600.0 je fa one b re The diffnrence betwern CL and st Hn.00.0 Write @ program in Java to accept the number of days and display the result after converting i into number of years, number of months. and the remaining number of days. J To convert days into years, months and days public class days { public ( int b,y,m,d; V305; b=0%365; static void maingint a) using function argument System.out.printin(*The number of years =“ y)s System.out.printin@’The number of months = “4+ m); System.out.printin(*The number of days = “+ d); ) ) Output: ‘old main(int a) g_use the following StEPS! “Hence, first of all We neg 2. Using Stream Class ‘To input a value by using 11 (i) InputStreamReader cl to import this package by 4 putStreamRes i ble in j ng the statement vaio packag' and BufferedReadg, io* 10. amReader Import ja (ii) In the main functior classes as shown below: n, create objects oF InputStre: aden System.in)s BufferedRea ‘The object names like read al InputStreamReader read = REW InputStreamRe: ler in = new BufferedReader(read) a as per the user's choice. nd in can be any word ‘The different types of values © Data Values tay to Accept Numeri . + To accept an integer: int n; . . ec: System.out.printin(“Enter a number”): ae accepting data Uoagh n = Integerparselnt(in.readLine( ))* InputStreamReader class and. + To accept a decimal number: ‘Scanner class, a relevant message float n; must be displayed before the . : input statement. This is used as System.out printin(“Enter a decimal number”): q prompt for the user and It alse n = Float.parseFloat(in.readLine( )): activates the input editor. + To accept a decimal fraction up to 64 bit double n; System.out.printIn(“Enter a decimal number"); n = Double.parseDouble(in.readLine( )); @ Syntax to Accept a Character char ch; System.out.printIn(“Enter a character”); ch = (char)(in.read( )); tax to Accept a String String str; System.out.printIn(“Enter a String”); str = in.readLine( ); A Sample Program A class contains ‘b’ number of boys and ‘g’ number of girls. On a rainy day, ‘ba’ number of boys and ‘ga’ number of girls are absent. Write ‘a program to input the values of ‘b’, ‘g’, ‘ba’ and ‘ga’. Calculate and display the following: (i) Percentage of girls present in the class. Gi) Percentage of boys present in the class. [Percentage must be calculated on the total number of students.] Bex 1 To find the percentage of girls and boys present in the class import java.io.*; public class Present { public static void main(String args[]) throws IOException { int g,b,ga,ba; float pg.pb; InputStreamReader read= new InputStreamReader(System.in); BufferedReader in= new BufferedReader(read); System.out.printIn(“Enter number of girls and boys of the class”); g = Integer.parseInt(in.readLine()); b = Integer.parseInt(in.readLine()); ‘System.out.printin(“Enter number of girls and boys absent in the class”); integer.parseInt(in.readLine()); integer.parseInt(in.readLine()); pg=(float)(g-ga)/(g+b)*100; pb=(float)(b-ba)/(g+b)*100; System.out.printIn(“Percentage of girls present in the class="+pg); System.out.printn(“Percentage of boys present in the class="+pb); } } Output: §. Using Scanner Chass 1O tapaea vate by: aniing Seanner chew sl nach (0 Seannor olin is a membor of jayne shown below Je following eps! h sue, Monee, fant of all, WRDON jAVajqy Paekage in your programe ay 1+; or Import java.util. seanners ety Package Dot Claw operator import jn ii ( crion its showny GD Croate object of Scanner elasy in the main fanctt Seannor (Systom.in); Seanner sc os new 1 + 1 A Class Seannor Now Class Object Oporator You ea use any object name of your choice 1 lata types can be input by using next() functions of S : " ‘anner Gi) "Phe values of diffe class ais per the table shown below: integer int © seanexttnt( ); float Moat f= senextlloat( ); double double d jextDouble( J; string String 9 = XI); OF String 8 = in.nextLine( A Sample Program Prog. 47 Write a class with name employce and basic as its data member. Find the ‘ wa gross pay of an employee for the following allowances and deduction, Use meaningful variables: Dearness Allowance 25% of Basic Pay House Rent Allowance = 15% of Basic Pay Provident Fund = 8.33% of Basic Pay Net Pay = Basic Pay + Dearness Allowance + House Rent Allowance Gross Pay = Net Pay — Provident Fund 2005) 2° W program to calculate Employee's Gross and Net Salary by using Scanner Class*/ import java.util; public cl ( public static void main(String args|}) { Scar imployee_Salary System.out.printin(“Enter employce’s name and basic salary”); double basie,da,hra,pf,gp=0.np=0; String empn; basic*8.33/100.0; asictdathra; np=gp-phy System.out.printin(“Name of the employee ="+empn); System.out.printIn(‘Gross P: System.out.printIn(“Net Pay=Rs: } } Output: Nee Fayeaa.29837.5 4, Using Command Line Argument This is one of the ways to accept the data values from the user and pass the arguments (known as command line arguments) to the main function. While accepting the values from the console, the system stores the data values in different locations as an array of strings. The arguments to the main function are passed through args[0], argsf1}, args{2] and so on. To input a value by using command line arguments use the following steps (Use a string type array (args[]) as an argument to the main function below: public static void main(String args[ }) or (String [ Jargs) (ii) The values of different d i eee integer float double string A Sample Program Java to find the value of the given expression, a+ (a-) Prog. 5 — Write a program in Pp A a a ine argument 1 To find the value of the given expression by using command line arg public class Expression { public static void main(String argst)) { int ab; double p; en /** The values of a and b are entered through argument in String form a = Integer.parseInt(args[0)); b = Integer.parseInt(args{1]); P = (double)(a*a+b*b)/(a-b); System.out.printIn(“The value of the expression ="+p); } } Compilation and Execution Step 1: Compile and close the program. Expression - Computer 10 |[ctass ae Toots Options |) {compite! Undo| Cut) Copy| Paste | Find. Close Source Code ¥ public class Expression public static void main(Stri os ant a double /s* the values of a and b are entered through arguent in String form+/ fa = Integer.parseint (azgs10]) 7 b = Integer.parsernt (args{1]); Pp = (double) (atatbsb) / (ab); Systen.out.printin(*"Zhe value of the expression ="tp), ph eysrat me a ‘Class compiled -no sy Ste] “Expression. + Emter the value as ‘Strings’ in the space provided under the main( )" in the Method Call window (as shown). : Click Ok. ‘The value of the expression =24.142657342057142 ‘The output of program will appear on the Terminal Window. es of Errors (When you run a program then it may happen that you ma due to incorrect input data and hence, some error arises. Generally, of errors that can occur in a computer program, i.e, 1. y not get the desired result there are three types Syntax error Logical error 3. Run time error 1, Syntax error ‘These errors occur due to the grammatical errors in the programming language, It may be missing of punctuation sign, incorrect instructions, undefined variables, etc. ‘A snippet is illustrated below: (int a=145,b=40.c=50: p= (atbyle: | System.outprintin(“The value of the expression ="+p); variable ‘p’ is not defined in the program. Here, you can notice that the data type of ou define the data type of the variable ‘p’ Thus, the program shows a syntax error. If y as double, it shows ‘No syntax error’. Thus, the program is error-free and ready to execute. Syllabus | 55 2. Logical error an The error which occurs in the programming logic is known as tox ee Wise the program is compiled successfully but does not produce the desire s. A u A snippet is illustrated below: Ans. = 160.8 ; ; In the snippet shown above, there is no grammatical error in the structure of the program. Hence, program will compile and execute the result. But the result is not the desired result as per the requirement. Here, user wants to divide the sum of ‘a’ and ‘b’ by c. But the statement p = ashy bo. - instructs the compiler to add ‘a’ with the result of o which is a logical error. Ty overcome this error, the statement should be written as shown below: int a=160,b=40¥ float p=0; P= (atb)/e; System.out.printin(“The value of the expression ="+p); Ans, = 4.0 Thus, the correct result is obtained. 3. Run Time error Tis a type of error that occurs at runtime when the compiler does not respond properly while executing a statement. For example: Dividing a number by zero or trying to find out the square root of a negative number, etc. Consider the following snippet. | p= (atb)/e; System.out printIn(“The value of the expression ="+p); value, which is a run Here, the value of c = 0, so the result will come to an infinite time error. Jaya Programming it more readable for the user: ation about the code to the user. Java programming. They are: fament Statements in Comments in a program m the compiler. They only provide inform ‘There are three ways to give a comment in 1. Single line comment (/) 2, Multi line comment (/* 3. Documentation comment (/** They are not executed by */) on 1. Single Line Comment itis a single line comment which provides short relevant in A single line comment starts with // followed by the mes For example: 1/ A program to find the sum of two numbers formation about the program. Ce Multi line Comment ‘a way {0 present more information about programs to explait mment lines and ends with */. in the logic in detail. It ‘This comment starts with /* followed by the cor For example: /* A program to calculate discount It accepts the marked price and discount percent as inputs“/ 3, Documentation Comment Documentation comment is not a discussion text document to be viewed by other users. TI the set of comment lines and ends with */. For example: /** Author name : Amit Shukla Starting date of project: 05/03/2018 Completion date of project: 12/05/2018*/ about the program logic but includes some his comment starts with /** followed by REVIEW i cight _ Q.1 What is the purpose of the following functions? (i) nextInt( ) (ii) nextLine( ) ‘Ans. (i) nextint( )function is used to accept an integer value from the user at the time of execution. (ii) nextLine( function accepts a string including spaces at the time of execution. Q.2 Predict the output in each case: (i) Math.sqrt (-36) (i) Math.pow(-4,3); Ans. (i) The square root of a neg % th Plata: , the output will (il) The outp IX Syllabus | 57 i in the program? 2.3 Why do you need to mention the keyword Seas ee ANS. The keyword import allows to include a packagi 4 What happens when . () the value of a variable is divided by a (i) semicolon is missing in an input/output st 1 1e" error Occurs. Ans. (i) When a value is divided by zero, ‘Run Timi ence then ‘SYM ror (i) If semicolon is missing in the input/output sta “ a Q.5 Name the method of scanner class that is used to input: () a decimal number from the console. (Gi) a word or text of a line from the keyboard. Ans, () nextFloat( ) or nextDouble( ) ()_next() or nextLine( ) I. Fill in the blanks: 1. The p: 2 ackage needed to import StreamReader class is . + function accepts an integer by using scanner object. 3. The package needed to import Scanner class is 4. The keyword . - is used to include a package in a program. Division by a variable that contains a value zero is called +. error, ~ Statement is used to accept value at run time. ~ function accepts a string by using scanner object, ~ Keyword refers to a non-returnable type function. 9. Scanner ob = --- Scanner(. =) ©. The command line argument accepts the d 1 lata value as an of Strings. HL. Explain the following functions: 1. Integer-parseInt(in.readLine( )); 2 (char)(in.read( )); 3. next( ); 4. nextInt( ); 5. nextLine( ); UL. Answer the following: (af What are the different ways to give input in a Java Program? \_2-What is a package? Give an example. \_ 3 What is the use of the keyword ‘import’ in Java Programming? 4. What is a Run Time erro: *? Explain with an example, \ 5 What are the different types of errors that take pk Name them. 6. Give two differences between Syntax error ace during the execution of a program? and Logical error, 1V. Unsolved Java Programming: 1. In an election, there are candidates X and Y. On the election day, 80% of the voters go for polling, out of which 60% vote for X. Write a program to take the number of voters as input and calculate: (i) number of votes X get (ii) number of votes Y get A shopkeeper offers 10% discount on the printed price of a mobile phone. However, a customer has to pay 9% GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer taking printed price as an input. . Aman spends + of his salary on food, on rent, 2 on miscellaneous. Rest of the salary is his saving. Write a program to calculate and display the following: (@ money spent on food (i) money spent on rent (ii) money spent on miscellaneous (iv) money saved Take the salary as an input. is Write a program to input time in seconds. Display the time after converting them into hours, minutes and seconds. Sample Input: Time in seconds: 5420 Sample Output: 1 Hour 30 Minutes 20 Seconds The driver took a drive to a town 240 km at a speed of 60 km/h. Later in the evening, he drove back at 20 km/h less than the usual speed. Write a program to calculate: (i) the total time taken by the driver (if) the average speed during the whole journey total distance total time oe Vrite a program to input two unequal numbers. Display the numbers after swapping u [Hintraverage speed = heir values in the variables without using a third variable. Sample Input: a Sample Output: a = 76,b = 65 65, b = 7 A certain amount of money is invested for 3 years at the rate of 6%, 8% and 10% per annum compounded annually: Write a program to calculate: (i) the amount after 3 years (i) the compound interest after 3 years. Accept certain amount of money (Principal) as an input. r . Hint: A = Px + ay ou +2) 0+ FS-)' and ci= A-P 8. The co-ordinates of two points A and B on a straight line are given as (x1,y1) and 2. (x2,y2). Write a program to calculate the slope (m) of the line by using formula: — Wav) Slope = “(Q7— x1) Take the co-ordinates (x1,y1) and (x2,y2) as input.

You might also like