Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAVA QB Answers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

UNIT I

Questions carrying 2 marks


1. What is Object Oriented Programming?
Object-oriented programming is an approach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand.
2. Define the terms i) Data Encapsulation ii) Data Abstraction
i)The wrapping up of data and methods into a single unit (called class) is known as encapsulation.
Data encapsulation is the most striking feature of a class, means data is not accessible to the
outside world and only those methods, which are wrapped in the class can access it.
ii) Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and Cost and methods that operate on these attributes. They
encapsulate all the essential properties of the Objects that are to be created.
3. What do you mean by data hiding?
These methods provide the interface between the object's data and the program. This insulation
of the data from direct access by the program is called data hiding.
4. What is Polymorphism? Give example
Polymorphism means the ability to take more than one form. Consider the operation of addition.
For two numbers, the operation will generate a sum. If the operands are strings then the operation
would produce a third string by concatenation.

5. What is dynamic binding?


Dynamic Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at runtime. It is associated with polymorphism and inheritance. A
procedure call associated with Polymorphic reference depends on the dynamic type of that
reference.
6. Mention any four advantages of OOP.
•Emphasis is on data rather than procedure.
•Programs are divided into what are known as Objects.
•Data structures are designed such that they characterize the objects.
•Methods that operate on the data of an object are tied together in data structure.
•Data is hidden and cannot be accessed by external functions.
•Objects may communicate with each other through methods.
•New data and methods can be easily added whenever necessary.
•Follows bottom-up approach in program design.
7. Mention any four application areas of OOP.
The promising areas for application Of OOP includes:
•Real-time systems
•Simulation and modelling
•Object-oriented databases
•Hypertext. hypermedia and expertext
•AI and expert systems
•Neural networks and parallel programming
•Decision support and office automation systems
•CIM/CAD/CAD system
8. List any four features of Java

9. What is Java Bytecode?


