0% found this document useful (0 votes)
11 views26 pages

S-22

The document is a model answer sheet for the Summer 2022 examination in Java Programming from the Maharashtra State Board of Technical Education. It provides guidelines for examiners on assessing student answers, including how to evaluate understanding and credit for various types of responses. Additionally, it contains sample questions and answers covering key Java concepts, programming syntax, and error handling.

Uploaded by

prajwalhulle105
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)
11 views26 pages

S-22

The document is a model answer sheet for the Summer 2022 examination in Java Programming from the Maharashtra State Board of Technical Education. It provides guidelines for examiners on assessing student answers, including how to evaluate understanding and credit for various types of responses. Additionally, it contains sample questions and answers covering key Java concepts, programming syntax, and error handling.

Uploaded by

prajwalhulle105
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/ 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 Important Instructions to examiners: 1) The answers should be examined by key words and not as wordsto-word as given in the model answer scheme. 2) The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding level of the candidate. 3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for subject English and Communication Skills. 4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn by candidate and model answer may vary. The examiner may give credit for anyequivalent figure drawn. 5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and there may be some difference in the candidate's answers and model answer. 6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on candidate's understanding. 7) For programming language papers, credit may be given to any other program based on equivalent concept. 8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if the students in first year (first and second semesters) write answers in Marathi or bilingual language (English +Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model answer, Q] Sub “Answer Marking No | Qn. Scheme 1. ‘Attempt any FIVE of the following: 10 a) _| Enlist the logical operators in Java. 2M Ans. | && : Logical AND IM each ||: Logical OR Any two | _: Logical NOT operators D) _ | Give the syntax and example for the following functions 2M i) min() ii) Sqrt () Ans. | i) ming Syntax: (Any one of the following) IM for static int mintint x, int y) Returns minimum of x and y each static long min(long x, long y) Returns minimum of x and y | function static float min(float x, float y) Returns minimum of x and y with static double min(double x, int y) Returns minimum of x andy _|_ example Page 1/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 Example: int y= Math.min(64,45); i)Sqrt) Syntax: static double sqrt(double arg) Retums square root of arg. Example: double y= Math.sqrt(64); ° Define the interface in Java. 2M Ans. | Interface is similar to a class It consist of only abstract methods and final variables. IM for To implement an interface a class must define each of the method | each point, declared in the interface. Any two It is used to achieve fully abstraction and multiple inheritance in | points Java. @) | Enlist any four inbuilt packages in Java. 2M Ans, | 1 java.lang %M for 2java.util each 3.java.io package 4,java.awt Any four S java.net packages 6,java.applet ©) _ | Explain any Ovo methods of File Class 2M Ans. | 1. boolean createNewFile(): It creates a new, empty file named by | 1M for this abstract pathname automatically, if and only if no file with the | each same name exists. method iffile.createNewFile()) Any two System.out printin(""A new file is successfully created."); methods 2. String getName(): It returns the name of the file or directory denoted by the object’s abstract pathname. System.out.printin("File name : " + file.getName()); 3. String getParent(): It returns the parent’s pathname string of the object's abstract pathname or null if the pathname does not name a parent directory. System.out printIn("Parent name : " + file.getParent()) Page 2/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) Subject: Java Programming Subject Code:| 22412 SUMMER - 2022 EXAMINATION MODEL ANSWER 4, boolean isFileQ; It retums True if the file denoted by the abstract pathname is a normal file, and False if itis not a normal file. ‘System.out.printin("File size (bytes) : " + file.isFile()); 5. boolean canRead(): It returns True if the application can read the file denoted by the abstract pathname, and returns False otherwise. System.out.printin("Is file readable : "+ file.canRead()); 6. boolean canWriteQ): It returns True if the application can modify the file denoted by the abstract pathname, and retums False otherwise. System.out.printin("Is file writeable : " + file.canWrite()); 7. boolean canExecute(): It returns True if the application can execute the file denoted by the abstract pathname, and returns False otherwise, System.out printin("Is file executable : " + file.canExecuteQ)); D 2M Ans. | Syntax: void fillOval(int top, int left, int width, int height) 2M for The filled ellipse is drawn within a bounding rectangle whose upper-__ correct left comer is specified by top and left and whose width and height are | syntax specified by width and height OR Syntax: void drawOval(int top, int left, int width, int height) The empty ellipse is drawn within a bounding rectangle whose upper- left corner is specified by top and left and whose width and height are specified by width and height ®) | Enlist any four compile time errors. mM Ans. | 1)Missing semicolon 4M for 2)Missing of brackets in classes and methods each error 3)Misspelling of variables and keywords. 4)Missing double quotes in Strings. Any four 5)Use of undeclared variable. can be 6)Incompatible type of assignment initialization. considered 7T)Bad reference to object. Page 3/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 2. ‘Attempt any THREE of the following: 12 a) | Explain any four features of Java 4M Ans. | 1.Object Oriented: In Java, everything is an Object. Java can be easily extended since it | 1M for is based on the Object model, each feature Any four features 2.Platform Independent: Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. 3.Simple: Java is designed to be easy to lear. If you understand the basic concept of OOP Java, it would be easy to master. 4.Secure: With Java's secure feature it enables to develop virus-free, tamper- free systems. Authentication techniques are based on public-key encryption. 5.Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. 6.Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. 7.Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. Page 4/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 b) | Write a Java program to copy the content of one file into another. | 4M Ans. | import java.io.*; 2M for class filecopy correct { logic, public static void main(String args[]) throws IOException { 2M for FileReader fr= new FileReader(“file] txt"); code FileWriter fo= new FileWriter("file2.txt"); int ch; try { while((ch=fi.readQ)!= -1) t fo.write(ch); System.out printIn(“file copied successfully”); fr.closeQ; fo.close(); finally if{frt=null) fi.closeQ); if(fo!=null) fo.close(); aa ©) | Write the difference between vectors and arrays. (any four| 4M points) Ans. [S.No ‘Array Vector IM for 1 | An array is a structure | The Vectors similar to array holds | each point that holds multiple | multiple objects and like an array; values of the same it contains components that can be | Any four type. accessed using an integer index. points 2 [An amay is a] Vectors are heterogeneous. You homogeneous data type | can have objects of different data where it can hold only | types inside a Vector. objects of one data type Page 5/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) (ISOMEC - 27001 - 2005 Certified) Subject: Java Programming Subject Code: SUMMER - 2022 EXAMINATION MODEL ANSWER 22412 3] After creation, an array | The size of a Vector can grow or is a fixed-length | shrink as needed to accommodate structure adding and removing items after e Vector has been created 4 /Array can store | Vector are store non primitive type primitive type data | data element. element. Declaration of an array | Declaration of Vector: int arr{] = new int [10];_| Vector list = new Vector(3) 6 | Array is the static] Vector is the dynamic memory memory allocation, allocation a) Ans, lcontained within a try block. If an exception occurs within the try block, it is thrown. Syntax: uy it // block of code to monitor for errors + leateh: [Your code can catch this exception (using catch) and handle it in some lrational manner. System-generated exceptions are automatically Ithrown by the Java runtime system. A catch block immediately lfollows the try block. The catch block can have one or more |statements that are necessary to process the exception, |Symtax: |catch (ExceptionTypel exOb) Ht |’ exception handler for ExceptionTypel I} Explain exception handling mechanism w.rst. try, catch, throw] 4M and finally. ltry: IM for [Program statements that you want to monitor for exceptions are} each Page 6 /26 Subject: Java Programming Subject Code: |_22412 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER [throw: lit is mainly used to throw an instance of user defined exception. |Example: throw new myException(“Invalid number”); assuming lmyException as a user defined exception finally: linally block is a block that is used to execute important code such as |closing connection, stream ete. Java finally block is always executed lwhether exception is handled or not. Java finally block follows try or lcatch block. \Syntax: linally \ block of code to be executed before try block ends P 3 ‘Attempt any THREE of the following: 12 a) _ | Write a Java Program to find out the even numbers from 1 to 100) 4M using for loop. Ans. | class test { 2M for publie static void main(String argsf]) Program { logic ‘System.out.printIn("Even numbers from 1 to 100 :");, for(int i=1;i<=100; i++) 2M for { Program ini%2—0) syntax System.out.print(i+" } + t b) | Explain any four visibility controls in Java. aM Ans, | Four visibility control specifiers in Java are public, default, private and protected. The visibility control in java can be seen when concept | 3M for of package is used with the java application. Explanatio 1) private :The access level of a private specifier is only within the ” class. It cannot be accessed from outside the class. 2) default : When no specifier is used in the declaration, it is called as, default specification. Default scope for anything declared in java, Page 7/26 MAHARASHTRA STATE BOARD OF TECH (Autonomous) (ISO/IEC - 27001 - 2005 Certified) ICAL EDUCATION SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code:| 22412 is implicit public, With this it can be accessed anywhere within | 1M for the same package. access 3) protected :The access level of a protected specifier is within the | speeificatio package and outside the package through derived class. ntable 4) public :The access level of a public specifier is everywhere. It can be accessed from within the class, outside the class, within thepackage and outside the package. 5) private protected access: The visibility level is between protected access and private access, The fields are visible in all subclasses regardless of what package they are in. These fiveaccess specifiers can be mapped with four categories in which packages in java can be managed with access specification matrix as: ‘Access Modifier | Pubife | Protected | Friendly | Private | private ] ‘Access Location (default) | protected Same Class Yes_[ Yes Yes Yes__| Yes Sub elassinsame [Yes] Ves Yes Yer No package ‘ther dassesin | Ves) Ves Yes We No same package Sub classin other [Yes | Yes No Yes No packages Nonsub classes im | Yes | No No We No other packages ©) _ | Explain single and multilevel inheritance with proper exampl aM Ans. | Single level inheritance: In single inheritance, a single subclass extends from a single IM for superclass. each explanatio : IM for Example each class A example { Page 8/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code:| 22412 ‘void display) { System.out printIn(“In Parent class A”); } t class B extends A /iderived class B from A. { void show() { System.out.printIn(“In child class B”); t public static void main(String args{]) { B b= new BO; b.display(); //super class method call bshow0; // sub class method call } } Note : any other relevant example can be considered. Multilevel inheritance: In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as a superclass for another class, Basically it appears as derived from a derived class. Corre Cer Example: class A { void display() Page 9/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 { System.out.printin(“In Parent class A”); } } class B extends A. //derived class B from A { void show() { System. out printin(“In child class B” i } class C extends B_//derived class C from B { public void print() System.out printIn(“In derived from derived class C”); } public static void main(String args[]) { Cc=new CO; c.display(); //super class method call eshow(); // sub class method call c.print); //sub-sub class method call } } Note : any other relevant example can be considered. @)_| Write a java applet to display the following output in Red color. | 4M Refer Fig. No. 1. Fig No. Ans. | import java.awt.*; 2M for import java.applet.*; correct public class myapplet extends Applet logic Page 10/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 { public void paint(Graphics g) 2M for { correct int x[J={10,200,70}; syntax int y[J={10,10,100}; gsetColor(Color.ted); g.drawPolygon(x,y,3); } ** * + ‘Attempt any THREE of the followin; 12 a) | Explain switch case and conditional operator in java with] 4M suitable example. Ans. | switch...case statement: The switch....case statement allows us to execute a block of code among many alternatives IM for Syntax : explanatio switch (expression) ” { switch case case valuel: statement Hf code break; IM for ease value2: example code break; default: 1/ default statements ) The expression is evaluated once and compared with the values of each case. If expression matches with valuel, the code of case valuel are executed. Similarly, the code of case value? is executed if expression matches with value2, Page 11/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 break is a required statement, which is used to take break from switch block, if any case is true, Otherwise even after executing a case, if break is not given, it will go for the next case If there is no match, the code of the default case is executed. Example : / Java Program to print day of week i/-using the switch...case statement class testl { public static void main(String[] args) { int number = 1 String day; switch (number) t case | day = "Monday"; break; case 2: day= "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day~ "Thursday"; break; case 5: day = "Friday"; break; day= "Invalid day" + Page 12/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 System. out printin(day), 3 } Note : any other relevant example can be considered. Conditional Operator: The Conditional Operator is used to select one of two expressions for evaluation, which is based on the value of the first operands. Tt is used | 1M for (o handling simple situations in a line. explanatio Syntax: ” expression! ? expression2:expression3; Conditiona The above syntax means that if the value given in Expression] is true, | f operator then Expression? will be evaluated; otherwise, expression3 will be evaluated. IM for example Example class test { public static void main(String[] args) { String result; int a= 6, b= 12; result = (ab ? "equal":"Not equal"); System.out.printIn("Both are "+result); } } Note : any other relevant example can be considered. b) Draw and explain life cycle of thread. aM Life cycle of thread includes following states 1.Newbom 2. Runnable 3. Running 4, Blocked 5. Dead Page 13/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code:| 22412 2M for diagram New — A new thread begins its life cycle in the new state. It is also referred to as a born thread. This is the state where a thread has been 2M for created, but it has not yet been started. AA thread is started by calling | explanatio its start() method. ” Runnable — The thread is in the runnable state after the invocation of the start() method, but the scheduler has not selected it to be the running thread. It is in the Ready-to-run state by calling the start method and waiting for its turn, Running — When the thread starts executing, then the state is changed to a “running” state. The method invoked is run|() Blocked-—This is the state when the thread is still alive but is currently not eligible to run. This state can be implemented by methods such as suspend()-resume(), wait()-notify() and sleep(time in ms). Dead — This is the state when the thread is terminated. The thread is in a running state and as soon as it is completed processing it is in a “dead state”. Once a thread is in this state, the thread cannot even run. again ©) | Write a java program to sort an I-d array in ascending order] _ 4M using bubble-sort. Ans. | public class BubbleSort 2M for { correct public static void main(String{] args) logic Page 14/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 { int arr{] =(3,60,35,2,45,320,5); System.out printin("Amay Before Bubble Sort"); 2M for for(int i=0; icarr.length; i++) correct { syntax ‘System.out.print(arr{i] +" t System.out printIn(); int n=arr.length; int temp = 0; for(int i=0; in; i++) { for(int j=; j <(n-i); J+) { iffarr{j-1] >arr{i]) { swap elements temp = arrfj-1]; arrfj-1] = anil; arr{j] = temp; i t t System.out printin(""Array After Bubble Sort"); for(int iO; iarr.length; i++) ‘ System.out.print(arfi] +" i } ‘@) _ | Explain how to create a package and how to import it aM Ans, | To create package following steps can be taken: 1) Start the code by keyword ‘package’ followed by package name. 3M Example : package mypackage; for steps to 2) Complete the code with all required classes inside the package | create with appropriate access modifiers. 3) Compile the code with ‘javac’ to get .class file. Page 15/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 Example: javac myclass java to get myclass.class 4) Create a folder which is same as package name and make sure) IM to that class this folder. To import the package inside any other program Make use of import statement to include package in your program. of package is present inside it. If not, copy it inside | import It can be used with ‘*" to gain full access to all classes within package one class access or just by giving class name if j Example import mypackage.myclass; or importmypackage.*; is required, ° Ans. Explain i) drawLine ) ~— drawOval i) drawReet iv) drawAre i) drawLine(): It is a method from Graphics class and is used to draw line between the points(x1, y1) and (x2, y2). Syntax : GrawLine(int x1, int yl, int x2, int y2) ii) drawOval():Its is a method from Graphics class and is used to draw oval or ellipse and circle. Syntax drawOval(int x, ,int y, int width, int height) It is used to draw oval with the specifiedwidth and height. If width and height are given equal, then it draws circle otherwise oval/ellipse. iii) drawRect():Itis a method from Graphics class and it draws a rectangle with the specified widthand height. Syntax drawRect(int x, int y, int width, int height) iv) drawAre():lt is a method from Graphics class and is used to draw a circular or elliptical are Syntax : draw Are(int x, int y, int width, int height, intstartAngle, intsweepAngle) aM IM for each Page 16/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) {ISOMEC - 27001 - 2005 Certified) Subject: Java SUMMER - 2022 EXAMINATION MODEL ANSWER Programming Subject Code: | 22412 where first fourare x, y, width and height as in case of oval or rect. The next two are start angle and sweep angle. When sweep angle is positive, it moves in anticlockwise direction. It is given as negative, It moves in clockwise direction a) Ans. ‘Attempt any TWO of the following: 2 How to create user defined package in Java. Explain with an] 6M suitable example. A java package is a group of similar types of classes, interfaces and | 3M sub-packages Package It also provid s protection and removes name collisions. creation Creation of user defined package: To create a package a physical folder by the name should be created in the computer Example: we have to create a package myPack, so we create a folder | (Note: d:\myPack Code The java program is to be written and saved in the folder myPack. To | Swippet can add a program to the package, the first line in the java program be used for should be package ; followed by imports and the program | describing) logic package myPack: import java.util; public class M Hieode } lass { Access user defined packag To access a user defined package, we need to import the package in our program. Once we have done the import we can create the object of the class from the package and thus through the object we can access the instance methods. 3M for import mypack.*; Example public class MyClassExample{ public static void main(String a[]) { Myclass c= new Myclass(); Page 17/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: | _ 22412 y 3 Example: (Note Any other package packagel; similar public class Box example { can be int l= 5; considered intb=7; J inth=8; public void display() { System.out.printin("Volume is:"+(I*b*h)); } } Source file: import package1.Box; class volume { public static void main(String args[]) { Box b=new Box(); bdisplay(); He b) | Write # Java program in which thread A will display the even | 6M numbers between 1 to 50 and thread B will display the odd numbers between 1 to 50. After 3 iterations thread A should go to sleep for 500ms. Ans. | Import java.lang.*; class A extends Thread { 3M lic void n mb lie void run() Correct by program ° with syntax for(int i=2;i<-50 Page 18/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 ‘System.out.printin("\t A thread :"+4); ifli = 6) // for 3° iteration 3M sleep(500); Correct } logic } catch(Exception e) ‘ System.out printIn("A thread interrupted"); } i } class B extends Thread { public void run() { try { for(int i=1;i<50;i=i+2) { System.out.printin("\t B thread :"+i); catch(Exception e) ‘ System.out printin("B thread interrupted"); , I i class OddEven { public static void main(String argsf]) { new AQstart(); new BO.start(); + } Page 19/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDU (Autonomous) {ISOMEC - 27001 - 2005 Certified) Subject: Java Programming Subject Code: SUMMER - 2022 EXAMINATION MODEL ANSWER 22412 ° Ans. What is constructor? List types of constructor. Explain] 6M parameterized constructor with suitable example. Construetor: A constructor is a special member which initializes an object | 2M for immediately upon creation. + It has the same name as class name in which it resides and it is syntactically similar to any method. + When a constructor is not defined, java executes a default constructor which initializes all numeric members to zero and other types to null or spaces. * Once defined, constructor is automatically called immediately after the object is created before new operator completes. Types of constructors: 1. Default constructor 2. Parameterized constructor 3. Copy constructor 4, Constructor with no arguments or No-Arg Constructor or Non- Parameterized constructor. Parameterized constructor: When constructor method is defined with parameters inside it, different value sets can be provided to different constructor with the same name. Example class Student { int roll_no; String name; Student(int r, String n) // parameterized constructor t roll_no name=n; i void display() { System.out printI("Roll no is: "+roll_no); ‘System.out.printIn("Name is : "+name); i Definition IM List types (Any 3) IM parameteri zed constructor 2M Example (Any Other Example Can be Page 20/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 public static void main(String af] considered { d Student s = new Student(20,"ABC"); // constructor with parameters s.display(; } I os ‘Attempt any TWO of the following: 12 a) | Write a Java Program to count the number of words from a text) 6M file using stream classes. (Note : Ans. | import java.io.*; Any other public class FileWordCount { relevant public static void main(String are{]) throws IOException logic shall { be File £1 = new File("input.txt"); considered it we-0; ) FileReader fr = new FileReader (f1); int e=0; try { while(c!=1) 3M { Correct e=fi.read(; program if(e=(chary'') with syntax wert + System.out printin("Number of words :"+(we+1)); aM t Y finally Correct ( logic if(Git—null) fr.close( t } i b) | Explain the difference between string class and string buffer | 6M class. Explain any four methods of string class Page 21/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 ‘Ans. [Te aie ee TM each os Any 2 points 1_| Sting ss major las StringBaffac iva peer clas of Sting 2 [Lengihistixes Lengths faible 3. [Contents of object cannot be modified | Contents ofobject canbe modified 4 [Object cam be created by asigaing | Objects can te created by calling Sting constints exclosed in double | constructor of StingBuffer class quotes. sing tow operator 5 | Sting “NSBIE™ SteingBaffac snow StingBuffer (MBE) . IM each Methods of string class ‘Any 4 1)toLowercase (): Methods Converts all of the characters in this String to lower case. correct Syntax: s1.toLowerCase() explanatio Example: String s=' System.out printIn(s.toLowerCase()); Output: sachin 2) toUppercase(): Converts all of the characters in this String to upper case Syntax: s1.toUpperCase() Example: String s="Sachin" System.out printIn(s.toUpperCase()); Output: SACHIN 3}trim 0: omitted. Syntax: sL.trimQ Example: String s=" Sachin "; System.out.printIn(s.trim(); Returns a copy of the string, with leading and trailing whitespace n Page 22/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 Output:Sachin 4)replace ():Returns a new string resulting from replacing all occurrences of old Char in this string with new Char. Syntax: sI.replace(‘x’,’y’) Example: String sl="Java is a programming language. Java is a platform."; String s2s1.replace("Java","Kava"); /ireplaces all occurrences of "Java" to "Kava" System.out-printIn(s2); Output: Kava is a programming language. Kava is a platform 5. length(: Syntax: int length( It is used to return length of given string in integer. Eg. String str="INDIA” ‘System.out.printIn(str-length(); // Returns 5 6. charAt(): Syntax: char charAt(int position) The charAt() will obtain a character from specified position Eg. String s-" INDIA” System.out.printIn(s.charAt(2) ); // returns D 7. substring(): Syntax: String substring (int startindex) startindex specifies the index at which the substring will begin.It will returns a copy of the substring that begins at startindex and runs to the end of the invoking string Example: System.out printin(("Welcome” substring(3)); //come (OR) String substring(int startindex,int endindex) Here startindex specifies the beginning index, and endindex specifies the stopping point. The string returned all the characters from the Page 23/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) Subject: Java Programming Subject Code:| 22412 SUMMER - 2022 EXAMINATION MODEL ANSWER beginning index, upto, but not including, the ending index. Example : System.out printhn(("Welcome” substring(3,5));//co 8. compareTo(): tax: int compareTo(Object 0) or int compareTo(String anotherString) There are two variants of this method. First method compares this, String to another Object and second method compares two strings lexicographically. Example, String strl = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable"; int result = str].compareTo( str2 ); System.out.printin(result); result = str2.compareTo( str3 ); System.out.printIn(result); ° Ans. Write a Java applet fo draw a bar chart for the following values. oM — Year 2011 2012 2013 2014 —_—s, uo | 120 170 160 import java.awt*; import java.applet.*; 2M for Applet tag /* 2M for Page 24/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 Syntax public class BarChart extends Applet { 2M int n=0; Correct String label[]; Logic int value]; public void init) { setBackground(Color.yellow); try { int n= Integer parselnt(getParameter("Columns")); label = new String[n}; value = new int[n]; label[0] = getParameter("labell"); label[1] ~ getParameter("label2"); label[2] = getParameter("label3"); label[3] = getParameter("label4"); value[0] = Integer-parselnt(getParameter("el"));, value[ 1] ~ Integer-parselnt(getParameter("c2"));, value[2] = Integer.parselnt(getParameter("c3"));, value[3] = Integer parseInt(getParameter(""c4")); } catch(NumberFormatException ¢){} } public void paint(Graphies g) { forint i=0;i<4;i++) { g.setColor(Color.black); g.drawString(label(i],20,i*50+30); gsetColor(Color.red); g.fillRect(50,i*50+10,value{i],40); ) Page 25/26 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) {ISOMEC - 27001 - 2005 Certified) SUMMER - 2022 EXAMINATION MODEL ANSWER Subject: Java Programming Subject Code: |_22412 im Page 26/26

You might also like