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

JAVA1 - Solution - Oct 22 - NSGAcademy

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

JAVA1 - Solution - Oct 22 - NSGAcademy

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAV/ TYBCS ~ Oct 2022 Exam Attempt any EIGHT of the following [8 4) What is use of Javae? (Chapter — 1) Solution: javac is the Java compiler, which is used to compile Java source code into platform- independent bytecode that can be interpreted and executed by the Java Virtual Machine (JVM). The javac command is a part of the Java Development Kit (IDK) and is typically used in the command-line interface. There are following some key uses of the javac command: ‘Compilation Error detection Generating class files ) Give the name of any two wrapper classes. (Chapter ~ 2) Solution: Two commonly used wrapper classes in Java de as follows i, Byte: The Byte class is the wrapper class forthe byte primitive type. It provides methods for converting between byte vallies and Siring objects, parsing String representations of bytes, and performing various operatidins on byte values, fi, Float: The Float class is the-wrapper class for the float primitive type. It provides methods for converting between float values and Siring objects, parsing String representations of floa's, and performing mathematical operations. ©) What is use of ‘implements? keyword? (Chapter ~ 3) Solution: There are following some key uses of the ‘implements’ keyword: i, Implementing interfaces: By using the implements keyword, a class can declare that it intends to implement the methods specified by one or more interfaces. This means the las will provide the necessary method implementations required by the interface(s) ii, __ Multiple interfaces: Java allows a class to implement multiple interfaces by separating thein with commas. For example, ‘class MyClass implements Interfacel, Interface?” Indicates that ‘MyClass’ implements both “Interface” and “Interface2", and it must provide implementations for all the methods declared in both interfaces, {), List types of constructor. (Chapter ~ 2) Solution: Constructor in java is a special member of class which is generally used to initialize objects There are two types of constructors in java ‘No-argument Constructor: A constructor that has no parameter is called as no-argument constructor. Parameterized Constructor: A constructor that has parameters is called as parameterized come cones acta IE NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electror Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAVA-L TYBCS ~ Oct 2022 Exam °) F) h) Note: If class doesn’t have any constructor, then java compiler provides a no-argument constructor which is called as default constructor. What is use of Array? (Chapter ~ 1) Solution: Uses of Array: Storing and accessing multiple values: Arrays allow us to store’multiple values of the same type in a single variable. Each element in the array can be aetessed using an index, ‘which represents the position of the element within the array. This makes it easy to access and manipulate individual elements. Sorting and searching: Arrays are commonly used sort ind searching algorithms. Sorting algorithms like bubble sort, selection sort, and guicksoioften rely on arrays to store and manipulate elements, Searching algorithms like binary search also require sorted arrays to perform efficient searches: ive the name of any two listeners. (Chapter ~5) Solution: Listeners are used for handling the events geiigrated from the source. The java.aw.event package provides many Listener interfaces for event handling. Two of them are as follows ActionListener: It is notified against ActionEvent that indicates a component-defined action occurred like a button click or selecting an item from the menu-item list ItemListener: It is notified against ftemEvent that indicates whether an item was selected ‘What is exception? (Chapter ~ 4) Solution: Exception is an tinexpected event, which occurs during the execution of program, that disrupts thetnormal flow of the program and program terminates abnormally, which is not recommended, therefore, these exceptions should be handled There are two types of exceptions in Java ie., checked exception and unchecked exception Give the syntax of endsWith() method? (Chapter ~ 2) Solution: The endsWith() method is used to check whether a string ends with a specified suffix, Syntax: public boolean endsWith(String suffix) Here, endsWith( is a method available in the Siring class. Ittakes a single parameter suffix, which is the string that we want to check if it is a suffix of the original string. The method returns a boolean value tre if the original string ends with the specified suffix; otherwise, it returns false. sonesacena NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electror Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAVA-L TYBCS ~ Oct 2022 Exam i) What is package? (Chapter ~ 2) 2. Attempt any FOUR of the following : [ax Solution: A java package is a group of similar types of classes, interfaces and sub-packages, There are two types of packages: built-in package and user-defined package. Some examiples of built-in packages are lang, util, io, awt, swing, sql et. There are following ways to access package in a java source file import pkgname.* import pkgname.classname; ‘What is use of new operator? (Chapter ~ 1 & 2) Solution: Uses of new operator: Creating objects: The new operator is used 0 ereate ai instance of a class. When we use new followed by the name of a class, Java allocates memory to store the object and initializes its instance variables. It then returns a reference to the newly created object. Allocating memory for arrays: The new operator ean also be used to allocate memory for arrays of any data type. We can Specify the size of the array using square brackets CLD) after the data type, sl Java will allocate contiguous memory for the specified number of elements. ) ‘When constructor of elas will be called?” Comment, (Chapter — 2) Solution: In Java, the constructor of a class is called in the following scenarios: ‘Object instantiation: The constructor is called when we create a new instance (object) ‘of a class using the ‘new’ operator. The constructor is invoked at the time of object ‘ereation to allocate memory for the object and initialize its member variables, Inhetitanée hierarchy: When a class extends another class, the constructor of the siiperclass is called implicitly before the constructor of the subclass. This ensures that the superclass is properly initialized before the subclass. ‘Construetor chaining: In constructor chaining, one constructor calls another ‘constructor in the same class using the #his() keyword to perform additional initialization tasks, Its important to note that constructors are not called directly using method invocation syntax, They are automatically invoked during object creation or as a result of constructor chaining. Their purpose is to ensure that objects are properly initialized and ready for use. sonesaceona. [EI NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAV/ TYBCS ~ Oct 2022 Exam ») What is command line argument? Where they are stored in a program. (Chapter ~ 1) Solution: Java command-line argument is an argument jc., passed from console during execution of java program. The passed arguments are received in java program and they can be further used as an input. Number of arguments may be zer0 or many and must be separated! by space. JVM ‘wraps all arguments and supplies them to the main () of programs as an arniy of Strings. Here's an example of the main() method with the args parameter: public static void main(String[] args) { // Program logic goes here } ‘The args parameter is an array of strings (String{]) that contains the Command-line arguments, ‘When we execute a Java program from the commatil line and provide arguments, those arguments are stored in the args array. The first argument js stored in args[0], the second argument in argsf 1, and so on. For example, if we run the following commie in the terminal: java MyProgram arg! arg? fg ‘The args array will be populated as follows: cargs[0] = arg” cargs{l] = arg" cargs[2] = "arg" ©) What is Frame? Giye its any two methods. (Chapter ~ 5) Solution: Frame is siclass that represents a top-level window with a border and title. It is a part of the Abstract Window Toolkit (AWT) and is used to create graphical user interfaces (GUIs). The Frame elais extends the Window class and provides functionality for creating and managing windows in a Java application, ‘The Frame class provides a wide range of methods for managing windows, handling events, setting layout managers, and more. Two commonly used methods of the Frame class: setTTitle(String title): This method is used to set the title ofthe frame. It allows us to specify a string that will be displayed as the title of the window in the title bar. setSize(int width, int height): This method is used to set the size of the frame. It allows us to specify the width and height in pixels thatthe frame should be resized to. sunesaceona. [EI NSG ACADEMY Contact: 9823782121 / 7276030223 OBJECT ORIENTED PROGRAMMING USING JAV/ 1* Floor, Pinaccle Pride, Above Maharashtra Electronics, Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam Exampk import java.awt*; public class MyFrame extends Frame { public MyFrame() { setTitle("NSG Academy"); setSize(300, 200); setVisible(true); public static void main(Stringl } gs) { MyFrame frame = new MyFrame(); 4) Differentiate between method overloading and method overriding, (Chapter ~ 2 & 3) Solution: ‘Method Overloading Method Overriding Overloading means reusing # method name, but with different arguments Overloaded method must have different argument lists Overriding means providing the specific ‘implementation of a method to a subclass which is already provided by its super class Overriding method must have the same argument list, Overloaded methiod may have different return types. Overriding method must have the same return type, except that as of Java 5, the return type can be a subclass which is known as a covariant return, Overloaded method may have different access modifiers Overriding method must not have a more restrictive access modifier. It may have a less restrictive access modifier. cones aceon [EI NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAV/ TYBCS ~ Oct 2022 Exam ©) Write any two access specifiers. (Chapter ~ 2) Solution: There are four access specifiers in java ie., public, private, protected and default (no explicit specifier) that control the accessibility of classes, methods, and variables. Each access specifier has its own rules and limitations, allowing us to control the visibility and accessibility of elements based on our program's design and requirements. There are following two commonly used access specifiers publie: The public access specifier allows the declared element {0 he accessed from anywhere in the program, including other classes, packages, and ever external programs. It provides the highest level of accessibility. private: The private access specifier restricts the accessibility of the declared element to within the same class. It ensures that the elements not accessible from outside the class, including other classes and packages. Example: public class MyClass { public int x; —//'can be accessed from anywhere private int y; can be accessed within the sane class private void m1() { // m1() caitbe invoked within the same class 1 Code goes here } public void m2() { 1 m2( gait be invoked from anywhere Code goes here 3 3. Attempt any TWO of the following: (Out of Three) [2x48] ) Define ary interface shape with abstract method area() Inherit interface shape into the class triangle, Write @Java Program to calculate area of Triangle. (Chapter ~ 3) Solution import java.util; interface Shapet double area(); i class Triangle implements Shape private double base: private double height; public Triangle(double base,double height) { this.base = base; this height = height; } cones aceon. NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, OBJECT ORIENTED PROGRAMMING USING JAV/ Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam public double areaQ){ double a; = (this base * this height)/2; return a; } class TestTriangle| public static void main(String args{]){ ew Scanner(System.in), Seanner se double bh; System.out prini("Enter base and height of triangles") b= se.nextDouble(); h=semextDouble(): ‘Triangle t= new Triangle(bh); System.out printin("Area of triangle : "+.area()); } b)_ Design the following sercen by using swing, Student details —|5]x Roll No. Name Percentage Display| Clear] Write & Java program to accept the details of student & display on console by clicking on Display button, Clear button should clear all the controls. (Chapter ~ 5) Solution: import java.awt*; import java.awt.event.*; import javax.swing.*: class StudentFrame extends JFrame implements ActionListener { SLabel jl 2413; ‘JTextPield jtfl jtf2,e#3; Button jbl jb2; cones acta NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAV/ TYBCS ~ Oct 2022 Exam StudentFrame(){ setLayout(new FlowLayout()); setl.ocation( 50,50); setSize(200,350); setTitle("Student Details"); {lI = new JLabel("Roll No."); add(il) jtfl = new JTextField(20); adit); j12 = new JLabel("Name") add(il2);, jtf2 = new JTextField(20); add(tt2); j13 = new JLabel("Percentage"); add(il3);, itf3 = new JTextField(20); add(tt3); bl = new JButton("Display") add(jb): {jbl addActionListenes(this) {jb2 = new JButton( add(jb2);, jb2.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true): es public Void actionPerformed(ActionEvent ae){ iffae,getSource() = jb1){ ‘System out printin("Roll No :"tfl.getText()); ‘System.out.println("Name :"*jtf2.getText(); ‘System out println( "Percentage :"+jtf3.getText()); ) if(ae.getSource() — jb2){ jtfl setText("" jtP2setText("); jt setText("™); ) } Public static void main(String args{]){ new StudentFrame(); sunesaceona [EI NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, Sadashiv Peth, Pune-30 OBJECT ORIENTED PROGRAMMING USING JAV/ TYBCS ~ Oct 2022 Exam ©) Write a Java Program to copy the contents from one file into another file. While copying, change the case of cell the alphabets & replace all the digits by “*”. (Chapter ~ 4) Solution: import java.io.*; class MyFile{ public static void main(String argst)){ int n=args.length; int x; iffn==2)¢ yt FileReader fr=new FileReadertargs{0)); FileWriter fw —new FileWriter(args{ I); while((x=fi.read())!=1){ char ch=(cha)x: if{CharacterisUpperCase(ch)) ch ® Character.toLowerCase(ch); else if{CharactenisLowerCase(ch)) ‘ch = Character.toUpperCase(ch); iffCharaeter isDigit(ch)) ch; fiw.write(ch); fr.close(): fiw.close(); Jeatch(Exeeption e){ System.out printin(e); } jelset System out printin("Invalid arguments"); ) sunesaceona. [EI NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, OBJECT ORIENTED PROGRAMMING USING JAV/ Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam 4, Attempt any TWO of the following: (out of Three) [2x48] a) Differentiate between AWT & Swing. (Chapter ~ 5) Solution: AWT Swing ] Java AWT stands for Abstract Window | Java Swing is mainly referred to as Java Toolkit. Foundation Classes (FC). ‘The AWT component classes are provided by | The Swing component classes ate provided by Javaawt package Javax.swing package ‘The AWT components are heavy weighted | The Swing components are light weighted ‘The AWT components are platform dependent | The Swing component are platform independent The Appearance of AWT Components is | The Swing Components are configurable and mainly not configurable. It generally depends | mainly support phiggable look and feel ‘on the operating system’s look and feels Java AWT has comparatively less | Java Swing has more functionality as functionality as compared to Swing ‘compared to AWT Java AWT needs a higher amount of mnemory | Java,-Swing needs less memory space as for the execution. ‘compared to Java AWT. Java AWT is slower than swing in terms of | Java Swing is faster than the AWT. performance. ! b) Define user define exception zeronumber Exe. Write a Java program to accept a number from user. IF itis zero then thpow user defitié exception “Number is zero” otherwise calculate the sum of first & last digit of given Humber. (use Static keyword). (Chapter ~ 4) Solution: import javacl.*; class ZeroNumberExeeption extends Exception{ public String toString) return "Number is Zero" } class MyNumber{ private static int no; public static void accept(){ Scanner se = new Seanner(System.in): System.out print("Enter a number"); zno = se.nextInt(); sane AGRAWAL NSG ACADEMY Contact: 9823782121 / 7276030223 OBJECT ORIENTED PROGRAMMING USING JAV/ 1* Floor, Pinaccle Pride, Above Maharashtra Electronics, Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam public static void caleulate(){ uyt iffno 0) throw new ZeroNumberException(); else int sum = 0; sum = sum + (n0%10); while(no>9){ no = no/10; ) sum = sum + no; System. out printin("Sum of First & Last Digit is " Jcatch(ZeroNumberException e){ System.out printine); ' public static void main(Striag args[]){ accept(); calculate; } } Suni); ©). Write a Java program to accept n number from user & store only perfect numbers into array & display (hat array. (Chapter — 1) Solution: import java itil" elassiTestA ray { public static boolean isPerfeetint no){ iffno=1) return false; int sum = 1 for(int i=2; i0){ System.out.print("Enter number: 1no= sesnextInt(); iffisPerfect(no)){ afi] = no; i ) System.out.printin( forint jnO:icigi++) ‘System.out.prinialj Il perfeh numbers ai¥ as follows"); System.out printin(); 5. Attempt any ONE of the following: (out of Two) [33 8) Explain uses of final keyword with example. (Chapter — 1 & 3) Solution The final keyword provides immutability and guarantees thatthe declared entity will mot be piodified.Iphelps in ereating constants, preventing method overriding, and prohibiting class extension, depending on where itis used By using the final keyword, we can enhance code readability, maintainability, and enforce esired behavior in our Java programs. Hete are some common uses ofthe final keyword: 1) inal variables: Constants: By declaring a variable as final, we can create a constant whose value cannot ‘be changed once assigned. It is a common practice to use uppercase letters and underscores for naming constants, Example: final int MAX_VALUE = 100; final double PI = 3.14159; NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, OBJECT ORIENTED PROGRAMMING USING JAV/ Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam 3 Method parameters: When a parameter is declared as final, its value cannot be modified within the method. This is useful for ensuring that the parameter remains unchanged. ‘throughout the method execution Example: public void display( final String str) { 1 The value of the sér parameter cannot be modified here System.out printin(str); il methods: Method overriding prevention: When a method is déClared us final in a superclass, it ‘cannot be overridden by any subclass. This ensues that the behavior of the method in the superclass remains unchanged and cannot be moidified by Subclasses. Example: class A { final void m1() { / Method implementation class B extends A { 1 Cannot override the ini() method } Final classes: Class inheritance prevention: When a class is declared as final, it cannot be extended by anly other class. This means that the final class cannot have subclasses. This is useful ‘when we Want to prevent further extension and ensure that the class's implementation remains intact Exaniph final class A { 1 Class implementation 1 cannot extend the A class J class B extends A { } NSG ACADEMY 1* Floor, Pinaccle Pride, Contact: 9823782121 / 7276030223 Above Maharashtra Electronics, OBJECT ORIENTED PROGRAMMING USING JAV/ Sadashiv Peth, Pune-30 TYBCS ~ Oct 2022 Exam b) Define a class Emp with a member Eid and display() method, inherit Emp class into the EmpName class, EmpName class having a member Ename & display() method. Write a Java program to accept details of employee [Eid, Ename] & display it. (Use super keyword). (Chapter 3) Solution: import java.util.*; class Emp private int Eid; public Emp(int Eid) { this Eid = Bi public void display(){ System.out println("Employee ID : "*Eid); } } class EmpName extends Emp private String Ename; public EmpNametint Eid, Strtig Ename){ super(Eid); this.Ename = Enane: } public void display()i super.display(); System.out printin("Employee Name : "+Ename); } } élass Testnipy public static void main(String args{){ Scanner se = new Seanner(S int ids String name; System.out print("Enter Employee id e-mextInt): System.out.print("Enter Employee name:"); name = se.next(); EmpName ob = new EmpName(id,name) ob.display(), tem.in);,

You might also like