Usually, a computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system. First Java compiler translates source code into
what is known as bytecodes instructions. Bytecodes are not machine instructions and therefore,
in the second stage, Java interpreter generates machine code that can be directly executed by the
machine that is running the Java program.
10. What is Java Virtual Machine?
All language compilers translate source code into machine code for a specific computer. Java
compiler also does the same thing. The Java compiler produces an intermediate code known as
byte-code for a machine that does not exist. This machine is called the Java Virtual Machine and it
exists only inside the computer memory. It is a simulated computer within the computer and does
all major functions of a real computer.
11. Write the meaning of public static void main(String args[])
public static void main (String args[ ]) defines a method named main. This is similar to the main( )
function in C/C++. Every Java application program must include the main( ) method. This is the
starting point for the interpreter to begin the execution of the program.
Here, String args[] declares a parameter named args, which contains an array of objects of the class
type String
12. Mention two ways of writing comments in Java
In addition to the two styles of comments (//, /* */) Java also uses a third style of comment known
as documentation comment (/** */). This form of comment is used for generating documentation
automatically.
13. List any 4 primitive data types available in Java.

14. What is the difference between 10.3 and 10.3f?


In Java, `10.3` is a `double` literal and `10.3f` is a `float` literal ¹. The difference between the two is
that `double` is a 64-bit floating-point number and `float` is a 32-bit floating-point number ². When
you use a floating-point literal without a suffix, it is treated as `double`. If you want to specify a
`float` literal, you need to add an `f` or `F` suffix to the number ¹.
15. What are the two ways of initializing variables?
In Java, there are two ways to initialize variables:
1. You can declare a variable and assign a value to it on the same line. For example:
int x = 5;
2. You can declare a variable and assign a value to it later in your code. For example:
int x;
x = 5;
In both cases, you need to specify the data type of the variable (in this case, `int`) before the
variable name ⁴.
16. What is dynamic initialization of variables? Give example.
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared. For example, here is a short program that computes the volume of a cylinder
given the radius of its base and its height:
// Demonstrate dynamic initialization.
class DynInit
{ public static void main(String args[])
{ double radius = 4, height = 5;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
//volume is dynamically initialized at run time.
System.out.println("Volume is " + volume);
}
}
17. List different arithmetic operators available in Java
Arithmetic operators are used to construct mathematical expressions as in algebra.
Integer Arithmetic
Real Arithmetic
Mixed-mode Arithmetic
18. What is type conversion or type casting? What are its types?
The process of converting one datatype to another is called casting.
Syntax: type variable1 =(type) variable2;
In Java, there are two types of casting:
• Widening Casting (automatic/Implicit)
• Narrowing Casting (manual/Explicit)
19. What is automatic (implicit) type conversion? Give example
Widening Casting (automatic/Implicit) - converting a smaller type to a larger type size done
automatically by the compiler.

20. Write the meaning of System.out.println()


System.out.printIn("Java is better than C++ "); This is similar to the printf( ) statement of C or cout
<< construct of C++. Since Java is a true object-oriented language, every method must be part of
an object. The println method is a member of the out object, which is a static data member of
System class. This line prints the string Java is better than C++. to the screen.
21. Write a single print statement to produce the following output a. ONE b. TWO c. THREE
Here's a single print statement that will produce the output
System.out.println("a. ONE\nb. TWO\nc. THREE");
This will print:
a. ONE
b. TWO
c. THREE
The `\n` character is used to create a new line .
22. What is stream? List different types of streams in Java.
Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system.
Java defines two types of streams: byte and character.
23. Differentiate byte and character streams.
Java defines two types of streams: byte and character.
1. Byte streams provide a convenient means for handling input and output of bytes. Byte streams
are used, for example, when reading or writing binary data.
2. Character streams provide a convenient means for handling input and output of characters. They
use Unicode and, therefore, can be internationalized.
24. List the predefined streams of system object
All Java programs automatically import the java.lang package. This package defines a class called
System, which encapsulates several aspects of the run-time environment.
System also contains three predefined stream variables: in, out, and err.
1.System.out refers to the standard output stream. By default, this is the console.
2. System.in refers to standard input, which is the keyboard by default.
3. System.err refers to the standard error stream, which also is the console by default. However,
these streams may be redirected to any compatible I/O device.
25. Write the syntax of simple if statement with example.

26. Write the syntax of switch statement.

27. Give the syntax of declaring a symbolic constant with example.


In Java, you can declare a symbolic constant using the `final` keyword. The syntax for declaring a
symbolic constant is:
final type CONSTANT_NAME = value;
Here's an example:
final int MAX_VALUE = 100;
In this example, `MAX_VALUE` is the symbolic constant and its value is `100`. Once you declare a
symbolic constant using the `final` keyword, its value cannot be changed ⁴.
Questions carrying 4 or more marks
1. Explain various features of OOP.
Features of object-oriented paradigm are:
•Emphasis is on data rather than procedure.
•Programs are divided into what are known as Objects.
•Data structures are designed such that they characterize the objects.
•Methods that operate on the data of an object are tied together in data structure.
•Data is hidden and cannot be accessed by external functions.
•Objects may communicate with each other through methods.
•New data and methods can be easily added whenever necessary.
•Follows bottom-up approach in program design
2. Write a note on application and benefits of OOP.
The promising areas for application Of OOP includes:
•Real-time systems
•Simulation and modelling
•Object-oriented databases
•Hypertext. hypermedia and expertext
•AI and expert systems
•Neural networks and parallel programming
•Decision support and office automation systems
•CIM/CAD/CAD system
Benefits of OOP
OOP offers several benefits to both the program designer and the user.
•Through inheritance, we can eliminate redundant and extend the use of existing classes.
•We can build programs from the standard working modules that communicate with one another
rather than having to start writing the code from scratch. This leads to saving of development time
and higher productivity.
•The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
•It is possible to have multiple objects to coexist Without any interference.
•It is possible to map objects in the problem domain to those objects in the program.
•It is easy to partition the work in a project based on objects.
•The data-centered design approach enables us to capture more details of a model in an
implementable form.
•Object-oriented systems can be easily upgraded from small to large Systems.
•Message passing techniques for communication between objects make the interface descriptions
•with external systems much simpler.
•Software complexity can be easily managed.
3. List and explain different features of Java
Compiled and Interpreted: Usually a computer language is either compiled or interpreted. Java
combines both these approaches thus making Java a two-stage system. First Java compiler
translates source code into what is known as bytecodes instructions. Bytecodes are not machine
instructions and therefore, in the second stage, Java interpreter generates machine code that can
be directly executed by the machine that is running the Java program. We can thus say that Java is
both a compiled and an interpreted language.
Platform-independent and Portable: Java programs are portable i.e Java programs can be easily
moved from one computer system to another, anywhere and anytime. Java ensures portability in
two ways. First, Java compiler generates bytecode instructions that can be implemented on any
machine. Secondly, the size of the primitive data types are machine-independent.
Object-Oriented: Java is a true object-oriented language. Almost everything in Java is an object.
All program code and data reside within objects and classes. Java comes with an extensive set of
classes arranged in packages, that we can use in our programs by inheritance. The object model in
Java is simple and easy to extend
Robust and Secure: Java is a robust language. It provides many safeguards to ensure reliable code.
It has strict compile time and run time checking for data types. Security becomes an important
issue for a language that is used for programming on Internet. Java systems not only verify all
memory access but also ensure that no viruses are communicated with an applet.
Distributed: Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and programs. Java applications can open and access remote objects
on Internet as easily as they can do in a local system. This enables multiple programmers at
multiple remote locations to collaborate and work together on a single project.
Simple, Small and Familiar: Java is a small and simple language. Many features of C and C++ that
are either redundant or sources of unreliable code are not part of Java. For example, Java does not
use pointers, preprocessor header files, goto statement and many others. It also eliminates
operator overloading and multiple inheritance.
Multithreaded and Interactive: Java supports multithreaded programs, means handling multiple
tasks simultaneously. This means that we need not wait for the application to finish one task before
beginning another. For example, we can listen to an audio clip while scrolling a page and at the
same time download an applet from a distant computer. This feature greatly improves the
interactive performance of graphical applications.
High Performance: Java performance is impressive for an interpreted language, mainly due to the
use of intermediate bytecode. According to Sun, Java speed is comparable to the native C/C++.
Java architecture is also designed to reduce overheads during runtime. The incorporation of
multireading, enhances the overall execution speed of Java programs.
Dynamic and Extensible: Java is a dynamic language. Java is capable of dynamically linking in new
class libraries, methods, and objects. Java programs support functions written in other languages
such as C and C+ +. These functions are known as native methods. Native methods are linked
dynamically at runtime.
4. Explain a simple java program with example.

5. Explain the java program structure with example.


Java Program Structure
A Java program may contain many classes Of which only one class defines a main method. Classes
contain data members and methods that operate on the data members of the class. Methods may
contain data type declarations and executable statements. To write a Java program, we first define
classes and then put them together. A Java program may contain one or more sections as shown
below

The documentation section


comprises a set of comment lines giving the name of the program, the author and other details.
In addition to the two styles of comments (//, /* */) Java also uses a third style of comment known
as documentation comment (/** */). This form of comment is used for generating documentation
automatically.
Package Statement
The first statement allowed in a Java file is a package statement. This statement declares a package
name and informs the compiler that the classes defined here belong to this package. Example:
package student; The package statement is optional.
Import Statements
import statement is similar to the #include statement in C. Example: import student.test; This
statement instructs the interpreter to load the test class contained in the package student.
Interface Statements
An interface is like a class but includes a group of method declarations. This is also an optional
section and is used only when we wish to implement the multiple inheritance feature in the
program.
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a Java program. These classes are used to map the objects of real world problems. The
number of classes used depends on the complexity of the problem.
Main Method Class
Since every Java stand-alone program requires a main method as its starting point, this Class is the
essential part Of a Java program. A simple Java program may contain only this part. The main
method creates objects of various classes and establishes communications between them. On
reaching the end of main, the program terminates and the control passes back to the operating
system.
6. What are identifiers? Write the rules to be followed when creating an identifier.
Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables.
objects, packages and interfaces in a program. Java identifiers follow the following rules:
I. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be
descriptive and easily read.
7. List and explain different primitive data types available in Java.
Integer Types

Integer types can hold whole numbers such as 123.-96, and 5639. Java supports four types of
integers . They are byte, short, int, and long. Java does not support the concept of unsigned types
and therefore all Java values are signed meaning they can be positive or negative. Table 4.2 shows
the memory size and range of all the four integer data type
8. Explain automatic type conversion with suitable
code example.

9. Explain explicit type conversion with example.


10. What are streams? List and explain different byte and character streams
Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system. All streams
behave in the same manner, even if the actual physical devices to which they are linked differ. Thus,
the same I/O classes and methods can be applied to any type of device.
Byte Streams and Character Streams
Java defines two types of streams: byte and character.
1. Byte streams provide a convenient means for handling input and output of bytes. Byte streams
are used, for example, when reading or writing binary data.
2. Character streams provide a convenient means for handling input and output of characters. They
use Unicode and, therefore, can be internationalized.
The Byte Stream Classes
Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that
handle the differences between various devices, such as disk files, network connections, and even
memory buffers.
The Character Stream Classes
Character streams are defined by using two class hierarchies. At the top are two abstract classes,
Reader and Writer. These abstract classes handle Unicode character streams. Java has several
concrete subclasses of each of these.
11. Explain the relational and logical operators with example.
Relational Operators
Java has several expressions for testing equality and magnitude. All of these expressions return a
Boolean value (that is, true or false). We often compare 2 quantities, and depending on their
relation, take certain decisions. For example, we may compare the age of 2 persons, or the price
of 2 items and so on. These comparisons can be done with the help of relational operators.
Logical Operators
Java has 3 logical operators.
The logical operators && and | | are used when we want to form compound conditions by
combining 2 or more relations.
An example is: a > b && x = = 10
An expression of this kind which combines 2 or more relational expressions is termed as a logical
expression or a compound relational expression.
A logical expression also yields a value of true or false, according to the truth table.
For NOT, the ! symbol with a single expression argument is used. The value of the NOT expression
is the negation of the expression; if x is true, x is false.

12. Explain the increment, decrement and conditional operator with syntax and example.
Increment and Decrement Operators
The unary increment and decrement operators ++ and -- comes in two forms, prefix and postfix.
They perform two operations. They increment (or decrement) their operand, and return a value
for use in some larger expression.
In prefix form, they modify their operand and then produce the new value.
In postfix form, they produce their operand’s original value, but modify the operand in the
background. The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators
and are used in the following form:
++m; OR m++;
--m; or m--; m=5;
y= ++m; In this case, the value of y and m would be 6.
If m=5; y= m++; then, the value of y would be 5 and m would be 6.
13. Explain the process of reading a character from the keyboard with suitable example.

14. Explain different forms of if statement with syntax and example


15. Explain switch statement with syntax and example
UNIT II
Questions carrying 2 marks
1. What is the purpose of break and continue statement? Give example.
2. Write the for statement for a loop that counts from 1000 to 0 by -2
for (int i = 1000; i >= 0; i -= 2)
{
// Your code here
}
3. Write a for loop to display even numbers between 1 and 100
public class EvenNumbers
{
public static void main (String [] args)
{
for (int i = 1; i <= 100; i++)
{
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
4. What are arrays?
An array is a group of like-typed variables that are referred to by a common name. Arrays of any
type can be created and may have one or more dimensions.
Arrays can be of any variable type.
Eg: salary[10];
5. How to create and instantiate a one-dimensional array? Give example

6. How to initialize an array at the time of creation? Give example.


7. What is the use of length member of arrays?

8. How to create and instantiate a two-dimensional array? Give example


9. What are different ways of constructing String? Give example.

10. List any four methods associated with Strings.

11. What is vector? How it is different from array?


Vector stores its elements also in an array but it will increase its capacity automatically to ensure
all elements be stored. So, use a Vector when you don’t know the number of elements ahead of
time.
The key difference between Arrays and Vectors in Java is that Vectors are dynamically-allocated.
Vectors possess a number of advantages over arrays:
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.
12. What are classes and objects?
Java is a true object-oriented language and therefore the underlying structure of all Java programs
is Classes.
Classes create objects and objects use methods to communicate between them.
Classes provide a convenient method for packing together a group of logically related data items
and functions that work on them. Thus, a class is a template for an object, and an object is an
instance of a class.
13. What is the purpose of new operator?
14. Write the syntax to create a class in Java.
The General Form of a Class
A class is declared by use of the class keyword.
The data, or variables, defined within a class are called instance variables.

15. Write a statement that creates and instantiates an object in Java.


When you create a class, you are creating a new data type. You can use this type to declare objects
of that type
It has this general form:
Class object = new classname( );

16. What are constructors? What is the purpose of a constructor?


17. What is the use of this keyword in java?

18. List any two restrictions of static methods.


Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
Questions carrying 4 or more marks
1. Explain for loop with syntax and example.

2. Explain any three forms of for loop with suitable example


3. Explain while loop with syntax and example
4. Explain do while loop with syntax and example.

5. Explain break and continue statement with suitable example.


REFER 2 marks 1st question
6. Write a note on Labelled loops.
7. Explain the use of for each style of loop with suitable code example.
The for-each loop is used to iterate over elements of an array or a collection (like ArrayList) in
Java. It is also known as the enhanced for loop. The syntax of the for-each loop is:
for (dataType item : array) {
// code to be executed
}
Here's an example of how to use the for-each loop to iterate over an array of integers:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
This will output:
1
2
3
4
5
8. What are arrays? Explain how to declare instantiate initialize and use a onedimensional array
with suitable code example
REFER 2 marks 5th and 6th question
9. Explain different methods to initialize an array with suitable example.
In Java, there are several ways to initialize an array . Here are some of them:

1. Initializing an array at the time of declaration:

int[] numbers = {1, 2, 3, 4, 5};

2. Initializing an array using a for loop:

int[] numbers = new int[5];

for (int i = 0; i < numbers.length; i++)


{
numbers[i] = i + 1;
}

3. Initializing an array using the Arrays.fill() method:

int[] numbers = new int[5];

Arrays.fill(numbers, 0);

4. Initializing a multidimensional array:

int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};

10. Explain any four string methods with suitable example.


1. `toLowerCase()`: This method returns a new string with all characters converted to lowercase.
For example:
String str = "Hello, World!";
String lowerStr = str.toLowerCase(); // lowerStr is "hello, world!"
2. `toUpperCase()`: This method returns a new string with all characters converted to uppercase.
For example:
String str = "Hello, World!";
String upperStr = str.toUpperCase(); // upperStr is "HELLO, WORLD!"
3. `replace()`: This method replaces all occurrences of a specified character or substring with
another character or substring. For example:
String str = "Hello, World!";
String newStr = str.replace("World", "Java"); // newStr is "Hello, Java!"
4. `trim()`: This method returns a new string with leading and trailing whitespace removed. For
example:
String str = " Hello, World! ";
String trimmedStr = str.trim(); // trimmedStr is "Hello, World!"
5. `length()`: This method returns the length of the string. For example:
String str = "Hello, World!";
int len = str.length(); // len is 13
6. `equals()`: This method compares two strings for equality and returns true if they are equal and
false otherwise. For example:
String str1 = "Hello";
String str2 = "World";
boolean isEqual = str1.equals(str2); // isEqual is false
11. Explain any five vector methods with code example.
1. `addElement()`: This method adds an element to the end of the vector. For example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
2. `elementAt()`: This method returns the element at the specified index of the vector. For example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
String str = vec.elementAt(0); // str is "Hello"
3. `size()`: This method returns the number of elements in the vector. For example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
int size = vec.size(); // size is 2
4. `removeElement()`: This method removes the first occurrence of a specified element from the
vector. For example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
vec.removeElement("Hello"); // vec is ["World"]
5. `removeAllElements()`: This method removes all elements from the vector. For example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
vec.removeAllElements(); // vec is []
6. `insertElementAt()`: This method inserts an element at a specified index of the vector. For
example:
Vector<String> vec = new Vector<String>();
vec.addElement("Hello");
vec.addElement("World");
vec.insertElementAt("Java", 1); // vec is ["Hello", "Java", "World"]

12. Explain the wrapper class methods String() , valueOf() and parsing methods with syntax and
example.
Here are the explanations of the three wrapper class methods you mentioned:
1. `String()`: This method creates a new string object with the specified value. For example:
String str = new String("Hello, World!");
2. `valueOf()`: This method returns a string representation of the specified value. For example:
int num = 42;
String str = String.valueOf(num); // str is "42"
3. Parsing methods: These methods convert a string representation of a value to the corresponding
primitive data type. There are several parsing methods available for each primitive data type:
- `Byte.parseByte()`: Parses a string to a byte.
- `Short.parseShort()`: Parses a string to a short.
- `Integer.parseInt()`: Parses a string to an int.
- `Long.parseLong()`: Parses a string to a long.
- `Float.parseFloat()`: Parses a string to a float.
- `Double.parseDouble()`: Parses a string to a double.
- `Boolean.parseBoolean()`: Parses a string to a boolean.
For example:
String str = "42";
int num = Integer.parseInt(str); // num is 42

13. Write the general form of a class? Explain how to define a class in Java with suitable example.
The General Form of a Class
A class is declared by use of the class keyword.
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class are called members of the class.
14. Explain how to create an object in Java with suitable example.

15. Explain the use of Constructors with suitable example.


REFER 2 marks 14th question
16. Explain command line arguments in Java with example.

17. Explain how to pass objects to methods with suitable example.


Using Objects as Parameters
So far, we have only been using simple types as parameters to methods. However, it is both correct
and common to pass objects to methods.

18. Explain how to return an object from a method with suitable example
In Java, you can return an object from a method by specifying the return type of the method as the
class of the object. For example:

// Define a class
class Person {
String name;
int age;
}
// Define a method that returns an object of the class
public static Person createPerson(String name, int age) {
Person person = new Person();
person.name = name;
person.age = age;
return person;
}
// Call the method and get the returned object
Person person = createPerson("John", 30);
In this example, we define a class called `Person` with two fields: `name` and `age`. We then define
a method called `createPerson` that takes two parameters (`name` and `age`) and returns an object
of the `Person` class. Inside the method, we create a new `Person` object, set its fields to the values
of the parameters, and return it.
We can then call the `createPerson` method and get the returned `Person` object.

19. Explain method overloading with suitable example.

20. What is recursion? Illustrate recursion with a code example.


21. Explain static variable and methods with suitable example.

class MyClass {
static int count = 0;

public static void incrementCount() {


count++;
}
}
// Call the static method
MyClass.incrementCount();

In this example, we define a class called MyClass with a static variable called count and
a static method called incrementCount. The incrementCount method increments
the value of the count variable. We can then call the incrementCount method without
creating an instance of the MyClass class.
22. Create a class Student with members Register number, name and marks in three subjects.
Use constructors to initialize objects and write a method that displays the information of a
student.
class Student {
int regNo;
String name;
int marks1;
int marks2;
int marks3;
public Student(int regNo, String name, int marks1, int marks2, int marks3) {
this.regNo = regNo;
this.name = name;
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}
public void display() {
System.out.println("Register Number: " + regNo);
System.out.println("Name: " + name);
System.out.println("Marks in Subject 1: " + marks1);
System.out.println("Marks in Subject 2: " + marks2);
System.out.println("Marks in Subject 3: " + marks3);
}
}
// Create an object of the Student class
Student student = new Student(1234, "John Doe", 90, 85, 95);
// Call the display method to display the student's information
student.display();

23. Explain constructor overloading with suitable example


Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods
24. Explain how to pass variable-length arguments with suitable example.

public static void myMethod(int num, String... args) {


System.out.println("Number: " + num);
for (String arg : args) {
System.out.println(arg);
}
}

UNIT III
Questions carrying 2 marks

1. What is inheritance?
Inheritance is another aspect of OOP paradigm.
• The mechanism of deriving a new class from an old one is called Inheritance.
• The old class is known as the BASE CLASS OR SUPER CLASS OR PARENT CLASS.
• The new class derived is called the SUBCLASS OR DERIVED CLASS.
• The inheritance allows subclasses to inherit all the variables and methods of their parent classes.
2. What is the purpose of keyword extends?
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main
{
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // inherited from Animal class
dog.bark();
}
}
3. What is the purpose of super()?
Using Super
The super keyword is similar to this keyword.
Following are the scenarios where the super keyword is used.
• Super is used to invoke the superclass constructor from subclass.
•It is used to differentiate the members of superclass from the members of subclass, if they have
same names. i.e. to access a member of the superclass that has been hidden by a member of a
subclass.
4. What are abstract classes?

5. What are abstract methods?

6. How to prevent methods from overriding?


7. What are final variables?
In Java, a `final` variable is a variable whose value cannot be changed once it has been assigned².
When you declare a variable as `final`, you must initialize it at the time of declaration¹.
Here's an example:
public class Main {
public static void main(String[] args) {
final int x = 10;
// x = 20; // compile-time error
System.out.println(x);
}
}
In the above example, the variable `x` is declared as `final`. This means that its value cannot be
changed once it has been assigned. When we try to change the value of `x`, we get a compile-time
error.
The `final` keyword can also be used with methods and classes. When a method is marked as `final`,
it cannot be overridden by any subclass. When a class is marked as `final`, it cannot be subclassed⁵.

8. What is the purpose of final class?


Using Final with class:
We can also prevent inheritance by making a class final. When a class is declared as final, its
methods also become final. An abstract class cannot be declared as final because an abstract class
is incomplete and its subclasses need to provide the implementation.

9. What are final methods?


REFER 2marks 6th question
10. How to define a package?

11. How to import a package?

12. List any four API packages of Java.

13. What are different methods of creating threads?


14. List different states of a thread.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
15. List any four thread methods.
Start()
yield(),
sleep(),
stop()
16. What is the purpose of notify() and notifyall() method?
The Thread has been told to wait until some event occurs. This is done using the wait( ) method.
The thread can be scheduled to run again using the notify( ) method.

17. Differentiate suspend() and stop() methods of a thread


The `suspend()` method is used to suspend a thread temporarily, which can be restarted by using
the `resume()` method¹². On the other hand, the `stop()` method is used to stop the thread, and it
cannot be restarted again¹. Suspending a thread puts it to sleep indefinitely, while stopping a thread
terminates it

18. What is the purpose of resume() method?


Thread has been suspended using suspend( ) method. A suspended thread can be revived by using
the resume( ) method. This approach is useful when we want to suspend a thread for some time
due to certain reason, but do not want to kill it.

19. What is the purpose of wait() and notify() methods?


Thread has been told to wait until some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.
20. What is the purpose of exception handler?
An exception handler is a block of code that is used to handle exceptions that are thrown
by the program at runtime. It is used to catch and handle exceptions that are thrown by the
program so that the program can continue running without crashing .

21. List any four types of exceptions in Java.

22. What is the purpose of try and catch block?

Questions carrying 4 or more marks


1. Explain single inheritance with suitable example.
•Inheritance is another aspect of OOP paradigm.
• The mechanism of deriving a new class from an old one is called Inheritance.
• The old class is known as the BASE CLASS OR SUPER CLASS OR PARENT CLASS.
Single Inheritance (only one super class).
class Animal
{
public void eat()
{
System.out.println("I can eat");
}
}
class Dog extends Animal
{
public void bark()
{
System.out.println("I can bark");
}
}
public class Main
{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
2. Explain method overriding with suitable example.
3. Explain multi-level inheritance with suitable example
Multilevel Inheritance. (Derived from a derived class)

Multilevel inheritance is a type of inheritance where a subclass inherits properties and methods from
a superclass, which in turn inherits properties and methods from another superclass. In Java, you
can achieve multilevel inheritance by using the `extends` keyword.
Here's an example:
class Animal {
public void eat() {
System.out.println("I can eat");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("I can bark");
}
}
class Labrador extends Dog {
public void color() {
System.out.println("I am brown in color");
}
}
public class Main {
public static void main(String[] args) {
Labrador myLabrador = new Labrador();
myLabrador.eat();
myLabrador.bark();
myLabrador.color();
}
}
In this example, the `Labrador` class inherits the properties and methods of the `Dog` class which
in turn inherits the properties and methods of the `Animal` class. The `Labrador` class has its own
method called `color()` which is not present in the `Animal` or `Dog` classes.
4. Explain the purpose abstract and final classes.
The superclasses are more general than their subclasses. Usually, the superclasses are made
abstract so that the objects of its prototype cannot be made. So the objects of only the subclasses
can be used. To make a class abstract, the keyword abstract is used in the class definition.
The abstract class cannot be instantiated because it does not define a complete implementation.
public abstract class
{
….
}
Using Final with class:
We can also prevent inheritance by making a class final. When a class is declared as final, its
methods also become final. An abstract class cannot be declared as final because an abstract class
is incomplete and its subclasses need to provide the implementation.

5. Explain how to create and use a package in Java with suitable example.
6. List and explain different API packages available in Java.
In Java there are different API packages or System Packages, like
• lang • util • io • awt • Net • applet
The `java.lang` package is one of the most important packages in Java. It contains classes that are
fundamental to the design of the Java programming language. Some of the classes included in this
package are:
1.Object: This is the root class of the Java class hierarchy. All other classes are subclasses of this
class.
2. String: This class represents a sequence of characters.
3. System: This class provides access to system resources such as standard input, standard output,
and error output.
4. Math: This class provides mathematical functions such as trigonometric functions, exponential
functions, and logarithmic functions.
5. Thread: This class provides support for multithreaded programming.
6. Exception: This class is the superclass of all exceptions.
7. RuntimeException: This class is the superclass of all runtime exceptions.

The `java.util` package contains classes that are used for utility purposes such as data structures,
date and time manipulation, and input/output operations. Some of the classes included in this
package are:
1. **ArrayList**: This class provides a resizable array implementation.
2. **LinkedList**: This class provides a linked list implementation.
3. **HashMap**: This class provides a hash table implementation.
4. **Date**: This class represents a specific instant in time.
5. **Calendar**: This class provides methods for manipulating dates and times.
6. **Scanner**: This class provides methods for reading input from various sources.
7. **Random**: This class provides methods for generating random numbers.

The `java.io` package provides classes for performing input and output (I/O) operations in Java.
Some of the classes included in this package are:
1. **File**: This class provides methods for working with files and directories.
2. **InputStream**: This class provides methods for reading input from various sources.
3. **OutputStream**: This class provides methods for writing output to various destinations.
4. **Reader**: This class provides methods for reading character-based input.
5. **Writer**: This class provides methods for writing character-based output.
6. **BufferedReader**: This class provides buffered character input.
7. **BufferedWriter**: This class provides buffered character output.
The `java.awt` package provides classes for creating graphical user interfaces (GUIs) in Java. Some
of the classes included in this package are:
1. **Frame**: This class provides a top-level window for displaying other components.
2. **Button**: This class provides a push button component.
3. **Label**: This class provides a non-editable text display.
4. **TextField**: This class provides a text input component.
5. **TextArea**: This class provides a multi-line text input component.
6. **Checkbox**: This class provides a check box component.
7. **Choice**: This class provides a drop-down list component.

7. Explain how to create and implement interface using suitable example


8. Explain the process of creating a thread by Extended Thread class.
9. Explain the process of creating a thread by implementing Runnable interface with suitable
example.
10. List and explain any five thread methods
11. Explain the life cycle of a Thread with diagram.
REFER 4 marks 10 th question
12. Explain exception handling in Java with suitable example.
13. Illustrate the use of multiple catch statements with suitable example.
public class MultipleCatchExample
{
public static void main(String[] args)
{
Try
{
int[] arr = new int[5];
arr[10] = 50;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds");
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception");
}
catch (Exception e)
{
System.out.println("Something went wrong");
}
}
}
14. Illustrate the use of finally with suitable example.
15. List and explain any 5 built-in exceptions of Java
An ArithmeticException is a type of unchecked exception that occurs when an exceptional
arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of
this class⁴. It is a subclass of RuntimeException and is present in the java.lang package¹.
In Java, the ArithmeticException is thrown when a wrong mathematical expression occurs in a Java
program². It can be defined with zero parameters passed or with one parameter passed².

An ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is


accessed with an illegal index. The index is either negative or greater than or equal to the size of the
array¹. It is one of the most common errors in Java and occurs when a program attempts to access
an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of
the array.

An IndexOutOfBoundsException is a runtime exception in Java that occurs when an index is either


negative or greater than or equal to the size of the array. It is thrown to indicate that an index of
some sort (such as to an array, to a string, or to a vector) is out of range.

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is


made to convert a string with an incorrect format to a numeric value². It is thrown when it is not
possible to convert a string to a numeric type (e.g. int, float)². The NumberFormatException is a
built-in class in java that is defined in the Java.lang.NumberFormatException package¹.

An InterruptedException is thrown when a thread is interrupted while it's waiting, sleeping, or


otherwise occupied². It's a checked exception, and many blocking operations in Java can throw it².
The java.lang.InterruptedException is a checked exception which directly extends
java.lang.Exception¹.

Unit IV

Questions carrying 2 marks


1. What is an Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag
and hosted on a web server. Applets are used to make the website more dynamic and entertaining.
2. List two types of Applets available in Java.

3. What is the purpose of appletviewer?


AppletViewer is a standalone command-line program from Sun to run Java applets¹. Appletviewer
is generally used by developers for testing their applets before deploying them to a website¹. As a
Java developer, it is a preferred option for running Java applets that do not involve the use of a web
browser¹.
4. Write HTML file to run an applet program named Simple.
To run an applet program named Simple, you can write an HTML file that loads the applet¹. Here
is an example of an HTML file that runs an applet named Simple:
<html>
<head>
<title>Simple Applet</title>
</head>
<body>
<applet code="Simple.class" width="300" height="300">
</applet>
</body>
</html>
5. List any two features of Applets
Here are two features of Java applets:
1. Java applets are small Java programs that can be included along with various HTML documents¹.
2. Applets can be placed on a web page and will be executed by the web browser³.

6. What is the purpose of paint() method?

7. List any four methods associated with Applets


1. init( )
2. start( )
3. paint( )
4. stop( )
5. destroy( )
8. What is the purpose of repaint() method?

9. Differentiate stop() and destroy() methods.

10. What is the purpose of update() method.

11. List the superclasses of Applet defined by AWT

12. List any 4 methods defined by Applet.


REFER 2marks 7th question
13. What is an event? Give example.
14. What is the purpose of Event Listener?

15. List the key features of a swing GUI

16. What happens when the constructor JButton(String msg) is called?


When the constructor `JButton(String msg)` is called in Java, it creates a button with the specified
text.
For example, if you call `JButton("Click me!")`, it will create a button with the text "Click me!" on
it¹.
17. What is the purpose of setText() and getText() methods?
The `setText()` and `getText()` methods are used to set and retrieve the text of a component,
respectively.

The `setText()` method is used to set the text of a component. For example, if you have a `JButton`
object named `button`, you can set its text using the following code: `button.setText("Click me!");`.

The `getText()` method is used to retrieve the text of a component. For example, if you have a
`JTextField` object named `textField`, you can retrieve its text using the following code: `String
text = textField.getText();`.
18. List any four swing components.
Here are four Swing components in Java:
- `JButton`: A button that can be clicked by the user.
- `JTextField`: A text field that allows the user to enter text.
- `JLabel`: A component that displays a single line of read-only text.
- `JComboBox`: A drop-down list that allows the user to select one item from a list of items.
19. Differentiate Component and Container.
In Java, a `Component` is an abstract class that represents a graphical user interface (GUI)
component. It is the base class for all AWT components. A `Container`, on the other hand, is a
subclass of `Component` that can contain other components and containers.

In other words, a `Component` is an independent visual control, such as a push button or slider,
while a `Container` holds a group of components. Examples of containers are `JPanel`, `JFrame`,
and `JApplet`. Examples of components are `JLabel`, `JTextField`, and `JButton`.

Questions carrying 4 or more marks

1. Write the complete Applet skeleton with example.

2. List and explain any 6 methods defined by Applet


3. List and explain the components of Delegation Event Model
4. List and explain any three Event Listener Interfaces
5. Explain how any two Mouse events are handled in Applets with suitable example
6. Explain how any two Key events are handled in Applets with suitable example
7. With example explain creating frame window in applet.
8. Explain the purpose of JButton and explain any four methods associated with it.
9. Explain the use of JTextField and any four methods associate with it

10. Explain the use of JList and any for methods associated with it.
11. Illustrate the use of JLabel with suitable example.
12. List and explain different methods associated with JCheckBox.

13. Explain the use of JCombobox and any for methods associated with it.
14. Explain different methods associate with JRadioButton control with suitable example.

15. Explain with example creating a Frame window in Applet.


REFER 4marks 7th question
16. Write a note on Swing Components and Containers.
17. Write and explain a simple swing application program.
This code is a simple Swing application program in Java that creates a window with the title "Simple
Swing Application" and a label that says "Welcome to Swing!" .
Here is an explanation of the code:
import javax.swing.*;

public class SimpleSwingApplication {


public static void main(String[] args) {
JFrame frame = new JFrame("Simple Swing Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Welcome to Swing!");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
- The first line imports the `javax.swing.*` package which contains classes for creating graphical
user interfaces (GUIs) .
- The next line declares a class called `SimpleSwingApplication` .
- The `main()` method is the entry point of the program .
- The first line of the `main()` method creates a new instance of the `JFrame` class with the title
"Simple Swing Application" .
- The second line sets the default close operation for the window to `JFrame.EXIT_ON_CLOSE`,
which means that when the user clicks the close button on the window, the program will exit .
- The third line creates a new instance of the `JLabel` class with the text "Welcome to Swing!" .
- The fourth line adds the label to the content pane of the window .
- The fifth line packs the components in the window so that they are at their preferred size .
- The sixth line makes the window visible .

You might also like