You are on page 1of 21
22CS302 — Java Programming CIA -1 Question Bank Part-A, 1. Distinguish between Class and Object. Class Object Classis used asa template for declaring and creating the objects. An object is an instance of a class. When a class is created, no memory 1s allocated. ‘Objects are allocated memory space whenever they are created. The class has to be declared first and only once. ‘An object is created many times as per requirement. A class cannot be manipulated as they are not available in the memory Objects can be manipulated It is declared with the class keyword Ttis created with a class name in OF and with the new keywords in Java. Example: class car Example: objects ~ Honda, Maruthi 2. Can a java source file be saved using a name other than class name? Justify. No, it isn't compulsory to always save a the file with the same name as the class However, if you define a public class inside your java file, then the name of the file must be sameas that of the public class. It will identify the public class as an entry point to execute the java program. 3. Givea structure of Java program. bese ale eee eel betel eS cha east) Ta tee CCT CoE Tay lly main method class i main method defi Structure of Java Program 4 List any five features of Java. © Object Oriented © Platform independent © Portable * Secure © Multi threaded © Robust © ~~ Distributed 5, List out the types of java tokens. There are five types of java tokens: keywords, identifiers, literals, operators, and separators. Keywords: Keywords in Java are predefined or reserved words that have special meaning to the Java compiler. Example: class final, public, ete Identifier Java Identifiers are the user-defined names of variables, methods, classes, arrays, packages, and interfaces 6. Define access specifier. Access modifiers help to restrict the scope of @ class, constructor, variable, method, or data member. It provides security, accessibility, etc to the user depending upon the access modifier used with the element. Let us learn about Java Access Modifiers, their types, and the uses of access modifiers in this article. ‘Types of Access Modifiers in Java There are four types of access modifiers available in Java’ ‘* Default ~ No keyword required © Private © Protected © Public 7. Consider the following code segment: class Question {public static void main(String argsf) {for(int n=13n<=10;n4+}{ System.out.print(a+" "))}} i)Select the correct output description for the above code a)print first n natural numbers in a single line b)print first n natural numbers, one number in a single line ©)Prints first 10 natural numbers in a single line d)Prints first 10 natural numbers in a single line with no spaces. ii) Modify the above code such that it prints all even numbers till 100 8. Define Inheritance in Java. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. 9. List the type of inheritance in java © Single Inheritance © Multilevel inheritance © Multiple Inheritance © Hierarchical Inheritance © Hybrid inheritance 10. Compare method overriding and method overloading ‘Method Overloading Method Overriding Method overloading is a compile Method overriding is a runtime polymorphism: ‘time polymorphism. Method overloading helps to Method overriding is used to grant the specific increase the readability of the implementation of the method which is already program, provided by its parent class or superclass. Itis performed in two classes with inheritance Itoccurs within the class. relationships. Method overloading may or may Method overriding always needs inheritance. not require inheritance. Th method overloading, methods must have the same name and different signatures, In method overriding, methods must have the same name and same signature. 11. Which of the following statement(s) is/are false? a)You can write a new instance method in subclass with the same signature as the one in superclass, thus overriding it b)you can write a new static method in the subclass with the seme signature as the one in the superclass thus hi ng it ©)A subclass inherits all of its parent public, private and protected members, no matter what package the subclass is in d)You cannot declare new methods in the subclass that are not in the super class. 12. Mention the importance of super keyword. * tis used to access bese case constructors and variables © Itis used to invoke base class methods in case of method overriding. The main purpose of using super keyword is to improve the code readability and to avoid naming conflicts and confusions in case of inheritance. 18, State Package. Ajava package is a group of similar types of classes, interfaces and sub-packages Package in java can be categorized in two form, builtin package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql ete. ‘Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision There are different ways to access the package from outside the package. © import package; © import package.classname; 14, Which package is imported, by default? Justify Java compiler imports java.lang package intemally by default. It provides the fundamental classes that are necessary to design a basic Java program. The important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time. 15, Write the syntax of importing packages in a Java source file and give an example. The following syntax is employed to import a specific class import packageName.ClassName; Example: package myPackage; import java.util.Scanner, public class ImportingExample { public static void main(Stringl] args) { Scanner read = new Scanner(System.in); inti = read.nextint(), System.out.printin("You have entered a number "+i)}} 16. Define Thread in Java? Threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that do not affect the working of other threads despite them sharing the same memory. 17. List the Life cycle of a Thread (Thread States) Scie Runnable run() New Thread() te lalal ia) =4 STi dla =a 18. "Thread is a light weight process” - Comment. ‘Thread is called a light weight process to emphasize the fact that a thread is like @ process but it is more efficient and uses fewer resources (that's why “lighter’) and they also share the address space. Switching between thread is fast comparatively than process. The memory is shared: that makes thread communication easier. 19, What is multithreading? Multithreading is a programming concept in which the application can create a small unit of tasks to execute in parallel. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum ul by using the concepts of threads zation of CPU 20. Compare sleep and wait method. Sleep(): This Method is used to pause the execution of current thread for a specified time in Milliseconds. Here, Thread does not lose its ownership of the monitor and resumés it’s execution. Wait): This method is defined in object class. It tells the calling thread (a.k.a Current Thread) to wait until another thread invokes the notify() or notifyAll() method for this object. Part-B 1, Discuss about the characteristic features of OOPs 2, Discuss about the features of Java 3. Explain about various operators in Java with an example 4, Explain about various data types in java with an example program 5. Explain about any two looping statements with example. 6. Demonstrate the use of any three conditional structures with example. 7. List the types of access modifiers: What are non-access modifiers in Java? Javas access modifiers are public, private and protected. Java also defines a default access level (called package-private) public: When a member of a class is modified by public, then that member can be accessed by any other code. private: When a member of a class is specified as private then that member can only be accessed by other members of its class default: It is also referred to as no modifier. Whenever we do not use any access modifier itis treated as default where this allows us to access within a class, within a subclass, and also non-sun class within a package but when the package differs now be it a subclass or non-class we are not able to access protected: With the above default keyword we were facing an issue as we are getting closer to the real world with the above default modifier but there was a constriction as we are not able to access class sub-class from a different package. So protected access modifier allows not only to access class be it subclass or non-sub class but allows us to access subclass of the different package which brings us very close to a real-world and hence strong understanding of inheritance is required for understanding and implementing this keyword. Non-access Modifiers In java, we have 7 non-access modifiers. They are used with classes, methods, variables, constructors, etc to provide information about their behavior to JVM. They are as follows: © static © final © abstract © synchronized e transient «volatile ° native Final: In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended. Here are some of its characteristics: Final variables: When a variable is declared as final, its value cannot be changed once it has been initialized. This is useful for declaring constants or other values that should not be modified. Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is useful for methods that are part of a class's public API and should not be modified by subclasses. Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for classes that are intended to be used as is and should not be modified or extended. Initialization: Final variebles must be initialized either et the time of declaration or in the constructor of the class. This ensures that the value of the variable is set and cannot be changed. Performance: The use of final can sometimes improve performance, as the compiler can optimize the code more effectively when it knows that a variable or method cannot be changed Security: final can help improve security by preventing malicious code from modifying sensitive data or behavior. Static: The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same veriable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class. The static keyword is used for a constant variable or a method that is the same for every instance of a class. The static keyword is a non-access modifier in Java that is applicable for the following © Blocks Variables Methods Classes 8 How to access Static variable of Outer class from Static Inner class in java? Give example You can access the static variable of an outer class just using the class name. Following Java example demonstrates how to access static variables of a class from a static inner class. public class Outer { static class InnerDemo { static int data = 200; public void my_method() { System.out printin(‘This is my nested class"); System.out.printin(Outer.data); +} public static void main(String argsf) { Outer.InnerDemo nested = new Outer.innerDemo(); nested.my_method(); yo Output This is my nested class 200 9. Develop a computing solution, get input from user and also process the mark processing system (Record has the following fields: Name, Reg_no, Mark1, Mark2, Mark3, Marké, Total, average). Generate student information with total and average marks 10. Create a class Interest that implements @ simple program that will compute the amount of interest that is eamed on $17,000 invested at an interest rate of 0.07 for one year. The interest and the value of the investment after one year are printed to standard output 11. Consider the person "K" has some amount in his hand and the person "Y" has some amount in his hand. If they wish to exchange the amount among them, how they can exchange the amount by using the third party “Z" 12. A pizza in a circular shape with 8 inches and which is placed in a square box whose side length is 10 inches. Find how much of the box is “empty”? 13. Develop a java program te find the smallest number in the given array by creating one dimensional array using new operator. 14. Write a java program to print first ‘N’ Prime numbers 15. Define a class Point with two fields x and y each of type double. Also, define a method distance (Point p1, Point p2) to calculate the distance between points p1 and p2 and return the value in double. 16. Given an integes, n , perform the following conditional actions: If nis odd, print Weird If nis even and in the inclusive range of 2 to 5 , print Not Weird If nis even and in the inclusive range of 6 to 20, print Weird fn iseven and greater than 20 , print Not Weird 17. Consider the scenario of processing marks of a student John for a course as, part of a student management system. The assumption is that John takes exams in five different subjects. Find out the grade scored by John as per the table given below. Module Test MarksGrade >= 80A >=73 and < 80B+ >=65 and < 738 >=55 and < 65C <55D 18. Develop an application to generate Electricity bill. Read Consumer no., consumer name, previous month reading, current month reading, type of EB connection (,e domestic or commercial). Compute the bill amount using the following tariff. If the type of the EB connection is domestic, calculate the amount to be paid as follows First 100 units- Rs. 1 per unit 101-200 units - Rs. 2.50 per unit 201 -500 units - Rs. 4 per unit 501 and above units-Rs. 6 per unit If the type of the EB connection is commercial, calculate the amount to be paid as follows: First 100 units - Rs. 2 per unit 101-200 units - Rs. 4.50 per unit 201 -500 units - Rs. 6 per unit 501 and above units-Rs. 7 per unit 19. Write a Java program to reverse the given number. 20. Write a java program to multiply two matrices 21. Write a program to create interface method named customer .in this keep the methods called information(),show() and also maintain the tax rate .implement this interface in employee class and calculate the tax of the employee based on their income IncomeTax percentage MaleFemale >=190000 nil nil >=200000 10% nil >=500000 20% 10% <500000 25% 20% 22. Declare the class called employee _id and employee_name as members. Extend the class employee to have a subclass called salary having designation and monthly-salary as members. Define the following: a. Required Constructors b. Amethod to find and display all details of employees drawing salary more than 20000/- c. Methad main for creating an array for storing these details given as command line arguments and showing usage of above methods 23. Explain about Method overloading and method overriding in Java 24. Give example for Overloading by changing the number of parameters 25. How does Java implement or achieve inheritance? 26. Compare and contrast class, abstract class and interface. 27. Differentiate single inheritance and multilevel inheritance 28. How to create a package in Jave and What are the advantages of a java package? 29, Whatis a predefined package in Java? Give examples 30. When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy called? Outline with an example 31. Outline method overriding with an example. 32. Explain constructor overloading with example. 33. With suitable example, justify why multiple inheritance is not supported in Java using “extends”, 34. Demonstrate the use of abstract class with suitable example. 35. Make a class student, The student class has data members such as roll number, name, and branch. Create class called Exam that has data member six subject, marks. Derive the class result from exam and it has its own data members such as total marks and result. Write a java program to model this relation. 36. Write a Java program to create an interface Shape with the getArea() method. Create three classes Rectangle, Circle, and Triangle that implement the Shape interface. implement the getrea() method for each of the three classes. 37. Describe methods of creating a thread with example. Refer Slide no 13-17 38. Describe life cycle of thread with suitable diagram. 39. Write a program to define two threads for displaying even and odd numbers respectively with a delay of 500 ms after each number. import java.lang.Thread; class Odd extends Thread { public void run() 4 it for (inti = 1;i <20;iFi+2) { Thread.sleep(500); System. out printin(; bo} catch(Exception e)} y class Even extends Thread { public void run() ftry{ for (int i =O; i <20; i=i+2) { Thread sleep(500); System. out printin(i); % catch(Exception e)(} I public class HelloWorld{ public static void main(String [args}{ Odd o=new Odd(); Even e=new Even(); ostart(); e.stant(; % Output 10325 4769811 101312151417 161918 40. Enlist the advantages of Java Multithreading 41. Develop a Java program to perform the following tasks using two different threads. Each thread will be responsible for its own task only. Among these two threads one will find the average number of the input numbers and one will be responsible for finding the Maximum number from the input erray of numbers. import java.util*; class AverageNumber implements Runnable { intn; privateint(] num; double avg public AverageNumber(int{] num) { this.num = num; } public void run() { for(int i = 1: i < numllength-1; it) {n= nénumil avg = (double)n/i; } System. out printIn(Average Number is : "+avg) I class MaximumNumber implements Runnable { privateint{] number: public MaximumNumber(int{] number) {this number = number) public void run() {int largest = number(0]; for(int i=1; ic number.length; i+) { if(numberlil > largest) largest= numberli]; } System.out.printin(‘Largest Number is : * + largest); w public class Main { public static void main(String [J args) { Scanner s=new Scanner(System.in); int{] numarr = new int[6: for(int i=0; i<5; i++) {numarr[i] = s.nextint(} Runnable hello = new AverageNumber(numar; Thread thread = new Thread(hello); thread! start); Runnable bye = new MeximumNumber(numari); Thread thread2 = new Threadbye); thread? start); y Output 5 6 Largest Number is : 6 Average Number is : 4.5 42. For the following program, what will be output after its execution? public class Main(){ public static void main(String args() ( Thread thread=Thread.currentT hread() System.out.printin(thread.activeCount())} 43. The following is a simple program using the concept of thread. public class Questions extends Thread {public void run0) {for(int i=1;i<5;++) {System out printin(i++))} public static void main(String args() {Question tl=new Question(); t1.run()} What is the output of the above program?

You might also like