Page 1 :
Chapter 1: Concept of Objects, A. Choose the correct answer:, , 1. An object is represented by two attributes, out of which one is characteristics and the other one is _., a) Behaviour, b) Situation, c) Abstraction, d) Encapsulation, Ans. a) Behaviour, 2. Name the programming technique that implements programs as an organized collection of interactive objects., a) Procedural Programming, b) Modular Programming, c) Object-Oriented Programming, d) None of these, Ans. c) Object-Oriented Programming, 3. Name the characteristics of Object-Oriented Programming that hides the complexity and provides a simple, interface., a) Encapsulation, b) Polymorphism, c) Abstraction, d) Inheritance, Ans. c) Abstraction, 4. What is the behaviour aspect of an object represented by?, a) Functions, b) Data Members, c) Both a and b, d) None of these, Ans. a) Functions, 5. What is the ability of an object to have many methods which functions differently but have the same name?, a) Polymorphism, b) Encapsulation, c) Abstraction, d) Inheritance, Ans. a) Polymorphism, 6. Name the object-oriented technique that encompasses the parent class state and behaviours into its child., a) Polymorphism, b) Encapsulation, c) Abstraction, d) Inheritance, Ans. d)Inheritance, 7. Name the art of implementing encapsulation in Object-Oriented Programming., a) Polymorphism, b) Encapsulation, c) Abstraction, d) Class, Ans. d)class, 8. What is meant by state of an object?, a) Functions of the object, b) Data members of the object, c) Content of an object, d) All of these, Ans. c) Content of an object, 9. Name the term used to express the ability of objects to interact with each other., a) Message Passing b) Instantiation, c) Logical construct, d) All of these, Ans. a) Message Passing, B. Fill in the blanks:, 1. An object is an identity with certain characteristics and behaviour., 2. The values/attributes of the characteristics of an object are called the state of an object., 3. All the complexities of a program should be hidden in such a way that abstraction is obtained., 4. Class is a mechanism to implement encapsulation., 5. Objects interact with each other with the help of Message Passing., 6. A huge program divided into several individual segments is called functions/methods., 7. The objects methods/functions are said to access data., 8. A class is a logical construct and an object is a physical reality., 9. All objects have identity and are distinguishable even if the constituent components are same., Answer the following questions:, 1. Give two examples of real-world objects. Also specify their characteristics and behaviour., Ans. Real Life Objects, Example1:, Object Name: Pen, Characteristics: Company made, Colour, Body Shape and Nip. Behaviour:, , 1) Used for writing., 2) Used for correction, 3) Used for drawing or sketching
Page 2 :
Example 2:, Object Name: Dog, Characteristics: Name, Colour and Breed. Behaviour:, , 1) Barking, 2) Wagging its tail, 3) Running speed, 2. What do you understand by state of an object? Explain with an example., Ans. State of an object refers to the condition in which an object is in. Thus the values/attributes of its characteristics is, represented For example, a book is an object, which may be either in “open” or “closed” state, similarly a bulb may be in, switched on or switched off state., 3. How are objects implemented in Software?, Ans. Every object in real life has certain characteristics and behavior. It is the characteristic that is represented by data, variables and behaviour by methods or functions encapsulated in a class using software., 4. What is abstraction? How is encapsulation related to it?, Ans. Abstraction is the process of hiding the complexity and giving a simple interface and encapsulation is the process of, implementing abstraction., Using encapsulation, the data and the code is wrapped round inside a class., 5. Define encapsulation., Ans. Encapsulation is the process of wrapping/combining the characteristics and behavior into a single unit of an object to form, a unique identity., 6. Explain the term object using an example., 7. Ans. An object is an entity with certain characteristics and behaviour making it having its own individuality and, distinguishable. For example a pen has certain characteristics, for example its colour, shape, size, etc. and behaviour which is, used to write, sketch or draw, etc. Even though two pens are identical with the same colour, texture, shape and size, yet they, are two distinguishable pens., 8. What is a class?, Ans. A class is a method to implement encapsulation is programming. It is the class keyword in Java that is used to wrap, around the data members and member methods into a single unit. It acts as a template that allows instances of it to be, created, which are called objects., 9. What is Message Passing?, Ans. When the objects need to interact with one another, they pass or request information to or from one another. This, interaction is knows as message passing., 10. What is Object-Oriented Programming?, Ans. Object Oriented Programming is a technique of implementing programs which are organized as a co-interactive, collection of objects, each of which represents an instance of a class., 11. State the 4 characteristics/principles of Object-Oriented Programming., Ans. The 4 characteristics/principles of Object Oriented Programming are:, , i), ii), iii), iv), , Abstraction, Encapsulation, Polymorphism, Inheritance, 11. Explain briefly:, a) Abstraction, b) Inheritance, c) Polymorphism, Ans. a) Abstraction: Abstraction refers to the art of hiding the complexities and giving a simple interface. For example in a car,, for a layman, it is good enough to know driving. Hardly will he know the intricacies of movement of the engine, the, working of the electrical and electronic components; what he will know or will be interested with is the steering for turning, the, accelerator for speed and the switches. This is because he has been given a simple interface and the complexity of the car engine, movement has been kept completely hidden from him. Thus he doesn’t bother about the intricacies of the car’s engine, movement, but concentrates only on driving., b) Inheritance: Inheritance is the ability to inherit characteristics from another object. In more concrete terms, an object is able, to pass on its state and behaviours to its children. For inheritance to work, the objects need to have characteristics in common, with each other. It is basically a term that is used to represent hierarchical relationship of generalization., c) Polymorphism: The term Polymorphism is actually a combination of two terms
Page 3 :
Poly and Morphism. Here the term Poly means many and Morphism means forms. It is the ability of objects to have many, methods of the same name, but each one responds to different types of specific behaviour as they have different forms., 12. How does class acts as a blueprint for an object?, Ans. A class acts as a blueprint or template that defines certain characteristics and behaviour and an object is an instance or, copy of a class., 13. How does encapsulation acts as a protective layer for an object?, Ans. Encapsulation is a technique that binds together function and the data into a single unit. You can imagine it to be as a, protective wrapper that prevents the code and data from being accessed by other codes defined outside the wrapper., 14. How does modularity helps in reducing the c o m p l e x i t y o f a p r o g r a m ?, Ans. Modularity helps in breaking a huge task into smaller units called functions for easy maintainability and reusability, thus reducing the complexity of the task at large., 15. What do you understand by data abstraction? Explain with an example., 16. Ans. Data abstraction refers to, providing only essential information to the outside world and hiding their background, details, i.e., to represent the needed information in program without presenting the data., Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external, components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it, receives signals over the air or through a cable, how it translates them, and finally displays them on the screen., 17. Give a real world explanation about abstraction., Ans. A switch board is an example of abstraction. Imagine if the concept of switchboard did not exist. You would find a great, number of wires hanging round your room. To start with an appliance, you needed to join two wires. But essentially you need, to know which group of wires should be joined to start an appliance. Moreover, more the number of wires, more will it be, confusing to identify the wires to start an appliance. Thus joining of wires is not only confusing but may also prove fatal as far, as safety is concerned. Thus, the electrician installs a switchboard that connects each of the wires to a switch., Hence, it is just enough to know for the user to switch on that switch that starts an appliance., 18. Why abstraction often is referred to be as relative?, Ans. Abstraction is often referred to as relative because abstraction is the selective examination of certain aspects of a, problem. The goal of abstraction is to isolate those aspects that are important for some purpose and suppress or hide those, aspects that are unimportant. Abstraction must always be for some purpose, because the purpose determines what is, important and what is not. Many different abstractions of the same thing are possible, depending on the purpose for which, they are made., , Chapter 2: Java Terminology, A. Choose the correct answer:, , 1. What was Java initially called?, a) Oak, b) C, c) C++, d) None of these, Ans. a) Oak, 2. What is Java Programming Language?, a) A run-time system, b) A set of development tools, c) An Application Programming Interface (API), d) All of these, Ans. d)All of these, 3. Name the process that converts source code to byte code., a) Interpretation, b) Compilation, c) Both a and b, d) None of these, Ans. b) Compilation, 4. A Virtual Processor that is implemented in software and runs using the capabilities provided by your operating system and, computer hardware., a) Byte Code, b) Compiler, c) Interpreter, d) Java Virtual Machine (JVM), Ans. d) Java Virtual Machine (JVM), 5. Name the hardware or software environment in which a program executes., a) Operating System, b) Platform, c) Software, d) Program, Ans. b) Platform, 6. Name the programs that can be developed in such a way that it remains embedded in a web page and runs on the viewer’s, machine in a secured manner by Java-compatible browsers., a) Applets, b) Applications, c) Servlets, d) Enterprise Java Beans (EJB)
Page 4 :
Ans. a) Applets, 7. Name the Application program that is written and compiled which may then be executed in any machine provided it, contains the JVM., a) Applets, b) Applications, c) Servlets, d) Enterprise Java Beans (EJB), Ans. b) Applications, 8. What is the type of Java program that allows development and deployment of transactional, distributed object, application-based, server-side software components?, a) Applets, b) Applications, c) Servlets, d) Enterprise Java Beans (EJB), Ans. d) Enterprise Java Beans (EJB), 9. Choose from among the following which is not the characteristics of a Java program., a) It is platform-independent., b) It helps in developing any kind of applications., c) It does not support interactive content on web pages., d) It is ideal to make Distributed networking applications., Ans. c) It does not support interactive content on web pages., 10. What is a set of pseudo-machine language instructions that are understood by the Java Virtual Machine and are, independent of the underlying hardware called?, a) JVM, Ans. d) Bytecode, , b) Source Code, , c) Compilation, , d) Bytecode, , B. Fill in the blanks:, , 1. Java made Web interesting as it makes it Interactive, 2. Java was formerly known as Oak., 3. Bytecode is a set of pseudo-machine language instructions that are understood by the JVM., 4. Java’s portability can be attributed to Run-time system and its API., 5. Java programs are Interpreted by the JVM., 6. A Platform is the hardware/software environment in which a program remains., 7. Applets are small programs that remain embedded in a web page and runs on the viewer’s machine in a secured manner., , Answer the following questions:, 1. What is the significance of WWW?, , Ans. WWW or World Wide Web allows a huge pool of information (as web pages) to shared by multiple users over a World, Wide Network (Internet) and the introduction of Java makes the web pages dynamic and interactive in a secured manner., , 2. What is Browsing?, , Ans. Browsing over the internet allows surfing through the internet, thus enabling the users to see information in different pages, and interact with it., , 3. Name two types of Java programs., , Ans. The two types of Java programs are Applications and Applets., , 4. Why is Java choice for the Web?, , Ans. The introduction of active web pages makes Java an attractive addition to the web page. When we click on a web page, containing a Java applet, it is not that we just read it, listen to it, or watch it– we can interact with it. The dynamic, interactive, content to the web was brought about by Java: So much so web applications made in Java runs as if it is a computer program, installed in the local computer., , 5. What is Java API?, , Ans. An application programming interface (API), in the context of Java, is a collection of prewritten packages and classes. Similar, to a user interface, which facilitates interaction between humans and computers, an API serves as a software program interface, facilitating interaction., , In Java, most basic programming tasks are performed by the API’s classes and packages, which are helpful in, minimizing the number of lines written within pieces of code., 6. Define the term Bytecode., Ans. Bytecode is a set of pseudo-machine language instructions that are understood and executed by the Java Virtual, Machine and are independent of the underlying hardware., 7. What is JVM? Explain its relationship with bytecode., Ans. The Java Virtual Machine (JVM) is a microprocessor that is implemented in software and runs using the, capabilities provided by your operating system and computer hardware. Since the Java virtual machine is not a real, microprocessor, the Java bytecode is interpreted, rather than executed, directly in the native machine instructions of
Page 5 :
the host computer., , Chapter 3: The BlueJ Environment, A. Choose the correct answer:, , 1. Which of the following is an IDE?, a) NetBeans, b) BlueJ, c) Eclipse, d) All of these, Ans. d) All of these, 2. Name the tool that is in-built in the BlueJ environment that allows you to instantly evaluate arbitrary Java expressions, and statements., a) Class, b) Objects, c) Code Pad, d) All of these, Ans. c) Code Pad, 3. The Show Code Pad option is present in the, menu of the BlueJ IDE., a) Project, b) Edit, c) Tools, d) View, Ans. d) View, 4. What is the name of the window on which the output as displayed by System.out.println( ) received?, a) Terminal Window, b) Main Window, c) Editor Window, d) Object Bench, Ans. a) Terminal Window, 5. On which menu of the Terminal Window is the option to Clear screen at method call?, a) Option, b) Edit, c) Project, d) None of these, Ans. a) Option, 6. Which of the following is not a feature of BlueJ?, a) The concept of class and objects are presented in graphical manner., b) BlueJ interface is much simpler compared to contemporary IDEs like NetBeans and Eclipse., c) Objects are graphically shown on the Terminal Window., d) Code Pad allows to evaluate arbitrary Java expressions and statements., Ans. c) Objects are graphically shown on the Terminal Window., 7. What is the joining of data term in Java called?, a) Conjunction, b) AND, c) Concatenation, d) None of these, Ans. c) Concatenation, 8. What is the name of the text file that is automatically created containing a short description about your project, or may, contain specifications regarding your project?, a) AboutMe.Txt, b) Readme.Txt, c) AboutZUs.Txt, d) All of these, Ans. b) README.TXT, , B. State whether True or False:, , 1. IDE stands for Integrated Development Environment., 2. The class icon showing stripes indicates that the class is yet to be compiled., 3. The quick key combination for compilation is Ctrl + L., 4. The Terminal Window shows the output of a BlueJ program., 5. The operator + may be used to join two strings., 6. Creating a project actually forces you to organize the files in BlueJ into a folder., , C. Fill in the blanks:, , [True], [True], [False], [True], [True], [True], , 1. Bluej is an IDE that was designed in such a way that it supports the learning and teaching of object-oriented programming., 2. The Code Pad is a tool that instantly evaluates arbitrary Java expressions and statements., 3. BlueJ Projects are directories or folders containing the files that you create., 4. When you create a project a file named README.TXT is automatically created that allows you to write all relevant, documents related to a BlueJ project., 5. A compiled source code creates a bytecode file recognised by the JVM having the extension, .class., , A. Answer the following questions:, , 1. What is BlueJ? Where was it developed?, Ans. BlueJ is a popular IDE which is equipped with tools that support the learning and teaching of object-oriented, programming. BlueJ was designed in such a way that it supports the learning and teaching of object-oriented
Page 6 :
programming thus making its design different from other development environments (like NetBeans/Eclipse) as a result., BlueJ was developed in the year 1999 by Machael Kolling and Professor John Rosenberg at Monash University in, Melbourne., 2. How do you start BlueJ in Windows Operating System?, Ans. BlueJ can be started either from the desktop or from the Start Menu. From the Desktop doubleclick on the BlueJ icon., From the Start menu follow these steps:, 1. Click on the Start button on the Taskbar., 2. From the Start Menu click on All Programs., 3. From the menu list that appears click on the BlueJ folder and then click on BlueJ icon., 3. What is an IDE? State its advantages., Ans. An IDE stands for Integrated Development Environment. It is a software that has a built-in text editor, with tools for, compilation, execution and testing. Its advantages are:, • Write and edit source code, • See errors as you type, • See highlighted code syntax in different colours, • Automate repetitive tasks, • Compile the source code (program), • Browse class structures, • View JavaDocs, • Use drag-and-drop utilities for easy building of features, such as graphic objects or creating database connections, 4. Why is BlueJ used to teach Java in schools and colleges?, Ans. BlueJ is used to teach Java in schools and colleges because of the following features:, , a) Representation of class and objects is done in a graphical manner., b) The simplicity of the interface makes it easy to use for first time users., c) The Object Bench that allows object interaction explains the concept of classes and objects in a graphical, manner., The Code Pad allows you to instantly evaluate arbitrary Java expressions and statements., 5. State 2 advantages of using BlueJ?, 6. Ans. Two advantages of BlueJ are:, a) There is no need for a main( ) method for execution of a Java code., b) Testing of methods can be performed interactively., 7. What is Code Pad?, Ans. Code Pad is used to quickly and easily evaluate an arbitrary snippet of Java expression., 8. How do you start coding in BlueJ?, Ans. To start coding using BlueJ, you need to create a Project and start with a new class to start coding into it. Once, the class icon is displayed you may double click on it to start coding, 9. What is the significance of README file?, Ans. The README file is used to write all relevant documents related to the project. It is simply a text file containing, a short description about your project, or may contain specifications regarding your project., 10. How do you create a class in BlueJ?, Ans. To create a class in BlueJ click on the New Class… button on the main project window, which in turn displays, the Create New Class dialog, where you can assign a name for the class., 11. How do you start the editor in BlueJ?, Ans. To start the editor in BlueJ, you just need to double click on the class icon or right click on the class icon and, click on Open Editor option from the pop-up menu., 12. How do you remove the default code generated when a class is created in BlueJ?, Ans. To remove the default code, you may use your mouse by click and drag to select the entire code or press Ctrl+A, to select the entire code and press the Delete key., 13. How do you compile a program in BlueJ?, Ans. To compile a Java source code simply click on the Compile button on the editor window or use the keyboard, combination Ctrl+K., 14. What is the difference between System.out.print and System.out.println?
Page 7 :
Ans. System.out.print() displays or outputs a data item but keeps the cursor in the same line, hence the next output, continues to be in the same line. System.out.println() on the other hand display the data item and brings the cursor to, the next line, hence the next output is displayed in the next line following the previous output., 15. What is a Terminal Window? How do you automatically clear the Terminal Window screen with every, method call?, Ans. The Terminal Window is a window that acts as a console for output of a Java program, when using, System.out.print( ) or System.out.println( ) statements., To automatically clear the Terminal window with every method call use the following in the Terminal Window:, a) Click on the Options menu., b) Click on Clear screen at method call option from the menu., 16. What is concatenation?, Ans. Joining of two strings or data items is termed as concatenation., 17. What happens when all the data items are numeric and + is used in the System.out.print statement?, , Ans. When all data items are numeric and + is used in the System.out.println() statement, it gets evaluated, i.e., it, gets added., 18. How do you print different numeric data items in the same System.out.print statement without getting it, evaluated?, Ans. This is done by concatenating a blank string in the middle. For example, System.out.println(5 + “ ”+ 6);, Will give the output as: 5 6, 19. How do you compile and execute a program using Sun’s Java compiler? Ans. To compile a java source code, javac file for compilation and for execution use the java file., 20. Which method is necessary to execute a Java program in Java run-time environment?, Ans. The method that is necessary to execute a Java program in Java run-time environment is, public static void main(String args[])., 21. Why is BlueJ environment considered better for coding programs than conventional Java, programming?, Ans. The BlueJ environment is considered better for coding programs than conventional Java programming because:, a) There is no need for a main method., b) Testing can be performed interactively., c) It allows the complexity of input to be deferred., d), It encourages object-oriented thinking and programming., 16. State the characteristics of Java., Ans. Characteristics of Java:, a), Write Once Run Anywhere (WORA), b), Ligt Weight Code, c), Security, d), Built-in Graphics, e), Object Oriented Language, f), Supports Multimedia, g), Platform Independent, h), Open Product, , Chapter 4: Java Fundamentals, Fill in the blanks:, 1., 2., 3., 4., 5., 6., 7., , Java uses Unicode character set., Unicode is a two bytes character set., Character Set is a set of valid characters that a language can recognize., The smallest individual unit in a program is a token., Identifiers are fundamental building blocks that give names to different parts of a program., Escape sequences/Non graphic characters are characters that cannot be typed directly from the keyboard., Variables represent named storage locations whose values can be manipulated during program execution., , 8. Operators that act upon two operands are referred to as Binary operators., 9. The process of converting one predefined type into another is called Type Conversion., 10. The new operator is used to allocate memory for objects and arrays.
Page 8 :
Answer the following questions:, , 1. What is Character Set?, Ans. Character set is a collection of all the characters that can be used in a Java program. A character represents any letter, (whether capital or small), digits (0 to 9) or any symbol (%, &, ^, @, $, |, etc)., 2. What is bytecode?, Ans. Bytecode is an intermediate language which is received upon compilation of source code and interpreted by the JVM (Java, Virtual Machine)., 3. What is indentation in a Java program?, Ans. Indentations are whitespaces that are given by programmers to increase the readability of a source code., 4. What are keywords?, Ans. Keywords are reserved words in Java and thus provide a special meaning to the Java compiler., 5. What are Identifiers? State the rules while using Identifiers., Ans. Identifiers are the names given to different parts or elements of a program to identify it. The rules that you, should keep in mind to use identifiers are:, , a) It can have any alphabet (capital or small), digits, underscore and dollar sign characters., b) It should not begin with digits or should not contain any special character., c) It cannot have a space in between., d) It must not be a keyword., e) It can be of any length., f) Since Java is case-sensitive, it treats capital (upper-case) and small (lower-case), characters differently., 6. What is a literal? What are the different types of literals available in Java?, Ans. Literals are tokens that are used to represent constants that may be assigned to a variable., , Integer literal or Fixed point literal, Floating point literal, Boolean literal, Character literal, String literal, Null literal and Class, literal are the literals that are used in Java., , 7. State the difference between a Boolean literal and a character literal., , Ans. A character literal is used to enclose a character within single quotes and boolean literal refer to two states i.e. true (to, represent success) and false (to represent failure)., , 8. What are the escape sequences available in Java?, Ans. The escape sequences available in Java are:, Escape Sequences, '\b', '\f', '\n', '\r', '\t', '\', "\", '\\', '\0n', '\xHn', , Meaning, Backspace, Form feed, New line, Carriage return, Horizontal Tab, Single quote, Double quote, Backslash, Octal number, where n is the number, Hexadecimal number, where n is the number, Unicode character represented through its hexadecimal code n, , '\uHn', 9. What are the different punctuators available in Java?, Ans. There are 9 punctuators available in Java. They are: ( ) { } [ ]; ,, 10. What are Tokens?, , Ans. Token is the smallest fundamental unit in a program. They are the valid characters or symbols that can be used in a Java, program., , 11. State the difference between token and identifier., , Ans. Token is the smallest fundamental unit in a program, whereas identifier is a token which is used to give names to different, parts or elements of a program to identify it., , 12. State the two kinds of data types., Ans. The two data types are:, a) Fundamental Data Type
Page 9 :
b), Composite Data Type, 13. State the size of integer data types in Java., Ans. The size of integer data types are:, a) byte, – 8 bits, b) short, – 16 bits, c) int, – 32 bits, d) long, – 64 bits, 14. How are floating point numbers represented in Java?, , Ans. Floating point numbers are used to represent fractional numbers (with decimal point). Java, provides two ways of representing fractional numbers viz. float and double. Float type numbers are suffixed with F or f and, double type numbers are suffixed with D or d, however suffixing with D or d for double data type is optional., , 15. What are variables? How are variables initialized?, , Ans. Variable is a name given to memory location where data is stored or needs to be stored. The general format of variable, declaration is as follows:, , <data-type><variable-name>;, , For initialization of variables use the general syntax :, , <data-type> <variable-name>=<constant>;, , 16. How are symbolic constants represented in Java?, , Ans. Symbolic constants are represented with the final keyword before a variable declaration: For example, final int, MAX=100; declares a symbolic constant MAX with the constant value 100., , 17. How are negative numbers represented in Java?, , Ans. Negative numbers are represented in Java with the – (minus) sign preceding the number. Example -34, -24.34, etc., , 18. Differentiate between operator and expression., , Ans. An operator is a symbol or command that is used to perform a particular task like evaluating an expression. Expression, on the other hand is a combination of an operand and operators that evaluates to a value., , 19. Explain the term typecasting., , Ans. Typecasting is the process of converting the resultant data type of an expression from one data type to another., , 20. State the difference between Unary and Binary Operators?, , Ans. Unary operators are mathematical operators that works on a single operand (eg. –b, ++c ) whereas binary operators are, mathematical operators that works on two operands (eg. a+b, c*d)., 21. What is meant by precedence of operators?, Ans. Precedence of operators refers to the order in which a mathematical expression with multiple mathematical operators, gets evaluated., , 22. What are relational operators?, , Ans. Relational Operators are used to define a conditional expression., , 23. What is a compound statement? Give an example., , Ans. The group of statements within a block is referred to as a compound statement., For example,, {, int a=5, b=6; System.out.println(a+ “ ”+b);, }, 24. What are the different logical operators available in Java?, Ans. The different logical operators available in Java are AND( &&), OR (||) and NOT (!)., 25. State the difference between Shift-right (>>) and Shift-right-zero-fill (>>>) operators., Ans. Shift right( >>) operator is used to shift bits towards the right and the vacant places after shifting is filled up with 0 if the, number is positive and 1 if the number is negative to thus retaining the sign after shifting., Shift-right-zero-fill shift bits towards the right and the vacant places after shifting is filled up with 0. Thus the number, always results to a positive number., 26. What is type conversion? Under what circumstances is there a "Loss of Information"?, Ans. The process of converting implicitly or explicitly one data type into another compatible data type is termed as type, conversion., In case a variable or constant of higher size is assigned to a variable of smaller size, it results in, , possible loss of precision error., 27. What are comments? What are the different types of comments that may be used in a Java program?, , Ans. Comments are notes in a program to provide an easy understanding of the problem. This ensures proper documentation.
Page 10 :
But these statements are ignored by the compiler and no question of error may occur within this, whatsoever you may write, within it. There are three types of statements available in Java, viz. Single-line Comment, Multiline Comment and, Documentation Comment., 28. What is the purpose of new operator?, Ans. The new operator is used to allocate memory for objects and arrays., 29. What is a null statement?, Ans. Statement which has only a semicolon is termed as null statement. These statements are generally used where syntaxes of, certain commands require a statement whereas the programmer may not want to give it. In that case to abide by the syntax of, the command the null statement is used., 30. What is a compound statement?, Ans. The group of statements within a block is referred to as a compound statement., For example,, {, int a=5, b=6; System.out.println(a+ “ ”+b);, }, , 31. What do you understand by type conversion?, , Ans. Converting explicitly using type-casting the resultant of a mathematical expression from one data type to another is, termed as type conversion., 32. State the importance of a "class"., Ans. The class acts as a skeleton for an object. The classes are the bases of an object. It is a template upon which an object is, built. The class is the mechanism that is used to create objects., , 33. Why is Java called a strongly typed language?, , Ans. Java is a strongly-typed or statically-typed language in the sense that every variable has a type, every expression has a, type and every type is strictly defined. Also all assignments, whether explicit or via parameters passing in method calls, are, checked for type compatibility., , 34. How do you declare objects?, , Ans. Objects are declared using the new command using the following syntax:, <Class-name> <object-name>= new <Class-name>();, , 35. State one difference between the floating point literals float and double., Ans. The float data type is of size 32 bits, whereas double data type is of 64 bits., , Chapter 6: Conditional Structures, Answer the following questions:, , 1. What are conditional statements? With which commands do you implement conditional statement in Java?, Ans. Conditional Statements are those statements which contains a test-expression which may either result to true or false., Depending upon the result a statement or groups of statements are executed.It is implemented through if-else, if-else if-, , else, switch-case or using ternary operator (?:)., 2. When are braces optional or necessary in conditional statements?, , Ans. When there is only one statement to be executed if the result of a test-expression is true or, , false, giving braces is optional., 3. What are relational operators?, Ans. Relational operators are used for comparison between two data items or quantities that are used in a test-expression/, condition., , 4. State the difference between = and = =., Ans. ‘=’ is used to assign a value to a variable, whereas ‘==’ is used for comparison of two values for equality., 5. What are logical operators? Explain each of them with the help of an example., Ans. Logical operators are used when there are more than one relational expression needs to evaluated. It is, categorised as AND(&&), OR(||) and NOT(!).
Page 11 :
6. What is the function of nested if statement?, Ans. An if-else construct within an if or else construct or both is called nested if-else construct., 7. What is a conditional operator? Explain with the help of an example., Ans. The Ternary operator is an alternative to if-else statement for a concise clean and compact code., For example:, if(a>10), b=10;, else, b=15;, using conditional operator may be written as: b=(a>10)? 10:15;, 8. Compare if and ? :, Ans., , 9. What is the function of switch statement?, Ans. Using if statements to control the selection is perfectly okay for small programs but it becomes more complex when the, number of alternative increases makes the code look more and more complex, at times may even confuse the programmer., Using switch statement, it is possible to successively tests the value of an expression against a list of integer or character, constants as found in the case statement and when a match is found, a block of statements associated with that case gets, executed., 10. State the rules which are to be followed while using switch statement., Ans. Rules for switch-case statements are:, a) A case statement cannot exist by itself outside of a switch block., b) The break statement should appear as the last statement in a case block., c) Braces should be used to denote the start and end of the switch block., d) Only character constants and Integer constants are used in the case constants but allows only for, equality comparisons., e) All case labels in the same switch block may have unique values., 11. Differentiate between if and switch statements., Ans.
Page 12 :
Chapter 7: Repetitive Structures, A. Answer the following questions:, , 1. Explain the term loop with an example., Ans. Loop is a repetitive structure that allows a group of statements to be executed repeatedly. The loop, structure executes as long as the given test-expression is executed., , For example, the following for loop will execute 10 times displaying the first 10 natural numbers., , int i;, for( i =1 ; i<=10 ; i++), {, System.out.print(i+" ");, }, The loop starts with the initial value of 1 for ‘i' and iterates every time increasing the value of ‘i' by 1 as long as the value of ‘i’ is, less than or equal to 10. The loop body in the mean while displays each value of ‘i’ , thus giving the output as:, 1, , 2, , 3, , 4, , 5, , 6, , 7, , 8, , 9, , 10, , 2. Discuss "Elements That Control a Loop"., Ans. Elements that control the loop are:, 1. Initialization Expression(s): Before entering a loop, the variable that controls the execution of it, is called initialization. The initialization of a variable may be inside a loop or outside it. Whatever it, may be it is executed only once before the iteration starts., 2. Test Expression. The test-expression is a condition, which decides whether the loop body will be, executed or not. Till the test-expression evaluates to true, the loop body gets executed otherwise, the loop is terminated., 3. Update Expression(s). The update expression(s) change the value(s) of the control, variable(s). The update expression(s) is usually made to be executed; before the next iteration., 4. The Body of the Loop. The statements that are executed repeatedly (as long as the, testexpression is true) form the body of the loop., 3. What are the three types of looping statements available in Java?, Ans. The three types of looping statements in Java are:, a) for, b) while, c) do-while, 4. Classify loops depending upon the priority in which a test expression is evaluated., Ans. Depending upon the priority of a test-expression loops may be categorized as:, a) Entry-controlled loop, b) Exit-controlled loop, 5. Give the general syntax of a for loop and discuss each of its components., Ans. The general syntax of for loop is:
Page 13 :
for (initialization expression(s) ; test-expression ; update expression(s)), {, //body of the loop;, }, , o Initialization Expression(s): Before entering a loop, the variable that controls the execution, of it is called initialization., o Test Expression. The test-expression is a condition, which decides whether the loop body will, be executed or not., o Update Expression(s). The update expression(s) change the value(s) of the control variable(s)., The update expression(s) is usually made to be executed; before the next iteration., o The Body of the Loop. The statements that are executed repeatedly (as long as the, testexpression is true) form the body of the loop., , 6. Give an example to show how multiple initialization and updation are performed in a for loop., , Ans. For multiple initialization and multiple updation in a for loop they are separated by comma (,). The following example, shows how multiple initialization and updation is performed in a for loop., for(i=1, j=10 ; i<=10 ; j-- , i++), {, System.out.println("i=" +i+" "+"j="+j);, }, , 7. What is an empty for loop. Give an example., Ans. If the loop doesn’t contain a body, it is called an empty loop. For example, for(i=1;i<=100;i++);, Notice the semicolon at the end of the parenthesis, indicating that the for loop does not have body and therefore no, statement is repeatedly executed again and again., , 8. State one similarity and one difference between while and do-while loops., Ans. Similarity: The similarity between while and do-while loop is that, both the loops executes as long as, the given test-expression is satisfied., Difference: The difference between while and do-while loop is that, while is an, entry-controlled loop and do-while loop is an exit-controlled loop., 9. State one similarity and one difference between while and for loops., Ans. Similarity: The similarity between while and for loop is that, both the loops are entry-controlled, loops.., Difference: The difference between while and for loop is that, initialization in while loop is outside the, loop structure, whereas initialization of for loop is within the loop structure., 10. What is meant by an infinite loop? Give one example., 11. Ans. Infinite loop is a loop which executes indefinitely i.e. the given test-expression is forever evaluated, to true. For example,, for(i=1;i>0;i++), {, System.out.println(i);, }, The loop executes infinitely because the value of ‘i' is always greater than 0.
Page 14 :
12. Give the general syntax of a while loop. How do you create infinite loops using a while loop structure?, Ans. The general syntax of while loop is:, while (condition or test-expression), {, //body of the loop;, }, The easiest way of creating an infinite loop using while loop is: while(true), {, //body of the loop, }, , 13. Give the general syntax of a do-while loop. How do you create infinite loops using do-while loop, structure?, , Ans. The general syntax of do-while loop is:, do, {, , //body of the loop;, } while (condition or test-expression), The easiest way of creating an infinite loop using while loop is: do, {, , //body of the loop, } while(true);, , 14. Compare loops according to its usage., , Ans. The for loop is appropriate when you know in advance how many times the loop will be executed i.e. the first and the, last limit is already known. The other two loops while and do-while loops are more suitable in situations when it is not known, in advance when the loop will terminate. The while should be preferred when you may not want to execute the body-of-theloop even once (in case the test-expression is false), and the do- while loop should be preferred when you’re sure you want to, execute the body-of-the- loop at least once., 15. What are nested loops? Give an example of a nested for loop to show its functionality., Ans. A loop within a loop is called a nested loop. The following example shows how nested for loop works:, for(i=1;i<=5;i++), {, for(j=1;j<=i;j++), {, System.out.print(j);, }, System.out.println( );, }, The output received for the above program fragment is: 1, 12, 123, 1234, 12345, , 16. Name two jump statements and their use., Ans. The two jump statements in Java are break and continue. Whereas break statement is used to exit, from the loop or switch block, the continue statement is used to skip the remaining statements in a loop, and force the next iteration., 17. Explain the meaning of break and continue statements., Ans. The break statement is used to exit from the loop or switch block, the continue statement is used to
Page 15 :
skip the remaining statements in a loop and force the next iteration., 18. Explain how break statement works in a nested loop. Also give an example to show how continue, , statement works in a nested loop., Ans. The break statement is used to exit from the nested loop in a nested loop of which it is a content., Example of continue statement: for(x=1;x<=2;x++), {, for(y=1; y<=4 ; y++), {, if(y==3), continue; System.out.println(x+" \t "+y);, }, System.out.println("x="+x);, }, The output for the above code fragment would be,, , 1, , 1, , 1, , 2, , 1, , 4, , x=1, 2, , 1, , 2, , 2, , 2, , 4, , x=2, As you can see whenever the value of y reaches 3 it skips the statements only within the inner loop but the execution of the, outer loop continues remaining same thus System.out.println("x="+x); do get executed as it is actually present only within, the outer loop., , 19. With the help of an example, determine the working of, i) labelled break and, ii) labelled continue., Ans. i) The following example shows the working of labeled break statement: int i,j;, outer: //label for the outer block for(i=1;i<=3;i++), {, , inner: //label for the inner block for(j=1;j<=5;j++), {, , if (j>3), break outer; System.out.println(i+"\t"+j);, , } //End of the inner block System.out.println(j);, }, The output would be, , 1, , 1
Page 16 :
1, , 2, , 1, , 3, , Here you can see that there are two blocks labeled (outer and inner). Notice that when the value of j>3 it exits from the block, labeled outer, which makes it ultimately come out of both the loops., ii)The following example shows the working of labeled break statement: int i,j;, outer:, for (i=0;i<10;i++), {, for(j=0;j<10;j++), {, , if (j>i){, }System.out.println( ); continue outer;, }, , }, , System.out.print(" " + (i*j));, , The output will be, 0, 01, 024, 0369, 0 4 8 12 16, 0 5 10 15 20 25, 0 6 12 18 24 30 36, 0 7 14 21 28 35 42 49, 0 8 16 24 32 40 48 56 64, 0 9 18 27 36 45 54 63 72 81, The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop, counting i., , 20. How does the return statement works as a jump statement?, Ans. The return statement is used to force an exit from the method or function. The following program shows the working of, return statement:, class ReturnDemo, {, static void exit() //called method, {, System.out.println("Before the return"); if (true), return;, System.out.println("This won’t execute");, }, static void test( ) //calling method
Page 17 :
{, exit( );, }, }, If the test( ) method is executed it gives the following output., Before the return, As you can see that, the final System.out.println( ) statement is not executed. As soon as return is executed, control passes, back to the caller function i.e. test( )., , Chapter 9: Methods, A. Fill in the blanks:, , 1. In Java functions are known as Methods., 2. Methods are contained in class., 3. The function name and the parameter list together is known as Function Signature., 4. The access specifier, return type and the function signature together is known as Function prototype., 5. The arguments of the function given in function prototype are called Formal Parameters., 6. The arguments of the function given in statement that calls the function are called Actual Parameters., 7. If a function does not return any value, the returning type in the function prototype will be, void., 8. When a function is called by Value, the values of actual parameters are copied into separate memory locations as, allocated by the formal parameters., 9. Impure functions use call by Reference., 10. One of the practical implementations of polymorphism is Method Overloading., B. Write function prototypes for the following:, 1. private access method sum which accepts three int type variables as parameters and return a float type., Ans. private float sum(int a, int b, int c), 2. default access method Length which accepts a String type variable as parameters and return an int type., Ans. int Length(String s), 3. public access method increment which accepts an object of Myclass type as parameters and do not return any value., Ans. public void increment(Myclass ob), 4. protected access method largest which accepts a float type, int type and double type data as parameters and have a, byte type as return type., Ans. protected byte largest(float a, int b, double c), 5. public access static method calculate which accepts a byte and int type data type as parameters and return float, type., Ans. public static float calculate(byte a, int b), 6. Write the function prototype for the function "sum" that takes an integer variable (x) as it argument and returns a value, of float data type., , Ans. float sum(int x), , 7. Write the prototype of a function which takes in 2 integers and 1 String arguments and returns a value which is either, ‘true’ or false’., , Ans. boolean function (int a, int b, String s), , A. Answer the following questions:, 1. What is a method?, Ans. Function or Method is a block of code containing executable lines of code that represents the behavioural aspect of an, object., 2. Write two advantages of using functions in a program., Ans. The Advantages of using functions are:, , a), , b), , Reduces Complexity: Breaking a large task into smaller tasks automatically reduces complexity,, thereby increasing the maintainability of the program., Reusability: Once a method is defined, it can be invoked again and again from different segments of
Page 18 :
a program thus reusing the method whenever required., 3. Explain the function of a return statement., , Ans. The return statement is used to return-back or exit from a function. It comes in two variants:, 1., return; It is generally used with function having void return-type and is used to explicitly force an exit, from the function., 2., return <value>; It is used with function which have to return a value to the place where it is called, from. Thus it is used with functions having return- type anything other than void. This statement not, only forces an exit from the function but also returns a value., 4. If a function contains several return statements, how many of them will be executed?, , Ans. If a function contains several return statements, only the first one which JVM comes across is executed. Thus, , forcing an exit from the function and therefore the remaining return statements are not executed., 5. Name the keyword that causes the control to transfer back to the method call., Ans. The keyword that causes the control to transfer back to the method call is –return., 6. What is the role of the keyword void in declaring functions?, , Ans. The void return-type of a function is used to ensure that a function do not return any value., 7. Classify functions depending upon the value it returns., Ans. Depending on the value that is returned by a function, it is classified as:, , a), b), c), , Computational Function, Manipulative Function, Procedural Function, , 8. Differentiate between Formal Parameter and Actual Parameter., Ans. The difference between Actual Parameters and Formal Parameters are:, , 9. State the difference between function prototype and function signature., Ans. The difference between function prototype and function signature are:, , Function Prototype, Function prototype refers to the, return- type, function-name and the, parameter-list., , Function Signature, Function signature on the other hand refers, to the parameter list, i.e. the data types that, comprise the parameter-list, the number of, variables and their order., , 10. How are functions called? How does it return a value?, Ans. A function may be called or executed in Java by simply writing the function name followed by the parameter-list within, parenthesis. For example, if a function prototype contains the following:, void totalSurfaceArea(float l, float b, float h); when calling the function it, should be specified as:, totalsurfaceArea(x,y,z);, where x, y and z are variables of float type and are assigned to l, b and h respectively., After a function computes a value, it can be returned to the place where it is invoked using the general syntax:, , return <value>;
Page 19 :
11. What is call by value?, , Ans. During call by value a copy of the actual parameters is made by the formal parameters and therefore any changes made, , to the formal parameters is not reflected by the actual parameters., 11. State the difference between Call by Value and Call by Reference., , Ans. The difference between Call by Value and Call by Reference is that:, , 12. How are the following passed?, i) Primitive types, ii) Reference types, , Ans. i) Call by Value, , ii)Call by Reference, 13. Classify functions which accepts objects as parameters., , Ans. i) Pure Functions, , ii)Impure Functions, 14. Define an impure function., Ans. Impure functions are such methods which change the state of an object., 15. Differentiate between pure and impure functions., Ans. Difference between Pure and Impure functions:, , 16. Explain function overloading with an example., , Ans. Multiple functions with the same name but different parameter list is termed as function overloading.When an, overloaded function is invoked, Java uses the type and/or number of arguments as its guide to determine which, version of the overloaded method to actually call., Example,, // Demonstrate method overloading. public class OverloadDemo, {, void test(), {, System.out.println("No parameters");, }, //Overload test for one integer parameter. void test(int a), {, , System.out.println("a:" + a);, }, //Overload test for two integer parameters. void test(int a, int b), {, System.out.println("a and b: " + a +" " + b);, }, //Overload test for a double parameter double test(double a), {
Page 20 :
System.out.println("double a: " + a ); return a*a;, }, static void call(), {, OverloadDemo ob=new OverloadDemo(); double result;, ob.test();, ob.test(5);, ob.test(7,9); result=ob.test(12.73);, System.out.println("Result of ob.test(12.73): "+result);, }, , }, 17. Which OOP principle implements function overloading?, Ans. The principle of Polymorphism is implemented using Function Overloading., 18. When there are multiple definitions with the same function name, what makes them different from each other? [ICSE, 2009], Ans. When there are multiple definitions with the same name, the parameter-list makes them different from each other., 19. What are the different access specifiers available in Java?, Ans. The different access specifiers in Java are: default, public, protected and private., 20. What is the function of main( ) method?, Ans. In conventional Java the main( ) function is from where the program execution begins and is therefore also called the, driver function. In BlueJ environment main() do not have any relevance at all it behaves exactly like any other function in, Java., 21. How are static methods of one class called by methods in other classes?, Ans. Methods which are static are called by other classes using the class name of which it is a content followed by the method, call statement. For example,, class Myclass, {, static void trial(), {, }, , }, , class Anyclass, {, , }, , static void call(), {, Myclass.trial();//static method of Myclass is invoked, }, , Chapter 10:Class, A. Answer the following questions:, 1. What is a class?, , Ans. The class defines the characteristics and behaviour that may implemented by the objects, which are instantiated. It is, actually the method of implementing encapsulation in Java., 2. Mention any two attributes required for class declaration., Ans. Method name and class name, 3. Why is a class called an object factory?, , Ans. Factory in general refers to the process of generating some kind of products meant for it. A class is a blueprint of an object and therefore produces objects when instantiated. The characteristics and behaviour defined by, the class is reflected in each and every object that it instantiates. That is why a class is called an object factory., 4. Define Instance Variable. Give an example of the same.
Page 21 :
Ans. Instance variables refers to the data members declared within a class, that represents the characteristics of an, object. Each instance variable declared within a class becomes a part of an object that it instantiates. For example,, class Myclass, {, int a,b; //Instance Variable static void main( ), {, Myclass ob1=new Myclass(); Myclass ob2=new Myclass();, ob1.a=5;ob1.b=6; ob2.a=7;ob2.b=8;, }, }, In the main( ) function, there are two objects that are instantiated ob1 and ob2. Each object i.e. ob1 will have a set, of instance variable a and b (which are assigned 5 and 6 respectively) similarly ob2 will have another set of instance, variable a and b (which are assigned 7 and 8 respectively)., 5. What does the following mean?, Employee staff = new Employee( );, Ans. An object named staff is being allocated memory using the new command of the Employee class., 6. What is the use of the keyword this?, Ans. This keyword is used within a member function that acts as a reference to the current object., 7. What is a composite data type? In this respect also explain why a class is called composite data type?, Ans. Composite data type refers to a data type that is composed of multiple predefined discrete data types. The class acts as a, composite data type as it may contain data members that are composed of varied data types kept as a single unit., 8. How do you declare objects? Show with the help of an example., Ans. An object is declared using either of the general syntax:, , 1., 2., , <Class-name> <object-name> = new <Class-name>( <Parameter-List>);, <Class-name> <object-name>;, <object-name> = new <Class-name>( <Parameter-List>);, , For example, for a class named Coordinate to declare, , an object of Coordinate type you may use either of the syntax:, , 1. Coordinate obj=new Coordinate( ); or, 2. Coordinate obj; //declare an object, , obj=new Coordinate( ); // Allocate memory space, 9. How are objects used to access data-members?, Ans. The dot operator is used to access the individual members of a class using an object., Data members can be accessed within the functions of a class using the dot operator as shown in the, following syntax,, <objectname>.<data-member>, 10. Differentiate the following statements :, i) student Amit = new student( );, ii) student Sumit = new student(84,98,91);, Ans. i) An object named Amit is being created of student type using default constructor or a non-parameterised constructor., ii), An object named Sumit is being created of student type using a parameterised constructor that, accepts three integers as parameters., 11. Explain, with an example, how to return objects., Ans. The following program demonstrates how an object may be returned:, public class ReturnObject, {, int a,b;, void getval(int x,int y), {, a=x; b=y;, }, ReturnObject increment( )
Page 22 :
{, , ReturnObject temp=new ReturnObject( ); /*a new, object being created*/ temp.getval(a,b); /*initialize, the newly created, with values of the current object.*/, /*The statements below increases the attributes of the newly created object.*/, , temp.a++; temp.b++; return temp;, }, void show(), {, System.out.println(a+"\t"+b);, }, public static void main(String args[ ]), {, ReturnObject obj1=new ReturnObject(); obj1.getval(5,6);, ReturnObject obj2;, /*Declaration of the object, obj2*/, obj2=obj1.increment( ); obj1.show( );, obj2.show( );, }, , }, 12. Can an object be an attribute of another class, if so how?, Ans. The following example shows how an object may be an attribute of another class:, class Date, {, int dd,mm,yy;, }, public class Student, {, int roll; String name;, Date dob=new Date(); //variable dob of Date type static void test( ), {, Student obj=new Student( ); obj.roll=1; obj.name="Amit";, obj.dob.dd=12; /*To hold the day within the dd part of object dob of the object obj.*/, obj.dob.mm=9; /*To hold the day within the mm part of object dob of the object obj.*/, obj.dob.yy=90; /*To hold the day within the yy part of object dob of the object obj.*/, }, }, 13. What do you understand by Garbage Collection?, Ans. Garbage collection refers to automatic deallocation of the memory which was allocated using the new command when no, references to an object exist., 14. What are class variables and class methods?, Ans. The class variables and class methods are static methods within a class, that are not instantiated with every instance of, an object but rather only one copy is created., 15. What are the rules you should keep in mind while accessing static members?, Ans. The static members follows all rules of the access specifiers along with that it has the following restrictions:, , a), b), c), , They can only call other static methods. However, objects can be created in it., They can access only static data (class variables)., They cannot refer to this or super in any way. The usage of super keyword is beyond the scope of this, book., , 16. Explain in brief about the static block., Ans. Like instance variables, which is initialized through constructors, static variables are initialized through static block, it is a, block which gets executed exactly once, when the class is first loaded. Since only one copy of static variables exists within a, class, it needs to be initialized only once., 17. Differentiate between static and non-static data members., [ICSE 2010]
Page 23 :
Ans., , Static data-members, Multiple instances are not created with, every creation of an object., Static members are called by static, methods without using any object., , Non static data members, Multiple instances are created with every, creation of an object., Non-static members may be called by, static methods using an object., , 18. What is a Singleton class?, Ans. A Singleton class is such a class, whose just one and only one instance can be created., , Chapter 11: Constructors, Fill in the blanks:, , 1. A constructor is a Function defined in a class with name same as that of the class., 2. Constructor is invoked when an object is created., 3. A constructor that does not have any argument is called Default Constructor., 4. A constructor that takes the arguments is called Parameterised Constructor., 5. The class is the implicit return type of a constructor function., , A. Answer the following questions:, , 1. What is a constructor? Why is it needed in a program?, Ans. Constructor is a function that have the same name as the class and is automatically invoked during creation of an object., It is needed for:, , a) Allocate memory space for an object., b) Initialize data members within an object., , 2. State the characteristics of a constructor., Ans. Constructor is a member function of a class having the following characteristics:, , 1. It has same name as the class-name., 2. It cannot have a return type, not even void is used, because the implicit return type of a, constructor is the class itself., 3. It follows the usual rules of accessibility as other members of a class and therefore access, modifiers can be applied to it., 4. It gets called automatically whenever an object is created., 5. It is usually used to initialize the members of the class with legal initial values., , 3. How are constructors invoked?, Ans. Constructor function gets invoked automatically whenever an object is created., 4. Why do we need a constructor as a class member?, , Ans. Whenever an object is created, it must be constructed usually with legal initial values automatically without, being specified by the programmer. This will immensely relieve the programmer from initializing values of objects, for large programs and hence the need for constructor., 5. State the difference between function and constructor., Ans. Difference between function and constructor:, , Function, Its name is different as the name of, the class., Its return-typeshould be, specified., , Constructor, Its name is same as the classname., No return-type needs to be, specified., , 6. How are private constructors called?, Ans. Private constructors can be invoked only when an object is being created only within the same class block., 7. What are the different types of constructors available in Java?, Ans. Parameterised Constructor and Non-Parameterised Constructor., 8. What is a default constructor?, , Ans. Default Constructor refers to a non-parameterised constructor that initializes data members with default legal, values.
Page 24 :
9. Point out the difference between implicit and explicit default constructors., , Ans. Implicit default constructor is a constructor which gets created automatically by the JVM (which initializes the, data members with default initial values) incase the class do not have a constructor explicitly defined by the user., Explicit default constructor is a non-parameterized constructor defined by the programmer to initialize the datamembers within a class with default initial values., , 10. What are Temporary Objects? How are they created, explain with the help of an example?, Ans. An object that do not have a name and exist as long as the line is being executed is called Temporary or Anonymous, object. Temporary or Anonymous objects or instances are the ones that live in the memory as long as it is being used or, referenced in an expression and after that it dies. For example,, public class temp, {, int a,b;, temp(int x, int y), {, a=x; b=y;, }, void show(), {, System.out.println(a+","+b);, }, static void test( ), {, new temp(1,2).show( ); /*Temporary object is being called to invoke, }, show( ) function.*/, }, 11. What is constructor overloading? Illustrate it with the help of an example., , Ans. Multiple constructors of a class having different parameter lists in a class is termed as constructor overloading., For example,, class Cuboid, {, , double width; double height; double depth;, Cuboid( ) //Constructor with no parameter., {, width=0; height=0; depth=0;, }, Cuboid(double n) //Constructor with single parameter, {, width=height=depth=n;, }, Cuboid(double w, double h,double d), //Constructor with 3 parameters, {, width=w; height=h; depth=d;, }, void displayVolume(), {, double vol;, //Compute volume, vol= width*height*depth; System.out.println("The Volume is="+vol);, }, static void createObjects(), {, Cuboid mycuboid1=new Cuboid();, //Calls the first constructor version. Cuboid mycuboid2=new, Cuboid(2.0);, //Calls the 2nd constructor version.
Page 25 :
}, , Cuboid mycuboid3=new Cuboid(1.5,2.5,4.5);, //Calls the 3rd constructor version. mycuboid1.displayVolume( );, mycuboid2.displayVolume( ); mycuboid3.displayVolume( );, , }, 12. What is a destructor? Is destructor function necessary in Java? If no, explain why., Ans. Destructor is a function whose purpose is to deallocate memory space for an object which was allocated by the constructor., But Java uses a unique automatic method of deallocation of memory called garbage collection. This happens when no, references to an object exist, that object isassumed to be no longer needed, and therefore the memory occupied by the object, can be reclaimed. Since, garbage collection happens automatically in Java, there is no need of explicitly defining a destructor function in a class., 13. What is the implicit return type of a constructor function?, Ans. The implicit return type of a constructor is the class type., , Chapter 12:String Manipulation, A. Answer the following questions:, , 1. What is a String? Explain its use., Ans.The String data type is a class defined in the java.lang package and every variable that you create of String data type is, actually an object or object reference of the String class., Using String variable in Java it is possible to manipulate strings i.e. a group of characters, by extracting characters and, manipulate it., 2. Why is String considered to be immutable?, Ans. String is considered to be immutable as it is not possible to insert or remove characters from it. Moreover every time a, new value is assigned to a String variable it occupies a different memory location as compared to the previous allocation., 3. What are the common methods of initializing String objects?, Ans. A string may be initialised either using a String reference. For example, String s="COMPUTER";, Or initialised using a constructor while creating a String object. For example, String s=new String("COMPUTER");, 4. What is concatenation? Give an example to show how '+' operator is used to perform concatenation., Ans. Joining of two or more strings to form a single string is termed as concatenation. For example,, String a="AB", b="CD",c; c=a+b;, Thus the value of the variable c is "ABCD"., 5. Explain, with the help of an example, the functionality of toString( )., Ans. The toString( ) function in Java is used to convert a value of any data type to String. For example, the following, statements convert a value (say 45) stored in an integer variable to a String., int a=45;//45 is stored in int type variable, String s=Integer.toString(a); // Content of variable a is converted to String., 6. Give the code to extract the first and the last character of a string in Java., Ans. In case the String is stored in a variable named ‘s’., To extract the first character use: s.charAt(0), To extract the last character use: s.charAt(s.length( )-1), 7. State the use of the following String member functions, along with examples:, i) substring( ), ii) replace( ), iii) trim( ), , Ans. i)substring( ), , : It is used a part of a string from a given string . It has two syntaxes:, a) substring(s,e): Extracts characters from s to e-1(s and e are indexes and should be of, int type). For example, “INDIA”.substring(1,4) will give “NDI”., b) substring(s): Extracts characters from s till the end of the string (s is an index and should be of int, type). For example, “Laserjet”.substring(5) will yield ”jet”., , ii) replace( ) :It is used to replace a character/string from a string with another character/string. Its general, syntax is:, iii) trim(), , replace(c,d): It is used to replace the character c with character d. For example, “BEETEL”.replace(‘E’,’O’) will, yield “BOOTOL”, : It is used to remove leading and trailing spaces in a string. For example, “, COMPUTER ”.trim( ) will yield
Page 26 :
“COMPUTER”, , 8. Give the difference between the following functions:, i) = = and equals( ), ii) toLowerCase( ) and toUpperCase( ), iii) startsWith( ) and endsWith( ), iv) indexOf( ) and lastIndexOf( ), , Ans. i), , ==, Checks whether two strings belong to, the same memory location or not., Checks whether two quantities are, equal or not. The quantities may be, any data type other than string., , equals( ), Checks whether two string quantities, are same or not., Checks only two string quantities are, same or not., , ii), , toLowerCase( ), Converts a given character or a string to, lower case., , toUpperCase( ), Converts a given character or a string to, upper case., , iii), , startsWith( ), Checks whether a string begins with a, certain character or a string or not and, returns true or false accordingly., , endsWith( ), Checks whether a string ends with a, certain character or a string or not and, returns true or false accordingly., , iv), , indexOf( ), Searches for a certain character or string, from to left to right in a given string and, return the index for the first occurrence of, the found character or string otherwise, return -1., , lastIndexOf( ), Searches for a certain character or string, from to right to left in a given string and, return the index for the first occurrence, of the found character or string, otherwise, return -1., , 9. Explain compareTo( ) function, with respect to the values that it returns., Ans. The compareTo( ) function is used to lexicographically check two strings where the Unicode differs and accordingly, return their difference., The value returned by the compareTo( ) function is the difference between the corresponding Unicodes of the characters,, where it differs. If at no point the character differs in the strings a 0 is returned., For example,, System.out.println("abc".compareTo("abde"));, Will display –1, as the strings differ from the character at position 2 (i.e. 'c' and 'd'). The Unicode for 'c' is 99 and 'd' is 100 and, therefore their difference is –1., System.out.println("COMPUTRONICS".compareTo("COMPUTER"));, Will display 13, as the pair of strings differ from the character at position 6 (i.e. 'R' and 'E'). The Unicode for 'R' is 82 and 'E' is 69, and therefore their difference is 13., If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case,, it returns the difference of the lengths of the strings. For example,, System.out.println("AB".compareTo("ABCD"));, will display –2 as "AB".length( )–"ABCD".length( )=2 – 4=–2, 10. Differentiate between compareTo( ) and equals( ) methods., , Ans., , compareTo( ), equals( ), Checks two strings lexicographically., Checks two strings for equality., Returns the first difference between the, Returns either a true or a false., Unicode of the characters where it differs.
Page 27 :
Return type is int., , Return type is Boolean., , 11. What is Unicode? How can you get the unicode value of a Java character?, Ans. Unicode is a universal international standard character encoding that is capable of representing most of the world's, written languages. Using this system of encoding it is possible to represent 65,536 characters., To get the Unicode value of a Java character simply type-cast it with int. For example, char x='B';, int p=(int)x; //It will assign the Unicode of the character x into p., , Chapter 13:Arrays, A. Answer the following questions:, , 1. What are arrays?, Ans. An array is a homogeneous collection of data, referred by a name and occupying contiguous memory space., 2. How do you declare single or 2-dimensional arrays?, Ans. To declare a single dimensional array the following syntax is used: The general syntax is,, <data type> <array-name>[ ]; or,, <data type>[ ] <array-name>;, For example, to declare an integer array use, int a[ ]; int[ ] a;, 3. How do you create memory spaces for arrays?, Ans. To allocate memory space for a declared array the following general syntax is used., <array-name>=new<data-type>[<size>];, For example, to allocate 10 memory spaces for the integer array use, a=new int[10];, 4. How do you initialize single dimensional arrays. Explain with examples., Ans. To initialise a single dimensional array the following general syntax is used:, <data-type> < array-name>[ ]={ <list of values >}; For example, to initialise an integer, array you may use,, int a[ ]={1,2,3,4,5};, 5. With the help of an example, explain how arrays of objects are used in a Java program., Ans. The declaration for an array of objects uses the following general syntax,, <class-name> <array-name>[ ]=new <class-name>[<size>]; Or,, <class-name>[ ] <array-name>=new <class-name>[<size>]; Or,, <class-name> <array-name>[ ];, <array-name>=new <class-name>[<size>];, For example, to declare an object of size 10 for a class named Cuboid, you may use,, Cuboid obj[ ]=new Cuboid[10]; or,, Cuboid[ ] obj=new Cuboid[10]; or,, Cuboid obj[ ]; obj=new Cuboid[10];, 6. With the help of an example, show how arrays in Java are dynamic in nature., , Ans. Arrays in Java are always dynamic in nature in the sense that the size of an array is specified at run-time. Here is an, , example, that takes an integer(say n) as input using Scanner and then declares an integer array of size n., Scanner sc=new Scanner(System.in); int n;, System.out.println("Enter the value of n:"); n=sc.nextInt( );, int a[ ]=new int [n];, Note that the array ‘a’ of size n is declared at runitime., 7. "Array variables are references to a block of elements". What do you understand by this statement?, Ans. An array variable is always a reference to a block of memory and therefore can be used to refer to a memory, location which is referred by another array variable., For example,, int[ ] a = {100, 99, 98}; // "a" references the array object. int[ ] b; // "b" doesn't refer to, anything., b = a; // Now "b" refers to the SAME array as "a"
Page 28 :
b[1] = 0; // Also changes a[1] to 0 because a and b refer to the same array., 8. How do you determine the length of an array?, Ans. Length of an array refers to the number of elements in the array. To determine the length of an array the following, general syntax is used:, <array-name>.length( );, 9. With the help of an example show how arrays are passed to a function as Call by Reference., Ans. An array when passed to a function, it is always passed as a reference, therefore any changes made to the formal, parameter is reflected by to the actual parameter., The following example shows how this is performed:, class ArrayDemo, {, /*Method to double the value of each element in the array.*/, static void doubleIt(int b[ ]), {, for(int i=0;i<b;i++), {, b[i]=2*b[i];, }, }, public static void main(String args[ ]), {, int a[ ]={4,5,12,7,8,3};, System.out.println("Original Array..."); for(int i=0;i<6;i++), System.out.print(a[i]+"\t");, doubleIt(a); //this is how you pass an array as parameter., System.out.println("Updated Array..."); for(int i=0;i<6;i++), }, , System.out.print(a[i]+"\t");, , }, Output when main( ) is executed will be, Original Array..., 4 5 12 7 8 3, Updated Array... 8 10 24 14 16 6, 10. Explain:, i) Linear Search ii) Binary Search, Ans. i) Linear Search:, Linear Search is a search process technique that involves checking each element sequentially, with the given element to be searched for., , ii) Binary Search: Binary search is a search process technique where an element to be searched is checked, with the central element of the array and depending upon its value, it is checked in the sub-array before the, central position or in the sub-array after the central position. The same search process continues even with, the sub-array., , 11. Compare Linear Sorting, Selection Sorting and Bubble Sorting., Ans. Linear Sorting: The linear sorting process checks each element of the array with the remaining elements of the array, after it. In case the array element is greater than either of the remaining elements, the elements are interchanged. The, process continues until all elements are exhausted., Bubble Sorting: The bubble sorting process checks adjacent elements of the array, i.e. first element with the second element,, the second element with the third element and the process continues until all elements are exhausted. In case the array, element is greater than the adjacent element, the elements are interchanged. The process continues until all elements are, exhausted., Selection Sort: During the selection sort process, an element is taken from the first and from the remaining elements the, smallest or largest number (for ascending or descending order respectively) is found and interchanged., 12. Differentiate between Binary Search and Linear Search., , Ans.
Page 29 :
13. Which element is num[9] of the array num?, Ans. It is the 10th element in the array num., 14. Name the keyword that is used for allocating memory to an array. [ICSE 2009], Ans. The ‘new’ command is used for allocating memory to an array., , 15. State two advantages and disadvantages of using arrays., , Ans. Advantages:, i), Gives a concise code as declaration, allocation of space and initialization can be done in a single line., ii), Java arrays are dynamic, unlike other languages like C, C++ where it is static usually., Disadvantages:, i), Arrays allow you to store elements of only one data type, i.e. only homogeneous data can be, stored, thus data of heterogeneous data type cannot be stored, which is often required by a, programmer., ii), Arrays always require contiguous free memory location to be allocated for storing elements. But there, may be situations when the available memory is discrete in nature and therefore array cannot be used to, efficiently use the memory., , Chapter 14: Console Input / Output ; Encapsulation; Errors, A. Answer the following questions:, , 1. What is the function of the System class? What are the stream variables associated with the Stream?, Ans. class System is a built-in class present in java.lang package, having a final modifier, which does not allow it to be, inherited and contains pre-defined methods and fields, which provide facilities like standard input, output, etc., The Stream variables associated with the Stream class are System.in and System.out., 2. Explain the concept of Streams in Java., Ans. A stream in Java is an ordered sequence of bytes of undetermined length. Streams are ordered and in sequence so, that the Java virtual machine can understand and work upon the stream. There are two categories of streams in Java,, namely Byte stream and Character stream., 3. Briefly explain the two types of streams available in Java., Ans. Byte streams carry integers with values that range from 0 to 255. A diverse assortment of data can be expressed in byte, format, including numerical data, executable programs, Internet communications and bytecode—the class files run by a Java, virtual machine., Character streams are a specialized type of byte stream that handles only textual data. They are distinguished from byte, streams because Java's character set supports Unicode, a standard that includes many more characters than could be expressed, easily using bytes., 4. What is the function of the BufferedReader class? In this respect explain the function of the InputStreamReader class. Also, state the package under which the above classes are associated., Ans. The BufferedReader class read text from a character input stream, buffering characters so as to provide for the, efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used., The InputStreamReader class is a bridge from byte streams to character streams: It reads bytes and decodes them into, characters using a specified char set. The char set that it uses may be specified by name or may be given explicitly, or the, platform's default character set may be accepted., The package under which these classes are available is java.io., 5. Show, with the help of an example, how character and String can be entered through console using BufferedReader, class.
Page 30 :
Ans. Program to input a character from the console:, import java.io.*; class readCharDemo, {, static void test() throws IOException, {, char x;, BufferedReader br=new BufferedReader(new, InputStreamReader(System.in)); System.out.println("Enter a, character:");, , }, , }, , x=(char)br.read();, /*typecasting is necessary as the method read() returns the unicode, of the corresponding character entered by the user.*/, System.out.println("You have input:"+x);, , Program to input a String from the console:, import java.io.*; class readCharDemo, {, static void test() throws IOException, {, String s;, BufferedReader br=new BufferedReader(new, InputStreamReader(System.in)); System.out.println("Enter a, string:"); s=br.readLine(); System.out.println("You have, input:"+s);, }, }, 6. State the difference between print( ) and println( ) functions of the System class., Ans. System.out.print( ) is used to display a String on the console and keeps the cursor in the same line., , System.out.println( ) is used to display a String on the console and brings the cursor to the next line., , 7. Generally all numeric data you print using System.out.print( ) and System.out.println( ) is left-aligned if you want, a formatted output, where a numeric data will be right-aligned, what function would you use?, Ans. System.out.printf( ) should be used., 8. What is the function of the Scanner class? Under which package is it available?, Ans. The Scanner class is a class in java.util, which allows the user to read values of various types, from either, , keyboard or a file., , 9. What are tokens as identified by the Scanner class?, Ans. A token as identified by the Scanner class is a series of characters that ends with what Java calls whitespace. A whitespace, character can be a blank, a tab character, a carriage return, or the end of the file., 10. What is a delimiter? How would you make Scanner class read data from the keyboard separated by, or; or space?, Ans. A delimiter is a character or pattern that marks the end of a token. The delimiter to make a Scanner class read data from, the keyboard separated by , or ; or space is, sc.useDelimiter("[,; ]");, where sc is the name of the Scanner object., 11. Give an example where you will read an integer and an entire line of text (say a sentence) using the Scanner class., Ans. import java.util.Scanner;, class Example11, {, static void main(), {, Scanner sc=new Scanner(System.in); int n;, String s;, System.out.println("Enter an integer:"); n=sc.nextInt();, sc.nextLine();//dummy input System.out.println("Enter a string:");, s=sc.nextLine(); System.out.println("Integer:"+n);
Page 31 :
}, , System.out.println("String:"+s);, , }, 12. What is the function of hasNext( ) function of the Scanner class?, Ans. The hasNext…( ) member function of the Scanner class checks whether the next token is the specified token or, , not., A. State whether true or false:, , 1. A class is used to implement encapsulation., [True], [False], 2. Instance variables are used to represent behaviour of an object., 3. You need to prefix the keyword default before data members which, [False], should have default/friendly access specifier., 4. The access specifier private allows accessibility of a member only within the class where the member is, declared/defined, but not outside the class.[True], 5. Java source code should always have the .jav extension., [False], , B. Fill in the blanks:, 1. The access specifier protected allows accessibility within the same package by both classes and sub-classes but only by, , sub-classes in a different package., 2. In case there are multiple classes in a source code the class from where the program should start execution should have the, access specifier as public., 3. The private access specifier is not allowed for a class., 4. The extends keyword is used to perform inheritance in Java., 5. The keyword used to include a class in a package is package., , C. Choose the correct answer:, , 1. Which among the following allows global accessibility?, a) public, b) private, c) protected, , Ans. a) public, , d) All of these, , 2. Which among the following allows accessibility only within the class where the member is defined or declared?, a) public, b) private, c) protected, d) All of these, , Ans. b) private, , 3. In case, a source code has multiple classes; the class from which the program begins should have the, a) public, b) private, c) protected, d) All of these, , access specifier., , Ans. a) public, , 4. Which among the following is true, if a constructor is declared as private for a class?, a) Another class may declare the object of that class., b) An object may be declared only within that class., c) An object may be declared in a different package., d) None of these., Ans. b) An object may be declared only within that class., 5. Which among the following is not true for inheritance?, a) The class which is being inherited is called the super-class and the class that inherits it is called the sub-class., b) The extends keyword is used to perform inheritance., c) private members of a super-class is also inherited in the sub-class., d) The member functions of a super-class can manipulate the values of the data- members of a sub-class., Ans. d) The member-functions of a super-class can manipulate the values of the data- members of a sub-class., 6. Which among the following statements is true with respect to packages?, a) The command package <package-name>; should be the given as the first line inside the class., b) The command package <package-name>; should be the given just after the import command., c) The command package <package-name>; should be the given as the first line even before the import statement., d) The command package <package-name>; may be provided anywhere in the source code., , Ans. c) The command package <package-name>; should be the given as the first line even before the import, statement., 7. Which operator is used to access individual subpackages and classes in a package?, a) + operator, b) new operator, c) this operator, d) dot operator, , Ans. d) dot operator
Page 32 :
8. Which operator is used to import all classes within a package?, a) *, b) all, c) +, , Ans. a) *, , d) None of these, , 9. Which menu among the following is used to create a package in BlueJ?, a) Project, b) Edit, c) Tools, d) Help, , Ans. b) Edit, , 10. Which among the following access specifiers allows accessibility outside that package?, a) public and private, b) public and protected, c) public and default, d) private and protected., Ans. b) public and protected, , Answer the following questions:, , 1. What is a wrapper class? Give few examples of wrapper classes., Ans. The wrapper class encapsulate or wrap the primitive data-types within a class to form an object representation of it., , Examples of wrapper classes, 2. What are access specifiers?, Ans. Access specifiers are keywords which is used to declare which entity cannot be accessed from where. Its effect has, different consequences when used on a class, class member (variable or method), constructor. ava offers four access specifiers,, listed below in decreasing order of accessibility:, , •, •, •, •, , public, protected, default/friendly, private, , 3. Explain the statement:, Character c=‘A’;, Ans. An object named ‘c’ of the warapper class Character is being initialized with the character constant ‘A’., 4. Given a statement:, String s= “123”;, Write a statement so that the numeric value of the variable s may be stored in an integer., int a=?, Ans. int a=Integer.parseInt(s);, 5. Given a statement:, double d=12.36;, Write a statement so that the numeric value of the variable d may be stored in a String variable., String a=?, Ans. String a=Double.toString(d);, 6. Name the wrapper class function that converts an integer to a:, i) Binary Number, ii) Octal Number, iii) Hexadecimal Number, Ans. i) Integer.toBinaryString( ) ;, , ii) Integer.toOctalString( );
Page 33 :
iii) Integer.toHexString( );, , 7. State the difference between parse...( ) and valueOf() method., Ans. The parse...( ) method of the wrapper class converts a String to its corresponding primitive data type and returns it, whereas valueOf() method converts a String to the corresponding wrapper object and returns it., 8. State the similarity difference between private and default access apecifier. Ans. Similarity between private and default, , access specifier is that both allows accessibility within the class., , Difference between private and default is that private access specifier allows accessibility only within the class and default access, specifier allows accessibility to all classes within a package., 9. What is a package? State its significance., Ans. Package is a folder that contains compiled classes having both a name and a visibility control mechanism for using its, function in another class., A package gives you an organized way of managing classes in Java. You can group related classes into a package thus making it more, organized. Similarly it is possible to define classes inside a package that are not accessible by code outside the package. There may also, be classes that are only exposed to other members of the same package. This allows the classes to have intimate knowledge of each, other, but do not expose it to the entire world., 10. Why can’t a class be declared as private?, Ans. A class when defined as private, it will be impossible to access its members and thus making it unusable., 11. Write the statement to import all classes from the Simple package., , Ans. import Simple.*;, , A. Answer the following questions:, , 1. What is a bug?, Ans. Bug is any error that may have crept in a program because of typographical error or logical errors or some run-time, errors., 2. State the different types of errors you might encounter during coding., Ans. a), Syntax/Semantic error, , b), c), , Logical error, Run-time error, , 3. Give three examples when you will get compile-time error., Ans. Compile time errors may be generated in the following situations:, , a), b), c), , Missing semicolon after a statement., A keyword is used as an identifier., A keyword is mis-spelt., , 4. What are run-time errors?, Ans. Run-time errors occur during execution of a program when an exceptional situation may occur, which disrupts the, proper execution of the program., 5. What are Exceptions? What do you understand by the statement "throwing an exception"?, Ans. An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's, instructions. Whenever an error occurs during the execution of a method, the method creates an object and hands it off to the, run-time system. The object, called an exception object, contains information about the error, including its type and the state of, the program when the error occurred., During execution of a program, if a run-time error occurs, the method in which it occurs creates an Exception object and passes it, on to the Java run-time system. This is called throwing an object., 6. What do you understand by the statement "A Java code must honour the Catch/Specify Requirement"?, Ans. A Java program must honour the Catch or Specify Requirement. This means that code that might throw certain exceptions, must be enclosed by either of the following:, , •, •, , A try statement that catches the exception., A method that specifies that it can throw the exception. The method must provide a throws clause that, lists the exception., , 7. What is an Exception Handler?, Ans. The run-time system searches the call stack for a method that contains a block of code that can handle the exception. This, block of code is called an exception handler., 8. What are the different types of exceptions?, Ans. There are two types of exceptions:, , a), b), , Checked Exceptions, Unchecked Exceptions
Page 34 :
9. Give three common Exception class names., Ans. i) ArithmeticException, , ii) ArrayIndexOutOfBoundsException, iii) InputMismatchException, , 10. State the difference between throw and throws., , Ans., , throws, If a method is capable of causing an, exception that it doesn’t handle, it must, specify this behaviour using the throws, clause., , throw, The throw clause is used by the, programmer to deliberately invoke an, exception object., , 11. What is Encapsulation?, Ans. Wrapping up of characteristics (represented by data members) and behaviour (represented by member functions) into a, single unit (using a class) is called Encapsulation., 12. What are the different access specifiers available in Java?, , Ans. i), ii), iii), iv), , default, private, private, protected, , Ans. 13. State the difference between:, i), , i) public and protected access specifier., ii) private and default access specifier., , public, protected, It allows accessibility by all classes within It allows accessibility by classes within the, the package as well as outside the package. package but only by sub-classes outside the, package., , ii), , private, It allows accessibility only within the class, of which it is a member., , default, It allows accessibility by all classes within, the package., , 14. What happens when a constructor is given a private access?, Ans. When a constructor is given a private access, its object can only be created within the class of which it is a member., 15. Give an example to show how overloaded constructors can have different access specifiers., Ans. public class Example, {, int a,b; Example(), {, a=b=0;, }, private Example(int x), {, }, , a=b=x;, , public Example(int x,int y), {, a=x; b=y;, }, protected Example(int x,int y,int z), {, a=x; b=y+z;, }
Page 35 :
void show(), {, System.out.println(a+"\t"+b);, }, }, 16. What is inheritance? Which command is used for inheritance in Java?, Ans. Inheritance is the property by which all members of one class becomes members of another class. The class which is, being inherited is called the base or super class and the class which inherits it is called the derived or sub-class., The command used for inheritance is ‘extends’., 17. What are packages? Which package is imported by default in Java?, Ans. Package is a folder that contains compiled classes having both a name and a visibility control mechanism for using its, function in another class., The package which is imported by default is java.lang., 18. State the conditions necessary to make a class part of a package., Ans. To make a class part of a package, the first line of the source code should include the code:, package <package-name>;, 19. What is the function of import command in Java? Show with the help of an example how a single class within a, package is imported. Also state how all classes may be imported in a program., Ans. The import command in Java is used to include a class or group of classes that are within the package for its functions and, variables to be reused within a class., To import a single class of a package, use the following syntax: import <package-name>.<classname>;, To import an all classes of a package, use the following syntax: import <package-name>.*;, 20. What is a Wrapper class?, , Ans. For every primitive data-type there is corresponding class that wraps around the primitive data-type to form an object, , representation of it. This is called Wrapper class.