CS8392 Object Oriented Programming MCQ
CS8392 Object Oriented Programming MCQ
1.Which was the first purely object oriented programming language developed?
a)Java
b)C++
c)SmallTalk
d)Kotlin
Answer: c
Explanation: SmallTalk was the first programming language developed which was
purely object oriented. It was developed by Alan Kay. OOP concept came into the
picture in 1970’s.
Answer: c
Explanation: A class is Blueprint of an object which describes/ shows all the functions
and data that are provided by an object of a specific class. It can’t be called as parent or
instance of an object. Class in general describes all the properties of an object.
Answer: a
Explanation: Alan Kay invented OOP, Andrea Ferro was a part of SmallTalk
Development. Dennis invented C++ and Adele Goldberg was in team to develop
SmallTalk but Alan actually had got rewarded for OOP.
Answer: b
Explanation: Member functions are allowed inside a class but were not present in
structure concept. Data members, static data and public access specifiers were present in
structures too.
Answer: c
Explanation: Duplicate/Redundant data is dependent on programmer and hence can’t be
guaranteed by OOP. Code reusability is done using inheritance. Modularity is supported
by using different code files and classes. Codes are more efficient because of features
of OOP.
6.Pure OOP can be implemented without using class in a program. (True or False)
a)True
b)False
Answer: b
Explanation: It’s false because for a program to be pure OO, everything must be
written inside classes. If this rule is violated, the program can’t be labelled as purely
OO.
Answer: d
Explanation: Using inheritance we can reuse the code already written and also can avoid
creation of many new functions or variables, as that can be done one time and be reused,
using classes.
Answer: b
Explanation: Java doesn’t support all 4 types of inheritance. It doesn’t support
multiple inheritance. But the multiple inheritance can be implemented using interfaces
in Java.
Answer: d
Explanation: Any number of classes can be defined inside a program, provided that
2
their names are different. In java, if public class is present then it must have the same
name as that of file.
Answer: a
Explanation: OOP first came into picture in 1970’s by Alan and his team. Later it was
used by some programming languages and got implemented successfully, SmallTalk was
first language to use pure OOP and followed all rules strictly.
3
Answer: a
Explanation: As Java supports usual declaration of data variables, it is partial
implementation of OOP. Because according to rules of OOP, object constructors must be
used, even for declaration of variables.
Answer: b
Explanation: In C++, it’s not necessary to use classes, and hence codes can be written
without using OOP concept. Classes may or may not contain member functions, so it’s
not a necessary condition in C++. And, an object can only be declared in a code if its
class is defined/included via header file.
Answer: d
Explanation: We need not include any specific header file to use OOP concept in C++,
only specific functions used in code need their respective header files to be included or
classes should be defined if needed.
Answer: c
Explanation: Encapsulation and Abstraction are similar features. Encapsulation is
actually binding all the properties in a single class or we can say hiding all the features of
object inside a class. And Abstraction is hiding unwanted data (for user) and showing
only the data required by the user of program.
Answer: a
Explanation: Use of this pointer allows an object to call data and methods of itself
whenever needed. This helps us call the members of an object recursively, and
differentiate the variables of different scopes.
Answer: d
Explanation: It includes hiding the implementation part and showing only the required
data and features to the user. It is done to hide the implementation complexity and details
from the user. And to provide a good interface in programming.
Answer: a
Explanation: It can make programming easy. The programming need not know how the
inbuilt functions are working but can use those complex functions directly in the
program. It doesn’t provide more number of features or better features.
3.Class is abstraction.
a)Object
b)Logical
c)Real
d)Hypothetical
Answer: b
Explanation: Class is logical abstraction because it provides a logical structure for all of
its objects. It gives an overview of the features of an object.
4.Object is abstraction.
a)Object
b)Logical
c)Real
d)Hypothetical
Answer: c
Explanation: Object is real abstraction because it actually contains those features of
class. It is the implementation of overview given by class. Hence the class is logical
abstraction and its object is real.
Answer: c
Explanation: It is to idealize the interface. In this way the programmer can use the
programming features more efficiently and can code better. It can’t increase the program
complexity, as the feature itself is made to hide it.
Answer: a
Explanation: Abstraction applies to both. Control abstraction involves use of
subroutines and control flow abstraction. Data abstraction involves handling pieces of
data in meaningful ways.
7.Which among the following can be viewed as combination of abstraction of data and code.
a)Class
b)Object
c)Inheritance
d)Interfaces
Answer: b
Explanation: Object can be viewed as abstraction of data and code. It uses data
members and their functioning as data abstraction. Code abstraction as use of object of
inbuilt class.
Answer: b
Explanation: Higher the level of abstraction, lower are the details. The best way to
understand this is to consider a whole system that is highest level of abstraction as it
hides everything inside. And next lower level would contain few of the computer
components and so on.
Answer: a
Explanation: Abstraction is hiding the complex code. For example, we directly use cout
object in C++ but we don’t know how is it actually implemented. Encapsulation is data
binding, as in, we try to combine a similar type of data and functions together.
Answer: a
Explanation: Abstraction is called stream to provide a level of complexity hiding, for
how the files operations are actually done. Actual devices are called file because in one
way or another, those can be considered as single entity and there is nothing hidden.
12. If two classes combine some private data members and provides public member
functions to access and manipulate those data members. Where is abstraction used?
a)Using private access specifier for data members
b)Using class concept with both data members and member functions
c)Using public member functions to access and manipulate the data members
d)Data is not sufficient to decide what is being used
Answer: c
Explanation: It is the concept of hiding program complexity and actual working in
background. Hence use of public member functions illustrates abstraction here.
13. A phone is made up of many components like motherboard, camera, sensors and etc.
If the processor represents all the functioning of phone, display shows the display only,
and the phone is represented as a whole. Which among the following have highest level of
abstraction?
a)Motherboard
b)Display
c)Camera
d)Phone
Answer: d
Explanation: Phone as a whole have the highest level of abstraction. This is
because the phone being a single unit represents the whole system. Whereas
motherboard, display and camera are its components.
Answer: c
Explanation: It will make the code safer. One may think it reduces the readability,
but the fact is, it actually helps us understand the code better. We don’t have to read the
complex code which is of no use in understanding the program.
Answer: a
Explanation: An object is instance of its class. It can be declared in the same way that a
variable is declared, only thing is you have to use class name as the data type.
Answer: d
Explanation: You can create as many objects of a specific class as you want, provided enough
memory is available.
Answer: c
Explanation: Objects can be passed by reference. Objects can be passed by value
also. If the object of a class is not created, we can’t use members of that class.
Answer: c
Explanation: The array must be specified with a size. You can’t declare object array, or
any other linear array without specifying its size. It’s a mandatory field.
a)20
b)22
c)24
d)28
Answer: c
Explanation: The size of any object of student class will be of size 4+20=24,
because static members are not really considered as property of a single object. So
static variables size will not be added.
Answer: b
Explanation: Functions can always return an object if the return type is same as that of
object being returned. Care has to be taken while writing the prototype of the function.
Answer: a
Explanation: Using dot operator after the name of object we can access its
members. It is not necessary to use the pointers. We can’t use the names directly
because it may be used outside the class.
9.If a local class is defined in a function, which of the following is true for an object of that
class?
a)Object is accessible outside the function
b)Object can be declared inside any other function
c)Object can be used to call other class members
d)Object can be used/accessed/declared locally in that function
Answer: d
Explanation: For an object which belongs to a local class, it is mandatory to declare and
use the object within the function because the class is accessible locally within the class
only.
10. Which among the following is wrong?
a)class student{ }; student s;
b)abstract class student{ }; student s;
c)abstract class student{ }s[50000000];
d)abstract class student{ }; class toppers: public student{ }; topper t;
Answer: b
Explanation: We can never create instance of an abstract class. Abstract classes doesn’t
have constructors and hence when an instance is created there is no facility to initialize its
members. Option d is correct because topper class is inheriting the base abstract class
student, and hence topper class object can be created easily.
Answer: a
Explanation: A temporary object is created to return the value. It is created
because the object used in function is destroyed as soon as the function is returned.
The temporary variable returns the value and then gets destroyed.
Answer: c
Explanation: Only if the objects are of same class then their data can be copied from to
another using assignment operator. This actually comes under operator overloading. Class
constructors can’t be assigned any explicit value as in option class student{ }s1; class
topper{ }t1; s1=t1; and class student{ }s1; class topper{ }t1; s1.student()=s2.topper();.
14. Which among following is correct for initializing the class below?
class
student{ i
nt marks;
int cgpa;
public: student(int i,
int j){ marks=I;
cgpa=j
}
};
Answer: b
Explanation: It is the way we can initialize the data members for an object array using
parameterized constructor. We can do this to pass our own intended values to initialize the
object array data.
15. Object can’t be used with pointers because they belong to user defined class, and
compiler can’t decide the type of data may be used inside the class.
a)True
b)False
Answer: b
Explanation: The explanation given is wrong because object can always be used with
pointers like with any other variables. Compiler doesn’t have to know the structure of
the class to use a pointer because the pointers only points to a memory address/stores
that address.
2.Class is pass by
a)Value
b)Reference
c)Value or Reference, depending on program
d)Copy
Answer: b
Explanation: Classes are pass by reference, and the structures are pass by copy. It doesn’t
depend on the program.
3.What is default access specifier for data members or member functions declared within
a class without any specifier, in C++?
a)Private
b)Protected
c)Public
d)Depends on compiler
Answer: a
Explanation: The data members and member functions are Private by default in C+
+ classes, if none of the access specifier is used. It is actually made to increase the
privacy of data.
Answer: a
Explanation: Same variable can’t be defined twice in same scope. Even if the data types
are different, variable name must be different. There is no rule like Public member should
come first or last.
6.Size of a class is
a)Sum of the size of all the variables declared inside the class
b)Sum of the size of all the variables along with inherited variables in the class
c)Size of the largest size of variable
d)Classes doesn’t have any size
Answer: d
Explanation: Classes doesn’t have any size, actually the size of object of the class can be
defined. That is done only when an object is created and its constructor is called.
Answer: d
Explanation: Abstract classes can have member functions with no implementation,
where the inheriting subclasses must implement those functions.
Answer: a
Explanation: A friend class can access all the private members of another class, of which
it is a friend. It is a special class provided to use when you need to reuse the data of a
class but don’t want that class to have those special functions.
Answer: d
Explanation: It depends on the access specifier and the type of inheritance used with
the class, because if the class is inherited then the nested class can be used by subclass
too, provided it’s not of private type.
Answer: a
Explanation: The class containing main function can be inherited and hence the
program can be executed using the derived class names also in java.
11. Which among the following is false, for a member function of a class?
a)All member functions must be defined
b)Member functions can be defined inside or outside the class body
c)Member functions need not be declared inside the class definition
d)Member functions can be made friend to another class using the friend keyword
Answer: c
Explanation: Member functions must be declared inside class body, though the
definition can be given outside the class body. There is no way to declare the member
functions outside the class.
Answer: b
Explanation: Keyword class should come first. Class name should come after keyword
class. Parameterized constructor definition depends on programmer so it can be left
empty also.
Answer: b
Explanation: Class and structure are similar to each other. Only major difference is that a
structure doesn’t have member
functions whereas the class can have both data members and member functions.
Answer: b
Explanation: Class definition must end with a semicolon, not colon. Class can have
only member functions in its body with no data members.
Answer: d
Explanation: Instance of abstract class can’t be created as it will not have any constructor
of its own, hence while creating an instance of class, it can’t initialize the object members.
Actually the class inheriting the abstract class can have its instance because it will have
implementation of all members.
Answer: d
Explanation: It is a way of combining both data members and member functions, which
operate on those data members, into a single unit. We call it a class in OOP generally. This
feature have helped us modify the structures used in C language to be upgraded into class in
C++ and other languages.
2.If data members are private, what can we do to access them from the class object?
a)Create public member functions to access those data members
b)Create private member functions to access those data members
c)Create protected member functions to access those data members
d)Private data members can never be accessed from outside the class
Answer: a
Explanation: We can define public member functions to access those private data members
and get their value for use or alteration. They can’t be accessed directly but is possible to
be access using member functions. This is done to ensure that the private data doesn’t get
modified accidentally.
Answer: b
Explanation: Data member’s data type can be changed without changing any further
code. All the members using that data can continue in the same way without any
modification. Member functions can never change the data type of same class data
members.
Answer: b
Explanation: Data abstraction can be achieved by using encapsulation. We can hide the
operation and structure of actual program from the user and can show only required
information by the user.
Answer: c
Explanation: It is the class which uses both the data members and member functions
being declared inside a single unit. Only data members can be there in structures also.
And the encapsulation can only be illustrated if some data/operations are associated
within class.
Answer: d
Explanation: Immutable classes are used for caching purpose generally. And it can be
created by making the class as final and making all its members private.
Answer: a
Explanation: The data prone to change in near future is usually encapsulated so that it
doesn’t get changed accidentally. We encapsulate the data to hide the critical working of
program from outside world.
Answer: a
Explanation: Using access specifiers we can achieve encapsulation. Using this we can in
turn implement data abstraction. It’s not necessary that we only use private access.
9.Which among the following violates the principle of encapsulation almost always?
a)Local variables
b)Global variables
c)Public variables
d)Array variables
Answer: b
Explanation: Global variables almost always violates the principles of encapsulation.
Encapsulation says the data should be accessed only by required set of elements. But
global variable is accessible everywhere, also it is most prone to changes. It doesn’t hide
the internal working of program.
10. Which among the following would destroy the encapsulation mechanism if it was
allowed in programming?
a)Using access declaration for private members of base class
b)Using access declaration for public members of base class
c)Using access declaration for local variable of main() function
d)Using access declaration for global variables
Answer: a
Explanation: If using access declaration for private members of base class was allowed
in programming, it would have destroyed whole concept of encapsulation. As if it was
possible, any class which gets inherited privately, would have been able to inherit the
private members of base class, and hence could access each and every member of base
class.
11. Which among the following can be a concept against encapsulation rules?
a)Using function pointers
b)Using char* string pointer to be passed to non-member function
c)Using object array
d)Using any kind of pointer/array address in passing to another function
Answer: d
Explanation: If we use any kind of array or pointer as data member which should not
be changed, but in some case its address is passed to some other function or similar
variable. There are chances to modify its whole data easily. Hence Against
encapsulation.
12. Consider the following code and select the correct option.
class student
{
int marks;
public : int* fun()
{
return &marks;
}
};
main()
{
student s;
int
*ptr=c.fun()
; return 0;
}
Answer: d
Explanation: This code violates the encapsulation. By this code we can get the address of
the private member of the class, hence we can change the value of private member, which
is against the rules.
Answer: a
Explanation: This code maintains encapsulation. Here the private member is kept
private. Outside code can’t access the private members of class. Only objects of this
class will be able to access the public member function at maximum.
14. Encapsulation is the way to add functions in a user defined structure.
a)True
b)False
Answer: b
Explanation: False, because we can’t call these structures if member functions are
involved, it must be called class. Also, it is not just about adding functions, it’s about
binding data and functions together.
Answer: b
Explanation: The encapsulation can only ensure data security to some extent. If pointer
and addresses are misused, it may violate encapsulation. Use of global variables also
makes the program vulnerable, hence we can’t say that encapsulation gives pure security.
Answer: d
Explanation: It can only be indicated by using the data and functions that we use in
derived class, being provided by parent class. Copying code is nowhere similar to this
concept, also using the code already written is same as copying. Using already defined
functions is not inheritance as we are not adding any of our own features.
Answer: a
Explanation: There are basically 4 types of inheritance provided in OOP, namely, single
level, multilevel, multiple and hierarchical inheritance. We can add one more type as Hybrid
inheritance but that is actually the combination any types of inheritance from the 4 basic
ones.
Answer: b
Explanation: A class inheriting a base class defines single level inheritance. Inheriting
an already derived class makes it multilevel inheritance. And if base class is inherited by
2 other classes, it is multiple inheritance.
Answer: a
Explanation: Class topper is getting derived from 2 other classes and hence it is multiple
inheritance. Topper inherits class
stream and class student publicly and hence can use its features. If only few classes are
defined, there we are not even using inheritance (as in option class student{ }; class
stream{ }; class topper{ };).
Answer: d
Explanation: Java doesn’t support multiple inheritance. But that feature can be
implemented by using the interfaces concept. Multiple inheritance is not supported
because of diamond problem and similar issues.
Answer: c
Explanation: One base class can be derived into the other two derived classes or more. If
only one class gets derived by only 2 other classes, it is also hierarchical inheritance, but
it is not a mandatory condition, because any number of derived classes can be there.
Answer: c
Explanation: Firstly, keyword class should come, followed by the derived class name.
Colon is must followed by access in which base class has to be derived, followed by the
base class name. And finally the body of class. Semicolon after the body is also must.
Answer: c
Explanation: When 2 or more classes inherit the same class using multiple inheritance
and then one more class inherits those two base classes, we get a diamond like structure.
Here, ambiguity arises when same function gets derived into 2 base classes and finally
to 3rd level class because same name functions are being inherited.
9.Which access type data gets derived as private member in derived class?
a)Private
b)Public
c)Protected
d)Protected and Private
Answer: a
Explanation: It is a rule, that when a derived class inherits the base class in private
access mode, all the members of base class gets derived as private members of the
derived class.
10. If a base class is inherited in protected access mode then which among the following is
true?
a)Public and Protected members of base class becomes protected members of derived class
b)Only protected members become protected members of derived class
c)Private, Protected and Public all members of base, become private of derived class
d)Only private members of base, become private of derived class
Answer: a
Explanation: As the programming language rules apply, all the public and protected
members of base class becomes protected members of derived class in protected access
mode. It can’t be changed because it would hinder the security of data and may add
vulnerability in the program.
Answer: c
Explanation: Private access specifier is the most secure access mode. It doesn’t allow
members to be inherited. Even Private inheritance can only inherit protected and
public members.
12. While inheriting a class, if no access mode is specified, then which among the
following is true? (in C++)
a)It gets inherited publicly by default
b)It gets inherited protected by default
c)It gets inherited privately by default
d)It is not possible
Answer: c
Explanation: If the access mode is not specified during inheritance, the class is inherited
privately by default. This is to ensure the security of data and to maintain OOP features.
Hence it is not mandatory to specify the access mode if we want the class to be inherited
privately.
Answer: a
Explanation: First the base class constructor is invoked. When we create a derived class
object, the system tries to invoke its constructor but the class is derived so first the base
class must be initialized, hence in turn the base class constructor is invoked before the
derived class constructor.
14. The private members of the base class are visible in derived class but are not accessible
directly.
a)True
b)False
Answer: a
Explanation: Consider that a variable is private in base class and the derived class uses
public inheritance to inherit that class. Now if we also have a global variable of same
name as that of base class private variable, neither the global variable nor the base class
private variable will be accessible from derived class. This is because we can’t have 2
variables with same name in same local scope. Hence the private members are accessible
but not directly.
Answer: d
Explanation: It is not mandatory that you have to make the visibility mode either public or
protected. You can do either of those. That will give you permission to inherit the private
members of base class.
Answer: a
Explanation: It is actually the ability for a message / data to be processed in more than
one form. The word polymorphism indicates many-forms. So if a single entity takes more
than one form, it is known as polymorphism.
2.What do you call the languages that support classes but not polymorphism?
a)Class based language
b)Procedure Oriented language
c)Object-based language
d)If classes are supported, polymorphism will always be supported
Answer: c
Explanation: The languages which support classes but doesn’t support polymorphism, are
known as object-based languages. Polymorphism is such an important feature, that is a
language doesn’t support this feature, it can’t be called as a OOP language.
3.Which among the following is the language which supports classes but not polymorphism?
a)SmallTalk
b)Java
c)C++
d)Ada
Answer: d
Explanation: Ada is the language which supports the concept of classes but doesn’t
support the polymorphism feature. It is an object-based programming language. Note that
it’s not an OOP language.
4.If same message is passed to objects of several different classes and all of those can
respond in a different way, what is this feature called?
a)Inheritance
b)Overloading
c)Polymorphism
d)Overriding
Answer: c
Explanation: The feature defined in question defines polymorphism features. Here the
different objects are capable of responding to the same message in different ways,
hence polymorphism.
Answer: b
Explanation: Only virtual functions among these can show polymorphism. Class
member functions can show polymorphism too but we should be sure that the same
function is being overloaded or is a function of abstract class or something like this,
since we are not sure about all these, we can’t say whether it can show polymorphism
or not.
7.In case of using abstract class or function overloading, which function is supposed to be
called first?
a)Local function
b)Function with highest priority in compiler
c)Global function
d)Function with lowest priority because it might have been halted since long time, because
of low priority
Answer: b
Explanation: Function with highest priority is called. Here, it’s not about the thread
scheduling in CPU, but it focuses on whether the function in local scope is present or not,
or if scope resolution is used in some way, or if the function matches the argument
signature. So all these things define which function has the highest priority to be called in
runtime. Local function could be one of the answer but we can’t say if someone have
used pointer to another function or same function name.
Answer: a
Explanation: Static member functions are not property of any object.
Hence it can’t be considered for overloading/overriding. For
polymorphism, function must be property of object, not only of class.
Answer: c
Explanation: Only insertion operator can be overloaded among all the given options.
And the polymorphism can be illustrated here only if any of these is applicable of
being overloaded. Overloading is type of polymorphism.
Answer: a
Explanation: Notice that the function name in derived class is different from the function
name in base class. Hence when we call the disp() function, base class function is
executed. No polymorphism is used here.
13. Which problem may arise if we use abstract class functions for polymorphism?
a)All classes are converted as abstract class
b)Derived class must be of abstract type
c)All the derived classes must implement the undefined functions
d)Derived classes can’t redefine the function
Answer: c
Explanation: The undefined functions must be defined is a problem, because one may need
to implement few undefined
functions from abstract class, but he will have to define each of the functions declared in
abstract class. Being useless task, it is a problem sometimes.
Answer: d
Explanation: It never increases function definition overhead, one way or another if you
don’t use polymorphism, you will use the definition in some other way, so it actually
helps to write efficient codes.
15. If 2 classes derive one base class and redefine a function of base class, also overload
some operators inside class body. Among these two things of function and operator
overloading, where is polymorphism used?
a)Function overloading only
b)Operator overloading only
c)Both of these are using polymorphism
d)Either function overloading or operator overloading because polymorphism can be applied
only once in a program
Answer: d
Explanation: Both of them are using polymorphism. It is not necessary that
polymorphism can be used only once in a program, it can be used anywhere, any
number of times in a single program.
Answer: d
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation,
Polymorphism and Abstraction.
Answer: a
Explanation: There are two types of polymorphism in Java. Compile time
polymorphism (overloading) and runtime polymorphism (overriding).
Answer: b
Explanation: Overloading is determined at compile time. Hence, it is also known as compile
time polymorphism.
Answer: d
Explanation: Overloading occurs when more than one method with same name but different
constructor and also when
same signature but different number of parameters and/or parameter type.
5.Which concept of Java is a way of converting real world objects in terms of class?
a)Polymorphism
b)Encapsulation
c)Abstraction
d)Inheritance
Answer: c
Explanation: Abstraction is the concept of defining real world objects in terms of classes or
interfaces.
6.Which concept of Java is achieved by combining methods and attribute into a class?
a)Encapsulation
b)Inheritance
c)Polymorphism
d)Abstraction
Answer: a
Explanation: Encapsulation is implemented by combining methods and attribute
into a class. The class acts like a container of encapsulating properties.
7.What is it called if an object has its own lifecycle and there is no owner?
a)Aggregation
b)Composition
c)Encapsulation
d)Association
Answer: d
Explanation: It is a relationship where all objects have their own lifecycle and there is no
owner. This occurs where many to many relationships are available, instead of one to one
or one to many.
8.What is it called where child object gets killed if parent object is killed?
a)Aggregation
b)Composition
c)Encapsulation
d)Association
Answer: b
Explanation: Composition occurs when child object gets killed if parent object gets
killed. Aggregation is also known as strong Aggregation.
9.What is it called where object has its own lifecycle and child object cannot belong to
another parent object?
a)Aggregation
b)Composition
c)Encapsulation
d)Association
Answer: a
Explanation: Aggregation occurs when objects have their own life cycle and child
object can associate with only one parent object.
Answer: a
Explanation: In order for method overriding, method with same signature in both
superclass and subclass is required with same signature. That satisfies both concepts
inheritance and polymorphism.
Answer: b
Explanation: Serialization is not introduced with Java 8. It was introduced with an earlier
version of Java.
Answer: a
Explanation: BooleanSupplier function interface represents supplier of Boolean-valued results.
Answer: d
Explanation: Lambda expression enables us to pass functionality as an argument to
another method, such as what action should be taken when someone clicks a button.
Answer: c
Explanation: Traversing through forEach method of Iterable with anonymous class.
1. StringList.forEach(new Consumer<Integer>()
2. {
3. public void accept(Integer t)
4. {
5. }
6. });
7. //Traversing with Consumer interface implementation
8. MyConsumer action = new MyConsumer();
9. StringList.forEach(action);
10. }
11. }
6.Which feature of java 8 enables us to create a work stealing thread pool using all available
processors at its target?
a)workPool
b)newWorkStealingPool
c)threadPool
d)workThreadPool
Answer: b
Explanation: Executors newWorkStealingPool() method to create a work-stealing
thread pool using all available processors as its target parallelism level.
Answer: b
Explanation: Files.lines(Path path) that reads all lines from a file as a Stream.
Answer: c
Explanation: Optional object is used to represent null with absent value. This class has
various utility methods to facilitate code to handle values as ‘available’ or ‘not available’
instead of checking null values.
Answer: a
Explanation: Nashorn provides 2 to 10 times faster in terms of performance, as it
directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses
invoke dynamic feature.
10. What does SAM stand for in the context of Functional Interface?
a)Single Ambivalue Method
b)Single Abstract Method
c)Simple Active Markup
d)Simple Abstract Markup
Answer: b
Explanation: SAM Interface stands for Single Abstract Method Interface. Functional
Interface is also known as SAM Interface because it contains only one abstract
method.
Answer: c
Explanation: Java application uses ProcessBuilder object to create a new process. By
default, same set of environment variables passed which are set in application’s virtual
machine process.
Answer: b
Explanation: Java system properties are only used and accessible by the processes they are
added.
Answer: a
Explanation: Java system properties can be set at runtime using
System.setProperty(name, value) or using System.getProperties().load()
methods.
Answer: c
Explanation: java.home is the installation directory of Java Runtime Environment.
Answer: d
Explanation: System.getProperty(“variable”) returns null value. Because, variable is not
a property and if property does not exist, this method returns null value.
Answer: c
Explanation: The changes made by the setProperties method are not persistent. Hence, it
does not affect future invocation.
Answer: d
Explanation:
@Autowired
private Environment env;
This is how environment variables are injected in the class where they can be used.
@Value("$
{my.property}")
private String
prop;
b)
@Property("$
{my.property}")
c)
@Environment("$
{my.property}") private
String prop;
d)
@Env("$
{my.property}")
private String
prop; Answer: a
Explanation: @Value are used to inject the properties and assign them to variables.
Answer: b
Explanation: JAVA_HOME is used to store a path to the java installation.
Answer: b
Explanation: JDK is a core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program.
2.Which component is responsible for converting bytecode into machine specific code?
a)JVM
b)JDK
c)JIT
d)JRE
Answer: a
Explanation: JVM is responsible to converting bytecode to the machine specific code.
JVM is also platform dependent and provides core java functions like garbage
collection, memory management, security etc.
Answer: d
Explanation: JRE is the implementation of JVM, it provides platform to execute java
programs.
Answer: c
Explanation: JIT optimizes bytecode to machine specific language code by compiling
similar bytecodes at the same time. This reduces overall time taken for compilation of
bytecode to machine specific language.
Answer: a
Explanation: Java is called ‘Platform Independent Language’ as it primarily works on
the principle of ‘compile once, run everywhere’.
Answer: c
Explanation: main method cannot be private as it is invoked by external method.
Other identifier are valid with main method.
7.What is the extension of java code files?
a).class
b).java
c).txt
d).js
Answer: b
Explanation: Java files have .java extension.
9.How can we identify whether a compilation unit is class or interface from a .class file?
a)Java source file header
b)Extension of compilation unit
c)We cannot differentiate between class and interface
d)The class or interface name should be postfixed with unit type
Answer: a
Explanation: The Java source file contains a header that declares the type of class or
interface, its visibility with respect to other classes, its name and any superclass it may
extend, or interface it implements.
Answer: b
Explanation: Interpreters read high level language (interprets it) and execute the
program. Interpreters are normally not passing through byte-code and jit compilation.
This section of our 1000+ Java MCQs focuses on class fundamentals & object declaration in
Java Programming Language.
1.What is the stored in the object obj in following lines of Java code?
box obj;
Answer: b
Explanation: Memory is allocated to an object using new operator. box obj; just declares
a reference to object, no memory is allocated to it hence it points to NULL.
Answer: a
Explanation: None.
Answer: a
Explanation: None.
Answer: c
Explanation: Operator new dynamically allocates memory for an object and returns a
reference to it. This reference is address in memory of the object allocated by new.
Answer: a
Explanation: Every class does not need to have a main() method, there can be only
one main() method which is made public.
1. class main_class
2. {
4. {
5. int x = 9;
6. if (x == 9)
7. {
8. int x = 8;
9. System.out.println(x);
10. }
11. }
12. }
a)9
b)8
c)Compilation error
d)Runtime error
Answer: c
Explanation: Two variables with the same name can’t be
created in a class. output:
$ javac main_class.java
Exception in thread "main" java.lang.Error: Unresolved
compilation problem: Duplicate local variable x
7.Which of the following statements is correct?
a)Public method is accessible to all other classes in the hierarchy
b)Public method is accessible only to subclasses of its parent class
c)Public method can only be called by object of its class
d)Public method can be accessed by calling object of the public class
Answer: a
Explanation: None.
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
10. {
11. box obj = new box();
12. obj.width = 10;
13. obj.height = 2;
14. obj.length = 10;
15. int y = obj.width * obj.height * obj.length;
16. System.out.print(y);
17. }
18. }
a) 12
b) 200
c) 400
d) 100
Answer: b
Explanation:
None. output:
$ javac mainclass.java
$ java
mainclass
200
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
9. public static void main(String args[])
10. {
11. box obj1 = new box();
12. box obj2 = new box();
13. obj1.height = 1;
14. obj1.length = 2;
15. obj1.width = 1;
16. obj2 = obj1;
17. System.out.println(obj2.
height);
18. }
19. }
a)1
b)2
c)Runtime error
d)Garbage value
Answer: a
Explanation: When we assign an object to another object of same type, all the elements
of right side object gets copied to object on left side of equal to, =, operator.
output:
$ javac mainclass.java
$ java
mainclass 1
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
10. {
11. box obj = new box();
12. System.out.println(obj);
13. }
14. }
a)0
b)1
c)Runtime error
d)[email protected] in hexadecimal form
Answer: d
Explanation: When we print object internally toString() will be called to return string into
this format [email protected] in
hexadecimal
form. output:
$ javac mainclass.java
$ java
mainclass
[email
protected]
Answer: a
Explanation: Object of private constructor can only be created within class. Private
constructor is used in singleton pattern.
Answer: c
Explanation: this() and super() cannot be used in a method. This throws compile time error.
Answer: c
Explanation: The constructor cannot have a return type. It should create and return
new objects. Hence it would give a compilation error.
Answer: d
Explanation: Class class provides list of methods for use like getInstance().
Answer: b
Explanation: Constructor returns a new object with variables defined as in the class.
Instance variables are newly created and only one copy of static variables are created.
Answer: b
Explanation: No instance can be created of abstract class. Only pointer can hold instance of
object.
7.What is true about protected constructor?
a)Protected constructor can be called directly
b)Protected constructor can only be called using super()
c)Protected constructor can be used outside package
d)protected constructor can be instantiated even if child is in a different package
Answer: b
Explanation: Protected access modifier means that constructor can be accessed by
child classes of the parent class and classes in the same package.
Answer: d
Explanation: “this” is an important keyword in java. It helps to distinguish between local
variable and variables passed in the method as parameters.
Answer: d
Explanation: The class compiles successfully. But the object creation of that class gives a
compilation error.
Answer: a
Explanation: The constructor cannot have a return type. It should create and return
new object. Hence it would give compilation error.
This section of our 1000+ Java MCQs focuses on overloading methods & argument
passing in Java Programming Language.
1.What is the process of defining two or more methods within same class that have
same name but different parameters declaration?
a)method overloading
b)method overriding
c)method hiding
d)none of the mentioned
Answer: a
Explanation: Two or more methods can have same name as long as their parameters
declaration is different, the methods are said to be overloaded and process is called
method overloading. Method overloading is a way by which Java implements
polymorphism.
Answer: a
Explanation: When we pass an argument by call-by-value a copy of argument is made
into the formal parameter of the subroutine and changes made on parameters of
subroutine have no effect on original argument, they remain the same.
4.What is the process of defining a method in terms of itself, that is a method that calls
itself?
a)Polymorphism
b)Abstraction
c)Encapsulation
d)Recursion
Answer: d
Explanation: None.
1. class San
2. {
3. public void m1 (int i,float f)
4. {
5. System.out.println(" int float method");
6. }
7.
8. public void m1(float f,int i);
9. {
10. System.out.println("float int method");
11. }
12.
13. public static void main(String[]args)
14. {
15. San s=new San();
16. s.m1(20,20);
17. }
18. }
1. class overload
2. {
3. int x;
4. int y;
5. void add(int a)
6. {
7. x = a + 1;
8. }
10. {
11. x = a + 2;
12. }
13. }
15. {
17. {
18. overload obj = new overload();
19. int a = 0;
20. obj.add(6);
21. System.out.println(obj.x);
22. }
23. }
a)5
b)6
c)7
d)8
Answer: c
Explanation:
None. output:
$ javac Overload_methods.java
$ java
Overload_methods
7
1. class overload
2. {
3. int x;
4. int y;
5. void add(int a)
6. {
7. x = a + 1;
8. }
10. {
11. x = a + 2;
12. }
13. }
15. {
17. {
18. overload obj = new overload();
19. int a = 0;
21. System.out.println(obj.x);
22. }
23. }
a)6
b)7
c)8
d)9
Answer: c
Explanation:
None. output:
$ javac Overload_methods.java
$ java
Overload_methods
8
1. class overload
2. {
3. int x;
4. double y;
5. void add(int a , int b)
6. {
7. x = a + b;
8. }
10. {
11. y = c + d;
12. }
13. overload()
14. {
15. this.x = 0;
16. this.y = 0;
17. }
18. }
20. {
22. {
23. overload obj = new overload();
24. int a = 2;
25. double b = 3.2;
26. obj.add(a, a);
27. obj.add(b, b);
28. System.out.println(obj.x + " " + obj.y);
29. }
30. }
a) 6 6
b) 6.4 6.4
c) 6.4 6
d) 4 6.4
Answer: d
Explanation: For obj.add(a,a); ,the function in line number 4 gets executed and value of
x is 4. For the next function call, the function in line number 7 gets executed and value of
y is 6.4
output:
$ javac Overload_methods.java
$ java
Overload_methods
4 6.4
1. class test
2. {
3. int a;
4. int b;
5. void meth(int i , int j)
6. {
7. i *= 2;
8. j /= 2;
9. }
10. }
12. {
14. {
15. test obj = new test();
16. int a = 10;
17. int b = 20;
18. obj.meth(a , b);
19. System.out.println(a + " " + b);
20. }
21. }
a) 10 20
b) 20 10
c) 20 40
d) 40 20
Answer: a
Explanation: Variables a & b are passed by value, copy of their values are made on
formal parameters of function meth() that is i & j. Therefore changes done on i & j are
not reflected back on original arguments. a & b remain 10 & 20 respectively.
output:
$ javac Output.java
$ java
Output 10
20
1. class test
2. {
3. int a;
4. int b;
5. test(int i, int j)
6. {
7. a = i;
8. b = j;
9. }
10. void meth(test o)
11. {
12. o.a *= 2;
13. O.b /= 2;
14. }
15. }
17. {
19. {
20. test obj = new test(10 , 20);
21. obj.meth(obj);
22. System.out.println(obj.a + " " + obj.b);
23. }
24. }
a) 10 20
b) 20 10
c) 20 40
d) 40 20
Answer: b
Explanation: Class objects are always passed by reference, therefore changes done are
reflected back on original arguments. obj.meth(obj) sends object obj as parameter whose
variables a & b are multiplied and divided by 2 respectively by meth() function of class
test. a & b becomes 20 & 10 respectively.
output:
$ javac Output.java
$ java
Output 20
10
This section of our 1000+ Java MCQs focuses on access control of Java Programming
Language.
Answer: b
Explanation: main() method must be specified public as it called by Java run time
system, outside of the program. If no access specifier is used then by default member is
public within its own package & cannot be accessed by Java run time system.
2.Which of these is used to access a member of class before object of that class is created?
a)public
b)private
c)static
d)protected
Answer: c
Explanation: None.
3.Which of these is used as a default for a member of a class if no access specifier is used for
it?
a)private
b)public
c)public, within its own package
d)protected
Answer: a
Explanation: When we pass an argument by call-by-value a copy of argument is made
into the formal parameter of the subroutine and changes made on parameters of
subroutine have no effect on original argument, they remain the same.
4.What is the process by which we can control what parts of a program can access the
members of a class?
a)Polymorphism
b)Abstraction
c)Encapsulation
d)Recursion
Answer: c
Explanation: None.
Answer: c
Explanation: private members of a class can not be inherited by a subclass.
1. class access
2. {
3. public int x;
4. private int y;
5. void cal(int a, int b)
6. {
7. x = a + 1;
8. y = b;
9. }
10. }
12. {
14. {
19. }
a)3 3
b)2 3
c)Runtime Error
d)Compilation Error
Answer: c
Explanation:
None. output:
$ javac access_specifier.java
Exception in thread "main" java.lang.Error: Unresolved
compilation problem: The field access.y is not
visible
1. class access
2. {
3. public int x;
4. private int y;
5. void cal(int a, int b)
6. {
7. x = a + 1;
8. y = b;
9. }
11. {
13. }
14. }
16. {
18. {
23. }
24. }
a)2 3
b)3 3
c)Runtime Error
d)Compilation Error
Answer: b
Explanation:
None. output:
$ javac access_specifier.java
$ java
access_specifier
3 3
1. class static_out
2. {
3. static int x;
4. static int y;
5. void add(int a, int b)
6. {
7. x = a + b;
8. y = x + b;
9. }
10. }
12. {
14. {
15. static_out obj1 = new static_out();
16. static_out obj2 = new static_out();
17. int a = 2;
18. obj1.add(a, a + 1);
19. obj2.add(5, a);
20. System.out.println(obj1.x + " " + obj2.y);
21. }
22. }
a) 7 7.4
b) 6 6.4
c)7 9
d)9 7
Answer: c
Explanation:
None. output:
$ javac static_use.java
$ java
static_use 7
9
9. Which of these access specifier must be used for class so that it can be inherited by
another subclass?
a)public
b)private
c)protected
d)none of the mentioned
Answer: a
Explanation: None.
Answer: b
Explanation: None.
2.Which of these keywords is used to prevent content of a variable from being modified?
a)final
b)last
c)constant
d)static
Answer: a
Explanation: A variable can be declared final, doing so prevents its content from being
modified. Final variables must be initialized when it is declared.
Answer: b
Explanation: static statements are run as soon as class containing then is loaded, prior to
any object declaration.
Answer: d
Explanation: All objects of class share same static variable, when object of a class are
declared, all the objects share same copy of static members, no copy of static variables are
made.
Answer: a
Explanation: None.
Answer: a
Explanation: main() method must be declared static, main() method is called by Java
runtime system before any object of any class exists.
1. class access
2. {
3. public int x;
4. static int y;
5. void cal(int a, int b)
6. {
7. x += a ;
8. y += b;
9. }
10. }
12. {
14. {
15. access obj1 = new access();
16. access obj2 = new access();
17. obj1.x = 0;
18. obj1.y = 0;
20. obj2.x = 0;
23. }
24. }
a)1 2
b)2 3
c)3 2
d)1 5
Answer: d
Explanation:
None. output:
$ javac static_specifier.java
$ java
static_specifier
1 5
8.What will be the output of the following Java program?
1. class access
2. {
3. static int x;
4. void increment()
5. {
6. x++;
7. }
8. }
9. class static_use
10. {
12. {
13. access obj1 = new access();
14. access obj2 = new access();
15. obj1.x = 0;
16. obj1.increment();
17. obj2.increment();
18. System.out.println(obj1.x + " " + obj2.x);
19. }
20. }
a)1 2
b)1 1
c)2 2
d)Compilation Error
Answer: c
Explanation: All objects of class share same static variable, all the objects share same
copy of static members, obj1.x and obj2.x refer to same element of class which has been
incremented twice and its value is 2.
output:
$ javac static_use.java
$ java
static_use 2
2
2. {
3. static int x;
4. static int y;
5. void add(int a , int b)
6. {
7. x = a + b;
8. y = x + b;
9. }
10. }
12. {
14. {
15. static_out obj1 = new static_out();
16. static_out obj2 = new static_out();
17. int a = 2;
18. obj1.add(a, a + 1);
19. obj2.add(5, a);
20. System.out.println(obj1.x + " " + obj2.y);
21. }
22. }
a)7 7
b)6 6
c)7 9
d)9 7
Answer: c
Explanation:
None. output:
$ javac static_use.java
$ java
static_use 7
9
1. class Output
2. {
4. {
9. }
a) 1 2
b) 1 2 3
c) 1 2 3 4
d) 1 2 3 4 5
Answer: b
Explanation: arr.length() is 5, so the loop is
executed for three times. output:
$ javac Output.java
$ java
Output 1
2 3
1. class Output
2. {
4. {
8. }
9. }
a) 10 5
b) 5 10
c) 0 10
d) 0 5
Answer: a
Explanation: Arrays in java are implemented as objects, they contain an attribute that is
length which contains the number of elements that can be stored in the array. Hence
a1.length gives 10 and a2.length gives 5.
output:
$ javac Output.java
$ java
Output 10
5
This Section of our 1000+ Java MCQs focuses on Integer and Floating Datatypes of Java
Programming Language.
Answer: b
Explanation: Short occupies 16 bits in memory. Its range is from -32768 to 32767.
Answer: a
Explanation: Byte occupies 8 bits in memory. Its range is from -128 to 127.
a)1 and 2
b)2 and 3
c)3 and 4
d)All statements are correct
Answer: d
Explanation: Statements (1), (2), (3), and (4) are correct. (1) is correct because when a
floating-point number (a double in this case) is cast to an int, it simply loses the digits
after the decimal. (2) and (4) are correct because a long can be cast into a byte. If the long
is over 127, it loses its most significant (leftmost) bits. (3) actually works, even though a
cast is not necessary, because a long can store a byte.
4.An expression involving byte, int, and literal numbers is promoted to which of these?
a)int
b)long
c)byte
d)float
Answer: a
Explanation: An expression involving bytes, ints, shorts, literal numbers, the entire
expression is promoted to int before any calculation is done.
Answer: b
Explanation: Range of float data type is -(3.4e38) To +(3.4e38)
Answer: c
Explanation: None.
1. class average {
2. public static void main(String args[])
3. {
4. double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
5. double result;
6. result = 0;
9. System.out.print(result/6);
10.
11. }
12. }
a) 16.34
b) 16.566666644
c) 16.46666666666667
d) 16.46666666666666
Answer: c
Explanation:
None. output:
$ javac average.java
$ java average
16.46666666666667
1. class output {
2. public static void main(String args[])
3. {
4. double a, b,c;
5. a = 3.0/0;
6. b = 0/4.0;
7. c=0/0.0;
8.
9. System.out.println(a);
10. System.out.println(b);
11. System.out.println(c);
12. }
13. }
a) Infinity
b) 0.0
c)NaN
d)all of the mentioned
Answer: d
Explanation: For floating point literals, we have constant value to represent (10/0.0)
infinity either positive or negative and also have NaN (not a number for undefined like
0/0.0), but for the integral type, we don’t have any constant that’s why we get an
arithmetic exception.
3. {
4. int g = 3;
5. System.out.print(++g * 8);
6. }
7. }
a)25
b)24
c)32
d)33
Answer: c
Explanation: Operator ++ has more preference than *, thus g becomes 4 and
when multiplied by 8 gives 32. output:
$ javac increment.java
$ java
increment 32
1. class area {
2. public static void main(String args[])
3. {
4. double r, pi, a;
5. r = 9.8;
6. pi = 3.14;
7. a = pi * r * r;
8. System.out.println(a);
9. }
10. }
a) 301.5656
b) 301
c) 301.56
d) 301.56560000
Answer: a
Explanation:
None. output:
$ javac area.java
$ java
area
301.5656
This Section of our 1000+ Java MCQs focuses on Character and Boolean Datatypes of Java
Programming Language.
1.What is the numerical range of a char
data type in Java? a) -128 to 127
b) 0 to 256
c) 0 to 32767
d) 0 to 65535
Answer: d
Explanation: Char occupies 16-bit in memory, so it supports 216 i:e from 0 to 65535.
2.Which of these coding types is used for data type characters in Java?
a)ASCII
b)ISO-LATIN-1
c)UNICODE
d)None of the mentioned
Answer: c
Explanation: Unicode defines fully international character set that can represent all
the characters found in all human languages. Its range is from 0 to 65536.
Answer: a
Explanation: Boolean variable can contain only one of two possible values, true and false.
4.Which of these occupy first 0 to 127 in Unicode character set used for characters in Java?
a)ASCII
b)ISO-LATIN-1
c)None of the mentioned
d)ASCII and ISO-LATIN1
Answer: d
Explanation: First 0 to 127 character set in Unicode are same as those of ISO-LATIN-1 and
ASCII.
Answer: c
Explanation: Boolean can only be assigned true or false literals.
1. class array_output {
2. public static void main(String args[])
3. {
8. i++;
9. }
10. }
11. }
a) i i i i i
b) 0 1 2 3 4
c)i j k l m
d)None of the mentioned
Answer: a
Explanation:
None. output:
$ javac array_output.java
$ java
array_output i
i i i i
1. class mainclass {
2. public static void main(String args[])
3. {
4. char a = 'A';
5. a++;
6. System.out.print((int)a);
7. }
8. }
a)66
b)67
c)65
d)64
Answer: a
Explanation: ASCII value of ‘A’ is 65, on using ++ operator character
value increments by one. output:
$ javac mainclass.java
$ java
mainclass 66
1. class mainclass {
2. public static void main(String args[])
3. {
4. boolean var1 = true;
5. boolean var2 = false;
6. if (var1)
7. System.out.println(var1);
8. else
9. System.out.println(var2);
10. }
11. }
a)0
b)1
c)true
d)false
Answer: c
Explanation:
None. output:
$ javac mainclass.java
$ java
mainclass
true
1. class booloperators {
2. public static void main(String args[])
3. {
4. boolean var1 = true;
5. boolean var2 = false;
6. System.out.println((var1 & var2));
7. }
8. }
a)0
b)1
c)true
d)false
Answer: d
Explanation: boolean ‘&’ operator always returns true or false. var1 is defined true and
var2 is defined false hence their ‘&’ operator result is false.
output:
$ javac booloperators.java
$ java
booloperators
false
1. class asciicodes {
2. public static void main(String args[])
3. {
4. char var1 = 'A';
5. char var2 = 'a';
6. System.out.println((int)var1 + " " + (int)var2);
7. }
8. }
a) 162
b) 65 97
c) 67 95
d) 66 98
Answer: b
Explanation: ASCII code for ‘A’ is 65 and
for ‘a’ is 97. output:
$ javac asciicodes.java
$ java
asciicodes
65 97
This section of our 1000+ Java MCQs focuses on control statements of Java Programming
Language.
Answer: b
Explanation: Switch statements checks for equality between the controlling variable and its
constant cases.
Answer: a
Explanation: Continue and break are jump statements, and for is a looping statement.
3.Which of the following loops will execute the body of loop even when condition
controlling the loop is initially false?
a)do-while
b)while
c)for
d)none of the mentioned
Answer: a
Explanation: None.
4.Which of these jump statements can skip processing the remainder of the code in its body
for a particular iteration?
a)break
b)return
c)exit
d)continue
Answer: d
Explanation: None.
5.Which of this statement is incorrect?
a)switch statement is more efficient than a set of nested ifs
b)two case constants in the same switch can have identical values
c)switch statement can only test for equality, whereas if statement can evaluate any type of
boolean expression
d)it is possible to create a nested switch statements
Answer: b
Explanation: No two case constants in the same switch can have identical values.
1. class selection_statements
2. {
4. {
5. int var1 = 5;
6. int var2 = 6;
7. if ((var2 = 1) == var1)
8. System.out.print(var2);
9. else
10. System.out.print(++var2);
11. }
12. }
a)1
b)2
c)3
d)4
Answer: b
Explanation: var2 is initialised to 1. The conditional statement returns false
and the else part gets executed. output:
$ javac selection_statements.java
$ java
selection_statements
2
1. class comma_operator
2. {
4. {
5. int sum = 0;
9. }
10. }
a)5
b)6
c)14
d)compilation error
Answer: b
Explanation: Using comma operator, we can include more than one statement in the
initialization and iteration portion of the for loop. Therefore both ++i and j = i + 1 is
executed i gets the value – 0,1,2,3,4 & j gets the values -0,1,2,3,4,5. output:
$ javac comma_operator.java
$ java
comma_operator
6
1. class jump_statments
2. {
4. {
5. int x = 2;
6. int y = 0;
8. {
9. if (y % x == 0)
10. continue;
11. else if (y == 8)
12. break;
13. else
14. System.out.print(y + " ");
15. }
16. }
17. }
a) 1 3 5 7
b) 2 4 6 8
c) 1 3 5 7 9
d) 1 2 3 4 5 6 7 8 9
Answer: c
Explanation: Whenever y is divisible by x remainder body of loop is skipped by continue
statement, therefore if condition y == 8 is never true as when y is 8, remainder body of
loop is skipped by continue statements of first if. Control comes to print statement only in
cases when y is odd.
output:
$ javac jump_statments.java
$ java
jump_statments
1 3 5 7 9
1. class Output
2. {
3. public static void main(String args[])
4. {
5. final int a=10,b=20;
6. while(a<b)
7. {
8.
9. System.out.println("Hello");
10. }
11. System.out.println("World");
12.
13. }
14. }
a)Hello
b)run time error
c)Hello world
d)compile time error
Answer: d
Explanation: Every final variable is compile time constant.
1. class Output
2. {
4. {
5. int a = 5;
6. int b = 10;
7. first:
8. {
9. second:
10. {
11. third:
12. {
13. if (a == b >> 1)
15. }
16. System.out.println(a);
17. }
18. System.out.println(b);
19. }
20. }
21. }
a) 5 10
b) 10 5
c)5
d)10
Answer: d
Explanation: b >> 1 in if returns 5 which is equal to a i:e 5, therefore body of if is
executed and block second is exited. Control goes to end of the block second executing
the last print statement, printing 10.
output:
$ javac Output.java
$ java
Output 10
This section of our 1000+ Java MCQs focuses on Array Data Structure of Java
Programming Language.
Answer: c
Explanation: Operator new allocates a block of memory specified by the size of an
array, and gives the reference of memory allocated to the array variable.
Answer: d
Explanation: Operator new must be succeeded by array type and array size.
a)0
b)value stored in arr[0]
c) 00000
d) Class [email protected] hashcode in hexadecimal form
Answer: d
Explanation: If we trying to print any reference variable internally, toString() will be
called which is implemented to return the String in following form:
[email protected] in hexadecimal form
Answer: a
Explanation: None.
2. {
4. {
7. {
8. array_variable[i] = i;
9. System.out.print(array_variable[i] + " ");
10. i++;
11. }
12. }
13. }
a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10
Answer: a
Explanation: When an array is declared using new operator then all of its elements are
initialized to 0 automatically. for loop body is executed 5 times as whenever controls
comes in the loop i value is incremented twice, first by i++ in body of loop then by ++i in
increment condition of for loop.
output:
$ javac array_output.java
$ java
array_output 0
2 4 6 8
1. class multidimention_array
2. {
4. {
5. int arr[][] = new int[3][];
6. arr[0] = new int[1];
7. arr[1] = new int[2];
8. arr[2] = new int[3];
9. int sum = 0;
12. arr[i][j] = j + 1;
a)11
b)10
c)13
d)14
Answer: b
Explanation: arr[][] is a 2D array, array has been allotted memory in parts. 1st row
contains 1 element, 2nd row contains 2 elements and 3rd row contains 3 elements. each
element of array is given i + j value in loop. sum contains addition of all the elements of
the array.
output:
$ javac multidimention_array.java
$ java
multidimention_array
10
1. class evaluate
2. {
4. {
6. int n = 6;
7. n = arr[arr[n] / 2];
8. System.out.println(arr[n] / 2);
9. }
10. }
a)3
b)0
c)6
d)1
Answer: d
Explanation: Array arr contains 10 elements. n contains 6 thus in next line n is given
value 3 printing arr[3]/2 i:e 3/2 = 1 because of int Value, by int values there is no rest. If
this values would be float the result would be 1.5.
output:
$ javac evaluate.java
$ java
evaluate 1
1. class array_output
2. {
4. {
5. char array_variable [] = new char[10];
7. {
8. array_variable[i] = 'i';
9. System.out.print(array_variable[i] + "");
10. }
11. }
12. }
a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c)i j k l m n o p q r
d)i i i i i i i i i i
Answer: d
Explanation:
None. output:
$ javac array_output.java
$ java
array_output i
i i i i i i i
i i
1. class array_output
2. {
4. {
6. int sum = 0;
11. }
12. }
a)8
b)9
c)10
d)11
Answer: b
Explanation:
None. output:
$ javac array_output.java
$ java
array_output 9
TOPIC 1.21 PACKAGES
This section of our 1000+ Java MCQs focuses on packages of Java Programming Language.
Answer: c
Explanation: None.
2.Which of these is a mechanism for naming and visibility control of a class and its content?
a)Object
b)Packages
c)Interfaces
d)None of the Mentioned.
Answer: b
Explanation: Packages are both naming and visibility control mechanism. We can define a
class inside a package which is not accessible by code outside the package.
3.Which of this access specifies can be used for a class so that its members can be
accessed by a different class in the same package?
a)Public
b)Protected
c)No Modifier
d)All of the mentioned
Answer: d
Explanation: Either we can use public, protected or we can name the class without any
specifier.
4.Which of these access specifiers can be used for a class so that its members can be
accessed by a different class in the different package?
a)Public
b)Protected
c)Private
d)No Modifier
Answer: a
Explanation: None.
5.Which of the following is the correct way of importing an entire package ‘pkg’?
a)import pkg.
b)Import pkg.
c)import pkg.*
d)Import pkg.*
Answer: c
Explanation: Operator * is used to import the entire package.
Answer: d
Explanation: A package can be renamed only after renaming the directory in which the
classes are stored.
7.Which of the following package stores all the standard java classes?
a)lang
b)java
c)util
d)java.packages
Answer: b
Explanation: None.
1. package pkg;
2. class display
3. {
4. int x;
5. void show()
6. {
7. if (x > 1)
9. }
10. }
12. {
14. {
18. arr[0].x = 0;
19. arr[1].x = 1;
20. arr[2].x = 2;
22. arr[i].show();
23. }
24. }
Answer: c
Explanation:
None.
Output:
$ javac packages.java
$ java
packages 2
1. package pkg;
2. class output
3. {
5. {
6. StringBuffer s1 = new StringBuffer("Hello");
7. s1.setCharAt(1, x);
8. System.out.println(s1);
9. }
10. }
a)xello
b)xxxxx
c)Hxllo
d)Hexlo
Answer: c
Explanation:
None.
Output:
$ javac output.java
$ java
output
Hxllo
1. package pkg;
2. class output
3. {
5. {
6. StringBuffer s1 = new StringBuffer("Hello World");
7. s1.insert(6 , "Good ");
8. System.out.println(s1);
9. }
10. }
Answer: d
Explanation: Since output.class file is not in the directory pkg in which class output is
defined, program will not be able to
run.
outp
ut:
$ javac output.java
$ java output
can not find file output.class
This section of our 1000+ Java MCQs focuses on Inheritance of Java Programming
Language.
Answer: d
Explanation: None.
2.A class member declared protected becomes a member of subclass of which type?
a)public member
b)private member
c)protected member
d)static member
Answer: b
Explanation: A class member declared protected becomes a private member of subclass.
Answer: c
Explanation: None.
a)B,E
b)A,C
c)C,E
d)T,H
Answer: a
Explanation: If one is extending any class, then they should use extends keyword not
implements.
1. class A
2. {
3. int i;
4. void display()
5. {
6. System.out.println(i);
7. }
8. }
9. class B extends A
10. {
11. int j;
12. void display()
13. {
14. System.out.println(j);
15. }
16. }
18. {
19. public static void main(String args[])
20. {
21. B obj = new B();
22. obj.i=1;
23. obj.j=2;
24. obj.display();
25. }
26. }
a)0
b)1
c)2
d)Compilation Error
Answer: c
Explanation: Class A & class B both contain display() method, class B inherits class A,
when display() method is called by object of class B, display() method of class B is
executed rather than that of Class A.
output:
$ javac inheritance_demo.java
$ java
inheritance_demo
2
1. class A
2. {
3. int i;
4. }
5. class B extends A
6. {
7. int j;
8. void display()
9. {
10. super.i = j + 1;
11. System.out.println(j + " " + i);
12. }
13. }
15. {
17. {
18. B obj = new B();
19. obj.i=1;
20. obj.j=2;
21. obj.display();
22. }
23. }
a)2 2
b)3 3
c)2 3
d)3 2
Answer: c
Explanation:
None output:
$ javac inheritance.java
$ java
inheritance 2
3
1. class A
2. {
3. public int i;
4. public int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
13. int a;
14. B()
15. {
16. super();
17. }
18. }
20. {
22. {
23. B obj = new B();
24. System.out.println(obj.i + " " + obj.j)
25. }
26. }
a)1 2
b)2 1
c)Runtime Error
d)Compilation Error
Answer: a
Explanation: Keyword super is used to call constructor of class A by constructor of
class B. Constructor of a initializes i & j to 1 & 2 respectively.
output:
$ javac super_use.java
$ java
super_use 1
2
This section of our 1000+ Java MCQs focuses on Abstract class in Java Programming
Language.
Answer: b
Explanation: None.
Answer: a
Explanation: Thread is not an abstract class.
3.If a class inheriting an abstract class does not define all of its function then it will be
known as?
a)Abstract
b)A simple class
c)Static class
d)None of the mentioned
Answer: a
Explanation: Any subclass of an abstract class must either implement all of the
abstract method in the superclass or be itself declared abstract.
Answer: c
Explanation: Abstract class cannot be directly initiated with new operator, Since
abstract class does not contain any definition of implementation it is not possible to
create an abstract object.
Answer: a
Explanation: None.
6.What will be the output of the following Java code?
1. class A
2. {
3. public int i;
4. private int j;
5. }
6. class B extends A
7. {
8. void display()
9. {
10. super.j = super.i + 1;
11. System.out.println(super.i + " " + super.j);
12. }
13. }
15. {
16. public static void main(String args[])
17. {
18. B obj = new B();
19. obj.i=1;
20. obj.j=2;
21. obj.display();
22. }
23. }
a)2 2
b)3 3
c)Runtime Error
d)Compilation Error
Answer: d
Explanation: Class contains a private member variable j, this cannot be inherited by
subclass B and does not have access to it.
output:
$ javac inheritance.java
Exception in thread "main" java.lang.Error: Unresolved
compilation problem: The field A.j is not visible
7. What will be the output of the following Java code?
1. class A
2. {
3. public int i;
4. public int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
13. int a;
14. B()
15. {
16. super();
17. }
18. }
20. {
22. {
23. B obj = new B();
24. System.out.println(obj.i + " " + obj.j)
25. }
26. }
a)1 2
b)2 1
c)Runtime Error
d)Compilation Error
Answer: a
Explanation: Keyword super is used to call constructor of class A by constructor of
class B. Constructor of a initializes i & j to 1 & 2 respectively.
output:
$ javac super_use.java
$ java
super_use 1
2
8. What will be the output of the following Java code?
1. class A
2. {
3. int i;
4. void display()
5. {
6. System.out.println(i);
7. }
8. }
9. class B extends A
10. {
11. int j;
12. void display()
13. {
14. System.out.println(j);
15. }
16. }
18. {
20. {
21. B obj = new B();
22. obj.i=1;
23. obj.j=2;
24. obj.display();
25. }
26. }
a)0
b)1
c)2
d)Compilation Error
Answer: c
Explanation: class A & class B both contain display() method, class B inherits class A,
when display() method is called by object of class B, display() method of class B is
executed rather than that of Class A.
output:
$ javac method_overriding.java
$ java
method_overriding
2
2. {
3. public int i;
4. protected int j;
5. }
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. super.j = 3;
12. System.out.println(i + " " + j);
13. }
14. }
16. {
18. {
19. B obj = new B();
20. obj.i=1;
21. obj.j=2;
22. obj.display();
23. }
24. }
a)1 2
b)2 1
c)1 3
d)3 1
Answer: a
Explanation: Both class A & B have member with same name that is j, member of class
B will be called by default if no specifier is used. I contains 1 & j contains 2, printing 1
2.
output:
$ javac Output.java
$ java
Output 1
2
This section of our 1000+ Java MCQs focuses on Methods of Java Programming Language.
1.What is the return type of a method that does not return any value?
a)int
b)float
c)void
d)double
Answer: c
Explanation: Return type of a method must be made void if it is not returning any value.
2.What is the process of defining more than one method in a class differentiated by method
signature?
a)Function overriding
b)Function overloading
c)Function doubling
d)None of the mentioned
Answer: b
Explanation: Function overloading is a process of defining more than one method in a
class with same name differentiated by function signature i:e return type or parameters
type and number. Example – int volume(int length, int width) & int volume(int length , int
width , int height) can be used to calculate volume.
3.Which of the following is a method having same name as that of it’s class?
a)finalize
b)delete
c)class
d)constructor
Answer: d
Explanation: A constructor is a method that initializes an object immediately upon
creation. It has the same name as that of class in which it resides.
Answer: a
Explanation: main() method can be defined only once in a program. Program execution
begins from the main() method by java runtime system.
Answer: d
Explanation: All object of class share a single copy of methods defined in a class,
Methods are allotted memory only once. All the objects of the class have access to
methods of that class are allotted memory only for the variables not for the methods.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void volume(int height, int length, int width)
8. {
9. volume = width*height*length;
10. }
11. }
15. {
16. box obj = new box();
17. obj.height = 1;
18. obj.length = 5;
19. obj.width = 5;
20. obj.volume(3,2,1);
21. System.out.println(obj.volume);
22. }
23. }
a)0
b)1
c)6
d)25
Answer: c
Explanation:
None. output:
$ Prameterized_method.java
$
Prameterized_me
thod 6
1. class equality
2. {
3. int x;
4. int y;
5. boolean isequal()
6. {
7. return(x == y);
8. }
9. }
11. {
19. }
a)false
b)true
c)0
d)1
Answer: b
Explanation:
None. output:
$ javac Output.java
$ java
Output
true
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void volume()
8. {
9. volume = width*height*length;
10. }
11. }
13. {
15. {
16. box obj = new box();
17. obj.height = 1;
18. obj.length = 5;
19. obj.width = 5;
20. obj.volume();
21. System.out.println(obj.volume);
22. }
23. }
a)0
b)1
c)25
d)26
Answer: c
Explanation:
None. output:
$ javac Output.java
$ java
Output 25
1. class Output
2. {
3.
4. public static int sum(int ...x)
5. {
6. return;
7. }
9. {
10. sum(10);
11. sum(10,20);
12. sum(10,20,30);
13. sum(10,20,30,40);
14. }
15. }
a)only sum(10)
b)only sum(10,20)
c)only sum(10) & sum(10,20)
d)all of the mentioned
Answer: d
Explanation: sum is a variable argument method and hence it can take any number as an
argument.
1. class area
2. {
3. int width;
4. int length;
5. int volume;
6. area()
7. {
8. width=5;
9. length=6;
10. }
11. void volume()
12. {
14. }
15. }
17. {
19. {
20. area obj = new area();
21. obj.volume();
22. System.out.println(obj.volume);
23. }
24. }
a)0
b)1
c)30
d)error
Answer: d
Explanation: Variable height is
not defined. output:
$ javac cons_method.java
$ java cons_method
error: cannot find symbol height
This section of our 1000+ Java MCQs focuses on interfaces of Java Programming Language.
Answer: a
Explanation: None.
2.Which of these can be used to fully abstract a class from its implementation?
a)Objects
b)Packages
c)Interfaces
d)None of the Mentioned
Answer: c
Explanation: None.
3.Which of these access specifiers can be used for an interface?
a)Public
b)Protected
c)private
d)All of the mentioned
Answer: a
Explanation: Access specifier of an interface is either public or no specifier. When no
access specifier is used then default access specifier is used due to which interface is
available only to other members of the package in which it is declared, when declared
public it can be used by any code.
Answer: c
Explanation: interface is inherited by a class using implements.
5.Which of the following is the correct way of implementing an interface salary by class
manager?
a)class manager extends salary {}
b)class manager implements salary {}
c)class manager imports salary {}
d)none of the mentioned
Answer: b
Explanation: None.
Answer: d
Explanation: All methods and variables are implicitly public if interface is declared public.
1. interface calculate
2. {
4. }
9. {
11. }
12. }
16. {
17. display arr = new display;
18. arr.x = 0;
19. arr.cal(2);
20. System.out.print(arr.x);
21. }
22. }
a)0
b)2
c)4
d)None of the mentioned
Answer: c
Explanation:
None.
Output:
$ javac interfaces.java
$ java
interfaces 4
1. interface calculate
2. {
4. }
6. {
7. int x;
9. {
11. }
12. }
17. {
19. }
20. }
22. {
24. {
25. displayA arr1 = new displayA;
26. displayB arr2 = new displayB;
27. arr1.x = 0;
28. arr2.x = 0;
29. arr1.cal(2);
30. arr2.cal(2);
31. System.out.print(arr1.x + " " + arr2.x);
32. }
33. }
a)0 0
b)2 2
c)4 1
d)1 4
Answer: c
Explanation: class displayA implements the interface calculate by doubling the value of
item, where as class displayB implements the interface by dividing item by item,
therefore variable x of class displayA stores 4 and variable x of class displayB stores 1.
Output:
$ javac interfaces.java
$ java
interfaces 4
1
1. interface calculate
2. {
3. int VAR = 0;
4. void cal(int item);
5. }
6. class display implements calculate
7. {
8. int x;
9. public void cal(int item)
10. {
11. if (item<2)
12. x = VAR;
13. else
14. x = item * item;
15. }
16. }
21. {
23.
24. for(int i=0;i<3;i++)
26. arr[0].cal(0);
27. arr[1].cal(1);
28. arr[2].cal(2);
30. }
31. }
a) 0 1 2
b) 0 2 4
c) 0 0 4
d) 0 1 4
Answer: c
Explanation:
None. output:
$ javac interfaces.java
$ java
interfaces 0
0 4
This section of our 1000+ Java MCQs focuses on Object class of Java Programming
Language.
Answer: b
Explanation: Object class is superclass of every class in Java.
3.Which of these method of Object class is used to obtain class of an object at run time?
a)get()
b)void getclass()
c)Class getclass()
d)None of the mentioned
Answer: c
Explanation: None.
Answer: d
Explanation: Declaring a class final implicitly declared all of its methods final, and makes
the class inheritable.
5.Which of these keywords cannot be used for a class which has been declared final?
a)abstract
b)extends
c)abstract and extends
d)none of the mentioned
Answer: a
Explanation: A abstract class is incomplete by itself and relies upon its subclasses to
provide a complete implementation. If we declare a class final then no class can inherit
that class, an abstract class needs its subclasses hence both final and abstract cannot be
used for a same class.
6.Which of these class relies upon its subclasses for complete implementation of its
methods?
a)Object class
b)abstract class
c)ArrayList class
d)None of the mentioned
Answer: b
Explanation: None.
1. abstract class A
2. {
3. int i;
4. abstract void display();
5. }
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. System.out.println(j);
12. }
13. }
15. {
17. {
18. B obj = new B();
19. obj.j=2;
20. obj.display();
21. }
22. }
a)0
b)2
c)Runtime Error
d)Compilation Error
Answer: b
Explanation: class A is an abstract class, it contains a abstract function display(), the full
implementation of display() method is given in its subclass B, Both the display functions
are the same. Prototype of display() is defined in class A and its implementation is given
in class B.
output:
$ javac Abstract_demo.java
$ java
Abstract_demo 2
1. class A
2. {
3. int i;
4. int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
11. class Output
12. {
13. public static void main(String args[])
14. {
15. A obj1 = new A();
16. A obj2 = new A();
17. System.out.print(obj1.equals(obj2));
18. }
19. }
a)false
b)true
c)1
d)Compilation Error
Answer: a
Explanation: obj1 and obj2 are two different objects. equals() is a method of Object class,
Since Object class is superclass of every class it is available to every object.
output:
$ javac Output.java
$ java
Output
false
1. class Output
2. {
4. {
5. Object obj = new Object();
6. System.out.print(obj.getclass());
7. }
8. }
a)Object
b)class Object
c)class java.lang.Object
d)Compilation Error
Answer: c
Explanation:
None. output:
$ javac Output.java
$ java Output
class java.lang.Object
1. class A
2. {
3. int i;
4. int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
11. class Output
12. {
13. public static void main(String args[])
14. {
15. A obj1 = new A();
16. System.out.print(obj1.toString());
17. }
18. }
a)true
b)false
c)String associated with obj1
d)Compilation Error
Answer: c
Explanation: toString() is method of class Object, since it is superclass of every
class, every object has this method. toString() returns the string associated with the
calling object.
output:
$ javac Output.java
$ java Output
[email protected]
Answer: a
Explanation: If a class is defined inside another class, the inner class is termed as nested
class. The inner class is local to the enclosing class. Scope matters a lot here.
Answer: b
Explanation: Using inheritance we can have the security of the class being
inherited. The subclass can access the members of parent class. And have more
feature than a nested class being used.
Answer: a
Explanation: The nested classes are divided into two main categories. Namely, Static and
non-static. The categories define how the classes can be used inside another class.
4.Non-static nested classes have access to from enclosing class.
a)Private members
b)Protected members
c)Public members
d)All the members
Answer: d
Explanation: The non-static nested class can access all the members of the enclosing
class. All the data members and member functions can be accessed from the nested
class. Even if the members are private, they can be accessed.
Answer: d
Explanation: The static nested class doesn’t have access to any other members of the
enclosing class. This is a rule that is made to ensure that only the data which can be
common to all the object is being accessed by the static nested class.
Answer: d
Explanation: The nested class can be declared with any specifier, unlike the outer
classes which can only be declared public or package private. This is flexibility given
for the nested class being a member of enclosing class.
Answer: a
Explanation: The use of nested class increases encapsulation as the inner class is
getting even more grouped into the enclosing class. Firstly the class encapsulate the
data, having nested classes can increase the encapsulation even further.
Answer: a
Explanation: Like any other member of the class, the static nested class uses the dot
operator to be accessed. The reason behind is, the static classes can’t work with
instances, hence we use enclosing class name to access static nested class.
Answer: a
Explanation: An instance of inner class can exist only within instance of outer class. To
instantiate the inner class, one must instantiate the outer class first. This can be done by
the correct syntax above.
a)
value of x = 55
value of this.x = 0
value of Test.this.x = 1
b)
value of x = 1
value of this.x = 0
value of Test.this.x = 55
c)
value of x = 55
value of this.x = 1
value of Test.this.x = 0
d)
value of x = 0
value of this.x = 55
value of Test.this.x = 1
Answer: c
Explanation: The variable x denotes the parameter of the function. And this.x is the
variable of the inner class. Test.this.x is the variable of the outer class. Hence we get this
output.
Answer: a
Explanation: The class defined inside another class is local to the enclosing class. This
means that the instance of inner class will not be valid outside the enclosing class. There
is no restriction for instance to be private or public always.
14. If a
declaration of a member in inner class has the same name as that in the outer class, then
enclosing scope.
a)Outer declaration shadows inner declaration in
b)Inner declaration shadows outer declaration in
c)Declaration gives compile time error
d)Declaration gives runtime error
Answer: b
Explanation: The inner class will have more preference for its local members than those
of the enclosing members. Hence it will shadow the enclosing class members. This
process is known as shadowing.
Answer: a
Explanation: Top level class encloses the other classes or have same preference as that of
other top level classes. Having a class inside the top level class is indirectly having a top
level class which higher degree of encapsulation.
This section of our 1000+ Java MCQs focuses on ArrayList class of Java Programming
Language.
1.Which of these standard collection classes implements a dynamic array?
a)AbstractList
b)LinkedList
c)ArrayList
d)AbstractSet
Answer: c
Explanation: ArrayList class implements a dynamic array by extending AbstractList class.
2.Which of these class can generate an array which can increase and decrease in size
automatically?
a)ArrayList()
b)DynamicList()
c)LinkedList()
d)MallocList()
Answer: a
Explanation: None.
3.Which of these method can be used to increase the capacity of ArrayList object manually?
a)Capacity()
b)increaseCapacity()
c)increasecapacity()
d)ensureCapacity()
Answer: d
Explanation: When we add an element, the capacity of ArrayList object increases
automatically, but we can increase it manually to specified length x by using function
ensureCapacity(x);
4.Which of these method of ArrayList class is used to obtain present size of an object?
a)size()
b)length()
c)index()
d)capacity()
Answer: a
Explanation: None.
5.Which of these methods can be used to obtain a static array from an ArrayList object?
a)Array()
b)covertArray()
c)toArray()
d)covertoArray()
Answer: c
Explanation: None.
Answer: d
Explanation: trimTosize() is used to reduce the size of the array that underlines an
ArrayList object.
1. import java.util.*;
2. class Arraylist
3. {
5. {
6. ArrayList obj = new ArrayList();
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
11. System.out.println(obj);
12. }
13. }
a)[A, B, C, D]
b)[A, D, B, C]
c)[A, D, C]
d)[A, B, C]
Answer: b
Explanation: obj is an object of class ArrayList hence it is an dynamic array which
can increase and decrease its size. obj.add(“X”) adds to the array element X and
obj.add(1,”X”) adds element x at index position 1 in the list, Hence obj.add(1,”D”)
stores D at index position 1 of obj and shifts the previous value stored at that position
by 1.
Output:
$ javac Arraylist.java
$ java
Arraylist
[A, D, B,
C].
1. import java.util.*;
2. class Output
3. {
5. {
6. ArrayList obj = new ArrayList();
7. obj.add("A");
8. obj.add(0, "B");
9. System.out.println(obj.size());
10. }
11. }
a)0
b)1
c)2
d)Any Garbage Value
Answer: c
Explanation:
None.
Output:
$ javac Output.java
$ java
Output 2
1. import java.util.*;
2. class Output
3. {
5. {
7. obj.add("A");
8. obj.ensureCapacity(3);
9. System.out.println(obj.size());
10. }
11. }
a)1
b)2
c)3
d)4
Answer: a
Explanation: Although obj.ensureCapacity(3); has manually increased the capacity of obj
to 3 but the value is stored only at index 0, therefore obj.size() returns the total number of
elements stored in the obj i:e 1, it has nothing to do with ensureCapacity().
Output:
$ javac Output.java
$ java
Output 1
1. class Output
2. {
4. {
5. ArrayList obj = new ArrayList();
6. obj.add("A");
7. obj.add("D");
8. obj.ensureCapacity(3);
9. obj.trimToSize();
10. System.out.println(obj.size());
11. }
12. }
a)1
b)2
c)3
d)4
Answer: b
Explanation: trimTosize() is used to reduce the size of the array that
underlines an ArrayList object. Output:
$ javac Output.java
$ java
Output 2
1.String in Java is a?
a)class
b)object
c)variable
d)character array
Answer: a
Explanation: None.
2.Which of these method of String class is used to obtain character at specified index?
a)char()
b)Charat()
c)charat()
d)charAt()
Answer: d
Explanation: None.
3.Which of these keywords is used to refer to member of base class from a subclass?
a)upper
b)super
c)this
d)none of the mentioned
Answer: b
Explanation: Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super.
4.Which of these method of String class can be used to test to strings for equality?
a)isequal()
b)isequals()
c)equal()
d)equals()
Answer: d
Explanation: None.
Answer: b
Explanation: Strings in Java are immutable that is they can not be modified.
1. class string_demo
2. {
4. {
7. }
8. }
a)I
b)like
c)Java
d)IlikeJava
Answer: d
Explanation: Java defines an operator +, it is used to
concatenate strings. output:
$ javac string_demo.java
$ java
string_demo
IlikeJava
1. class string_class
2. {
4. {
5. String obj = "I LIKE JAVA";
6. System.out.println(obj.charAt(3));
7. }
8. }
a)I
b)L
c)K
d)E
Answer: a
Explanation: charAt() is a method of class String which gives the character specified by
the index. obj.charAt(3) gives 4th character i:e I.
output:
$ javac string_class.java
$ java
string_class I
1. class string_class
2. {
4. {
5. String obj = "I LIKE JAVA";
6. System.out.println(obj.length());
7. }
8. }
a)9
b)10
c)11
d)12
Answer: c
Explanation:
None. output:
$ javac string_class.java
$ java
string_class
11
2. {
4. {
10. }
11. }
a)hello hello
b)world world
c)hello world
d)world hello
Answer: c
Explanation:
None. output:
$ javac string_class.java
$ java
string_class
hello world
1. class string_class
2. {
4. {
5. String obj = "hello";
6. String obj1 = "world";
7. String obj2 = "hello";
8. System.out.println(obj.equals(obj1) + " " + obj.equals(obj2));
9. }
10. }
a)false false
b)true true
c)true false
d)false true
Answer: d
Explanation: equals() is method of class String, it is used to check equality of two String
objects, if they are equal, true is retuned else false.
output:
$ javac string_class.java
$ java string_class
false true
This section of our 1000+ Java MCQs focuses on exception handling of Java Programming
Language.
Answer: a
Explanation: Exceptions in Java are run-time errors.
Answer: c
Explanation: Exceptional handling is managed via 5 keywords – try, catch, throws, throw and
finally.
Answer: a
Explanation: None.
4.Which of these keywords must be used to handle the exception thrown by try block in
some rational manner?
a)try
b)finally
c)throw
d)catch
Answer: d
Explanation: If an exception occurs within the try block, it is thrown and cached by catch
block for processing.
Answer: c
Explanation: None.
1. class exception_handling
2. {
3. public static void main(String args[])
4. {
5. try
6. {
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.print("World");
12. }
13. }
14. }
a)Hello
b)World
c)HelloWorld
d)Hello World
Answer: b
Explanation: System.ou.print() function first converts the whole parameters into a string
and then prints, before “Hello” goes to output stream 1 / 0 error is encountered which is
cached by catch block printing just “World”.
Output:
$ javac exception_handling.java
$ java
exception_handling
World
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a, b;
8. b = 0;
9. a = 5 / b;
10. System.out.print("A");
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("B");
15. }
16. }
17. }
a)A
b)B
c)Compilation Error
d)Runtime Error
Answer: b
Explanation:
None.
Output:
$ javac exception_handling.java
$ java
exception_handling
B
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a, b;
8. b = 0;
9. a = 5 / b;
10. System.out.print("A");
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("B");
15. }
16. finally
17. {
18. System.out.print("C");
19. }
20. }
21. }
a)A
b)B
c)AC
d)BC
Answer: d
Explanation: finally keyword is used to execute the code before
try and catch block end. Output:
$ javac exception_handling.java
$ java
exception_handling
BC
1. class exception_handling
2. {
4. {
5. try
6. {
7. int i, sum;
8. sum = 10;
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("0");
15. }
16. System.out.print(sum);
17. }
18. }
a)0
b)05
c)Compilation Error
d)Runtime Error
Answer: c
Explanation: Value of variable sum is printed outside of try block, sum is declared only in
try block, outside try block it is undefined.
Output:
$ javac exception_handling.java
Exception in thread "main" java.lang.Error: Unresolved
compilation problem: sum cannot be resolved to a
variable
Answer: c
Explanation: “throw’ keyword is used for throwing exception manually in java program.
User defined exceptions can be thrown too.
2.Which of the following classes can catch all exceptions which cannot be caught?
a)RuntimeException
b)Error
c)Exception
d)ParentException
Answer: b
Explanation: Runtime errors cannot be caught generally. Error class is used to catch such
errors/exceptions.
Answer: d
Explanation: Throwable is built in class and all exception types are subclass of this
class. It is the super class of all exceptions.
4.Which of the following operators is used to generate instance of an exception which can be
thrown using throw?
a)thrown
b)alloc
c)malloc
d)new
Answer: d
Explanation: new operator is used to create instance of an exception. Exceptions may
have parameter as a String or have no parameter.
5.Which of the following keyword is used by calling function to handle exception thrown by
called function?
a)throws
b)throw
c)try
d)catch
Answer: a
Explanation: A method specifies behaviour of being capable of causing exception.
Throws clause in the method declaration guards caller of the method from
exception.
6.Which of the following handles the exception when a catch is not used?
a)finally
b)throw handler
c)default handler
d)java run time system
Answer: c
Explanation: Default handler is used to handle all the exceptions if catch is not used to
handle exception. Finally is called in any case.
Answer: a
Explanation: Finally block of the code gets executed regardless exception is caught or
not. File close, database connection close, etc are usually done in finally.
8.Which of the following should be true of the object thrown by a thrown statement?
a)Should be assignable to String type
b)Should be assignable to Exception type
c)Should be assignable to Throwable type
d)Should be assignable to Error type
Answer: c
Explanation: The throw statement should be assignable to the throwable type.
Throwable is the super class of all exceptions.
Answer: b
Explanation: Error is not recoverable at runtime. The control is lost from the application.
This section of our 1000+ Java MCQs focuses on throw, throws & nested try of Java
Programming Language.
Answer: c
Explanation: None.
2.Which of these class is related to all the exceptions that are explicitly thrown?
a)Error
b)Exception
c)Throwable
d)Throw
Answer: c
Explanation: None.
3.Which of these operator is used to generate an instance of an exception than can be thrown
by using throw?
a)new
b)malloc
c)alloc
d)thrown
Answer: a
Explanation: new is used to create an instance of an exception. All of java’s built in
run-time exceptions have two constructors: one with no parameters and one that
takes a string parameter.
4.Which of these keywords is used to by the calling function to guard against the
exception that is thrown by called function?
a)try
b)throw
c)throws
d)catch
Answer: c
Explanation: If a method is capable of causing an exception that it does not handle. It
must specify this behaviour the behaviour so that callers of the method can guard
themselves against that exception. This is done by using throws clause in methods
declaration.
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = args.length;
8. int b = 10 / a;
9. System.out.print(a);
10. try
11. {
12. if (a == 1)
13. a = a / a - a;
14. if (a == 2)
15. {
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
30. }
a)TypeA
b)TypeB
c)Compile Time Error
d)0TypeB
Answer: c
Explanation: Because we can’t go beyond array limit
1. class exception_handling
2. {
4. {
5. try
6. {
7. System.out.print("A");
8. throw new NullPointerException ("Hello");
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.print("B");
13. }
14. }
15. }
a)A
b)B
c)Hello
d)Runtime Exception
Answer: d
Explanation:
None.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main"
java.lang.NullPointerException: Hello at
exception_handling.main
2. {
3. public static void main(String[] args)
4. {
5. try
6. {
7. return;
8. }
9. finally
10. {
12. }
13. }
14. }
a)Finally
b)Compilation fails
c)The code runs with no output
d)An exception is thrown at runtime
Answer: a
Explanation: Because finally will execute always.
2. {
3. public static void main(String args[])
4. {
5. try
6. {
8. }
9. finally
10. {
11. System.out.println("Finally
executing ");
12. }
13. }
14. }
Answer: d
Explanation: None
This section of our 1000+ Java MCQs focuses on keyword finally and built in exceptions of
Java Programming Language.
Answer: b
Explanation: finally keyword is used to define a set of instructions that will be
executed irrespective of the exception found or not.
Answer: c
Explanation: try block can be followed by any of finally or catch block, try block
checks for exceptions and work is performed by finally and catch block as per the
exception.
Answer: a
Explanation: None.
4.Which of these exceptions will occur if we try to access the index of an array beyond its
length?
a)ArithmeticException
b)ArrayException
c)ArrayIndexException
d)ArrayIndexOutOfBoundsException
Answer: d
Explanation: ArrayIndexOutOfBoundsException is a built in exception that is caused
when we try to access an index location which is beyond the length of an array.
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = args.length;
8. int b = 10 / a;
9. System.out.print(a);
10. }
12. {
13. System.out.println
("1");
14. }
15. }
16. }
1. class exception_handling
2. {
4. {
5. try
6. {
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.print("B");
12. }
13. }
14. }
a)A
b)B
c)Compilation Error
d)Runtime Error
Answer: d
Explanation: Try block is throwing NullPointerException but the catch block is used to
counter Arithmetic Exception. Hence NullPointerException occurs since no catch is
there which can handle it, runtime error occurs.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = 1;
8. int b = 10 / a;
9. try
10. {
11. if (a == 1)
12. a = a / a - a;
13. if (a == 2)
14. {
15. int c[] = {1};
16. c[8] = 9;
17. }
18. }
19. finally
20. {
21. System.out.print("A");
22. }
23. }
25. {
26. System.out.println
("B");
27. }
28. }
29. }
a)A
b)B
c)AB
d)BA
Answer: a
Explanation: The inner try block does not have a catch which can tackle
ArrayIndexOutOfBoundException hence finally is executed which prints ‘A’ the outer try
block does have catch for ArrayIndexOutOfBoundException exception but no such
exception occurs in it hence its catch is never executed and only ‘A’ is printed.
Output:
$ javac exception_handling.java
$ java
exception_handling
A
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = args.length;
8. int b = 10 / a;
9. System.out.print(a);
10. try
11. {
12. if (a == 1)
13. a = a / a - a;
14. if (a == 2)
15. {
16. int []c = {1};
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
Answer: c
Explanation: try without
catch or finally Output:
$ javac exception_handling.java
$ java exception_handling
Main.java:9: error: 'try' without 'catch', 'finally' or resource declarations
Answer: a
Explanation: None.
Answer: b
Explanation: getMessage() returns a description of the exception.
Answer: b
Explanation: None.
Answer: a
Explanation: None.
Answer: a
Explanation: None.
2. {
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
11. }
12. }
14. {
16. {
18. }
20. {
21. try
22. {
23. compute(3);
24. }
25. catch(Myexception e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a)3
b)Exception
c)Runtime Error
d)Compilation Error
Answer: b
Explanation: Myexception is self
defined exception. Output:
$ javac
Output.java
java Output
Exception
2. {
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
10. return "detail";
11. }
12. }
14. {
16. {
18. }
20. {
21. try
22. {
23. compute(3);
24. }
25. catch(DevideByZeroException e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a)3
b)Exception
c)Runtime Error
d)Compilation Error
Answer: c
Explanation: Mexception is self defined exception, we are generating Myexception but
catching DevideByZeroException which causes error.
Output:
$ javac Output.javac
1. class exception_handling
2. {
3. public static void main(String args[])
4. {
5. try
6. {
7. throw new NullPointerException ("Hello");
8. System.out.print("A");
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.print("B");
13. }
14. }
15. }
a)A
b)B
c)Compilation Error
d)Runtime Error
Answer: d
Explanation: try block is throwing NullPointerException but the catch block is used to
counter Arithmetic Exception. Hence NullPointerException occurs since no catch is
there which can handle it, runtime error occurs.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello
2. {
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
10. return "detail";
11. }
12. }
14. {
15. static void compute (int a) throws Myexception
16. {
18. }
21. tr
y
22. {
23. compute(
3);
24. }
25. catch(Exception e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a)3
b)Exception
c)Runtime Error
d)Compilation Error
Answer: b
Explanation: Myexception is self
defined exception. Output:
$ javac
Output.javac
java Output
Exception
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = args.length;
8. int b = 10 / a;
9. System.out.print(a);
10. try
11. {
12. if (a == 1)
13. a = a / a -
a;
14. if (a == 2)
15. {
16. int c =
{1};
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
30. }
Answer: c
Explanation: try without
catch or finally Output:
$ javac exception_handling.java
$ java exception_handling
error: 'try' without 'catch', 'finally' or resource declarations
This section of our 1000+ Java MCQs focuses on creating threads in Java Programming
Language.
Answer: c
Explanation: AWT stands for Abstract Window Toolkit, it is used by applets to interact with
the user.
2.Which of these is used to perform all input & output operations in Java?
a)streams
b)Variables
c)classes
d)Methods
Answer: a
Explanation: Like in any other language, streams are used for input and output operations.
Answer: c
Explanation: Java defines only two types of streams – Byte stream and character stream.
4.Which of these classes are used by Byte streams for input and output operation?
a)InputStream
b)InputOutputStream
c)Reader
d)All of the mentioned
Answer: a
Explanation: Byte stream uses InputStream and OutputStream classes for input and output
operation.
5.Which of these classes are used by character streams for input and output operations?
a)InputStream
b)Writer
c)ReadStream
d)InputOutputStream
Answer: b
Explanation: Character streams uses Writer and Reader classes for input & output
operations.
Answer: d
Explanation: None.
7.What will be the output of the following Java program if input given is ‘abcqfghqbcd’?
1. class Input_Output
2. {
4. {
5. char c;
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
12. }
13. }
a)abcqfgh
b)abc
c)abcq
d)abcqfghq
Answer: c
Explanation:
None.
Output:
$ javac Input_Output.java
$ java
Input_Output
abcq
8. What will be the output of the following Java program if input given is “abc’def/’egh”?
1. class Input_Output
2. {
4. {
5. char c;
6. BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
11. } while(c!='\'');
12. }
13. }
a)abc’
b)abcdef/’
c)abc’def/’egh
d)abcqfghq
Answer: a
Explanation: \’ is used for single quotes that is
for representing ‘ . Output:
$ javac Input_Output.java
$ java
Input_Output
abc'
1. class output
2. {
3. public static void main(String args[])
4. {
5. StringBuffer c = new StringBuffer("Hello");
6. System.out.println(c.length());
7. }
8. }
a)4
b)5
c)6
d)7
Answer: b
Explanation: length() method is used to obtain length of StringBuffer
object, length of “Hello” is 5. Output:
$ javac output.java
$ java
output 5
This section of our 1000+ Java MCQs focuses on character streams of Java Programming
Language.
1.Which of these stream contains the classes which can work on character stream?
a)InputStream
b)OutputStream
c)Character Stream
d)All of the mentioned
Answer: c
Explanation: InputStream & OutputStream classes under byte stream they are not
streams. Character Stream contains all the classes which can work with Unicode.
Answer: a
Explanation: None.
3.Which of these method of FileReader class is used to read characters from a file?
a)read()
b)scanf()
c)get()
d)getInteger()
Answer: a
Explanation: None.
4.Which of these class can be used to implement the input stream that uses a character array
as the source?
a)BufferedReader
b)FileReader
c)CharArrayReader
d)FileArrayReader
Answer: c
Explanation: CharArrayReader is an implementation of an input stream that uses
character array as a source. Here array is the input source.
5.Which of these classes can return more than one character to be returned to input stream?
a)BufferedReader
b)Bufferedwriter
c)PushbachReader
d)CharArrayReader
Answer: c
Explanation: PushbackReader class allows one or more characters to be returned to the
input stream. This allows looking ahead in input stream and performing action
accordingly.
6.What will be the output of the following Java program?
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
6. String obj = "abcdef";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0,length,c,0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
21. {
22. // TODO Auto-generated catch block
23. e.printStackTrace();
24. }
25. }
26. }
a)abc
b)abcd
c)abcde
d)abcdef
Answer: d
Explanation:
None.
Output:
$ javac Chararrayinput.java
$ java
Chararrayinput
abcdef
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
6. String obj = "abcdef";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
21. {
22. // TODO Auto-generated catch block
23. e.printStackTrace();
24. }
25. }
26. }
a)abc
b)abcd
c)abcde
d)abcdef
Answer: a
Explanation:
None.
Output:
$ javac Chararrayinput.java
$ java
Chararrayinput
abc
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdefgh";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
23. // TODO Auto-generated catch block
24. e.printStackTrace();
25. }
26. }
27. }
a)abc
b)abcd
c)abcde
d)none of the mentioned
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string
“abcdefgh” whereas object input2 contains string “bcde”, when
while((i=input1.read())==(j=input2.read())) is executed the starting character of each object
is compared since they are unequal control comes out of loop and nothing is printed on
the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
This section of our 1000+ Java MCQs focuses on reading console inputs in Java
Programming Language.
Answer: a
Explanation: read method throws IOException.
Answer: c
Explanation: None.
3.Which of these class is used to read characters and strings in Java from console?
a)BufferedReader
b)StringReader
c)BufferedStreamReader
d)InputStreamReader
Answer: a
Explanation: None.
Answer: a
Explanation: FileInputStream implements InputStream.
5.What will be the output of the following Java program if input given is “Hello stop
World”?
1. class Input_Output
2. {
4. {
5. string str;
6. BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
7. do
8. {
9. str = (char) obj.readLine();
10. System.out.print(str);
11. } while(!str.equals("strong"));
12. }
13. }
a)Hello
b)Hello stop
c)World
d)Hello stop World
Answer: d
Explanation: “stop” will be able to terminate the do-while loop only when it occurs
singly in a line. “Hello stop World” does not terminate the loop.
Output:
$ javac Input_Output.java
$ java
Input_Output
Hello stop
World
1. class output
2. {
4. {
5. StringBuffer c = new StringBuffer("Hello");
6. StringBuffer c1 = new StringBuffer(" World");
7. c.append(c1);
8. System.out.println(c);
9. }
10. }
a)Hello
b)World
c)Helloworld
d)Hello World
Answer: d
Explanation: append() method of class StringBuffer is used to concatenate the string
representation to the end of invoking string.
Output:
$ javac output.java
$ java
output
Hello
World
1. class output
2. {
4. {
5. StringBuffer s1 = new StringBuffer("Hello");
6. s1.setCharAt(1,x);
7. System.out.println(s1);
8. }
9. }
a)xello
b)xxxxx
c)Hxllo
d)Hexlo
Answer: c
Explanation:
None.
Output:
$ javac output.java
$ java
output
Hxllo
8. What will be the output of the following Java program if input given is “abc’def/’egh”?
1. class Input_Output
2. {
4. {
5. char c;
6. BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
12. }
13. }
a)abc’
b)abcdef/’
c)abc’def/’egh
d)abcqfghq
Answer: a
Explanation: \’ is used for single quotes that is
for representing ‘ . Output:
$ javac Input_Output.java
$ java
Input_Output
abc'
Answer: d
Explanation: print() and println() are defined under the class PrintStream, System.out
is the byte stream used by these methods .
2.Which of these methods can be used to writing console output?
a)print()
b)println()
c)write()
d)all of the mentioned
Answer: d
Explanation: None.
Answer: b
Explanation: Character streams uses Writer and Reader classes for input & output
operations.
Answer: c
Explanation: None.
1. class output
2. {
4. {
5. String a="hello i love java";
6. System.out.println(indexof('i')+" "+indexof('o')+" "+lastIndexof('i')+"
"+lastIndexof('o') ));
7. }
8. }
a) 6 4 6 9
b) 5 4 5 9
c) 7 8 8 9
d) 4 3 6 9
Answer: a
Explanation: indexof(‘c’) and lastIndexof(‘c’) are pre defined function which are used
to get the index of first and last occurrence of
the character pointed by c in the
given array. Output:
$ javac output.java
$ java
output 6
4 6 9
1. class output
2. {
3. public static void main(String args[])
4. {
7. {
8. if(Character.isDigit(c[i]))
9. System.out.println(c[i]" is a digit");
10. if(Character.isWhitespace(c[i]))
11. System.out.println(c[i]" is a Whitespace character");
12. if(Character.isUpperCase(c[i]))
13. System.out.println(c[i]" is an Upper case Letter");
14. if(Character.isUpperCase(c[i]))
15. System.out.println(c[i]" is a lower case Letter");
16. i = i + 3;
17. }
18. }
19. }
a)
b)
c)
d)
0 is a digit
Answer: a
Explanation: Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i])
are the function of library java.lang
they are used to find weather the given character is of specified type or not. They return
true or false i:e Boolean variable. Output:
$ javac output.java
$ java output
a is a lower case Letter
is White space character
7.What will be the output of the following Java program?
1. class output
2. {
4. {
5. StringBuffer s1 = new StringBuffer("Hello");
6. StringBuffer s2 = s1.reverse();
7. System.out.println(s2);
8. }
9. }
a)Hello
b)olleH
c)HelloolleH
d)olleHHello
Answer: b
Explanation: reverse() method reverses all characters. It returns the reversed
object on which it was called. Output:
$ javac output.java
$ java
output
olleH
This section of our 1000+ Java MCQs focuses on reading & writing files in Java
Programming Language.
Answer: b
Explanation: None.
2.Which of these exception is thrown in cases when the file specified for writing is not
found?
a)IOException
b)FileException
c)FileNotFoundException
d)FileInputException
Answer: c
Explanation: In cases when the file specified is not found, then
FileNotFoundException is thrown by java run-time system, earlier versions of java
used to throw IOException but after Java 2.0 they throw FileNotFoundException.
4.Which of these values is returned by read() method is end of file (EOF) is encountered?
a)0
b)1
c)-1
d)Null
Answer: c
Explanation: Each time read() is called, it reads a single byte from the file and returns
the byte as an integer value. read() returns -1 when the end of the file is encountered.
Answer: a
Explanation: Both close() and read() method throw IOException.
Answer: c
Explanation: None.
1. import java.io.*;
2. class filesinputoutput
3. {
5. {
7. System.out.print(obj.available());
8. }
9. }
Answer: c
Explanation: obj.available() returns the
number of bytes. Output:
$ javac filesinputoutput.java
$ java
filesinputoutput
1422
(Output will be different in your case)
1. import java.io.*;
2. public class filesinputoutput
3. {
5. {
10. {
11. int c;
12. while((c = obj1.read()) != -1)
13. {
14. if(i == 0)
15. {
16. System.out.print(Character.toUpperCase((char)c));
17. obj2.write(1);
18. }
19. }
20. System.out.print(obj2);
21. }
22. }
23. }
a)AaBaCa
b)ABCaaa
c)AaaBaaCaa
d)AaBaaCaaa
Answer: d
Explanation:
None.
Output:
$ javac filesinputoutput.java
$ java
filesinputoutput
AaBaaCaaa
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdef";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
21. {
22. e.printStackTra
ce();
23. }
24. }
25. }
a)abc
b)abcd
c)abcd
e
d)abcd
ef
Answer: a
Explanation:
None.
Output:
$ javac Chararrayinput.java
$ java
Chararrayinput
abc
3. {
5. {
6. String obj = "abcdefgh";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
23. e.printStackTrace();
24. }
25. }
26. }
a)abc
b)abcd
c)abcde
d)none of the mentioned
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string
“abcdefgh” whereas object input2 contains string “bcde”, when
while((i=input1.read())==(j=input2.read())) is executed the starting character of each object
is compared since they are unequal control comes out of loop and nothing is printed on
the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
UNIT IV MULTITHREADING AND GENERIC
PROGRAMMING
TOPIC 4.1 MULTITHREADING BASICS
This section of our 1000+ Java MCQs focuses on Basics of multithreading of Java
Programming Language.
Answer: b
Explanation: Multithreaded programming a process in which two or more parts of the same
process run simultaneously.
Answer: c
Explanation: There are two types of multitasking: Process based multitasking and Thread
based multitasking.
Answer: a
Explanation: Java assigns to each thread a priority that determines hoe that thread should
be treated with respect to others. Thread priority is integers that specify relative priority of
one thread to another.
4.What will happen if two thread of the same priority are called to be processed
simultaneously?
a)Anyone will be executed first lexographically
b)Both of them will be executed simultaneously
c)None of them will be executed
d)It is dependent on the operating system
Answer: d
Explanation: In cases where two or more thread with same priority are competing for
CPU cycles, different operating system handle this situation differently. Some execute
them in time sliced manner some depending on the thread they call.
Answer: d
Explanation: Thread exist in several states, a thread can be running, suspended, blocked,
terminated & ready to run.
6.What will be the output of the following Java code?
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a)Thread[5,main]
b)Thread[main,5]
c)Thread[main,0]
d)Thread[main,5,main]
Answer: d
Explanation:
None.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[main,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a)4
b)5
c)0
d)1
Answer: b
Explanation: The output of program is Thread[main,5,main], in this priority assigned
to the thread is 5. It’s the default value. Since we have not named the thread they are
named by the group to they belong i:e main method.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[main,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a)main
b)Thread
c)System
d)None of the mentioned
Answer: a
Explanation: The output of program is Thread[main,5,main], Since we have not explicitly
named the thread they are
named by the group to they belong i:e main method. Hence
they are named ‘main’. Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[main,5,main]
Answer: a
Explanation: Thread is a lightweight and requires less resources to create and exist in
the process. Thread shares the process resources.
Answer: b
Explanation: Daemon thread runs in the background and does not prevent JVM from
terminating. Child of daemon thread is also daemon thread.
Answer: d
Explanation: Thread scheduler decides the priority of the thread execution. This
cannot guarantee that higher priority thread will be executed first, it depends on thread
scheduler implementation that is OS dependent.
Answer: b
Explanation: Time slicing is the process to divide the available CPU time to available
runnable thread.
5.Deadlock is a situation when thread is waiting for other thread to release acquired object.
a)True
b)False
Answer: a
Explanation: Deadlock is java programming situation where one thread waits for an
object lock that is acquired by other thread and vice-versa.
Answer: d
Explanation: start() eventually calls run() method. Start() method creates thread and
calls the code written inside run method.
Answer: a
Explanation: Thread(Runnable a, String str) is a valid constructor for thread. Thread() is
also a valid constructor.
Answer: b
Explanation: notify() wakes up a single thread which is waiting for this object.
10. Which of the following will ensure the thread will be in running state?
a)yield()
b)notify()
c)wait()
d)Thread.killThread()
Answer: c
Explanation: wait() always causes the current thread to go into the object’s wait pool.
Hence, using this in a thread will keep it in running state.
This section of our 1000+ Java MCQs focuses on Thread class of Java Programming
Language.
1.Which of these method of Thread class is used to find out the priority given to a thread?
a)get()
b)ThreadPriority()
c)getPriority()
d)getThreadPriority()
Answer: c
Explanation: None.
2.Which of these method of Thread class is used to Suspend a thread for a period of time?
a)sleep()
b)terminate()
c)suspend()
d)stop()
Answer: a
Explanation: None.
3.Which function of pre defined class Thread is used to check weather current thread being
checked is still running?
a)isAlive()
b)Join()
c)isRunning()
d)Alive()
Answer: a
Explanation:isAlive() function is defined in class Thread, it is used for implementing
multithreading and to check whether the thread called upon is still running or not.
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. t.setName("New Thread");
7. System.out.println(t);
8. }
9. }
a)Thread[5,main]
b)Thread[New Thread,5]
c)Thread[main,5,main]
d)Thread[New Thread,5,main]
Answer: d
Explanation:
None.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[New
Thread,5,main]
5.What is the priority of the thread in output in the following Java program?
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. t.setName("New Thread");
7. System.out.println(t.getName());
8. }
9. }
a)main
b)Thread
c)New Thread
d)Thread[New Thread,5,main]
Answer: c
Explanation: The getName() function is used to obtain the name of the thread, in this
code the name given to thread is ‘New Thread’.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g New Thread
6.What is the name of the thread in output in the following Java program?
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t.getPriority());
7. }
8. }
a)0
b)1
c)4
d)5
Answer: d
Explanation: The default priority given
to a thread is 5. Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g 5
7. What is the name of the thread in output in the following Java program?
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t.isAlive());
7. }
8. }
a)0
b)1
c)true
d)false
Answer: c
Explanation: Thread t is seeded to currently program, hence when you run the program
the thread becomes active & code ‘t.isAlive’ returns true.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g true
This section of our 1000+ Java MCQs focuses on creating threads in Java Programming
Language.
Answer: d
Explanation: None.
Answer: d
Explanation: Polling is a usually implemented by looping in CPU is wastes CPU time,
one thread being executed depends on other thread output and the other thread depends on
the response on the data given to the first thread. In such situation CPU time is wasted, in
Java this is avoided by using methods wait(), notify() and notifyAll().
3.Which of these method is used to tell the calling thread to give up a monitor and go
to sleep until some other thread enters the same monitor?
a)wait()
b)notify()
c)notifyAll()
d)sleep()
Answer: a
Explanation: wait() method is used to tell the calling thread to give up a monitor and go
to sleep until some other thread enters the same monitor. This helps in avoiding polling
and minimizes CPU idle time.
4.Which of these method wakes up the first thread that called wait()?
a)wake()
b)notify()
c)start()
d)notifyAll()
Answer: b
Explanation: None.
Answer: d
Explanation: notifyAll() wakes up all the threads that called wait() on the same object.
The highest priority thread will run first.
Answer: a
Explanation: When two or more threads need to access the same shared resource, they
need some way to ensure that the resource will be used by only one thread at a time, the
process by which this is achieved is called synchronization
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
17. {
19. {
24. obj1.t.wait();
25. System.out.print(obj1.t.isAliv
e());
26. }
27. catch(Exception e)
28. {
29. System.out.print("Main thread
interrupted");
30. }
31. }
32. }
a)true
b)false
c)Main thread interrupted
d)None of the mentioned
Answer: c
Explanation: obj1.t.wait() causes main thread to go out of processing in sleep state
hence causes exception and “Main thread interrupted” is printed.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Main thread
interrupted
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
17. {
19. {
26. }
27. catch(InterruptedException e)
28. {
30. }
31. }
32. }
a)true
b)false
c)Main thread interrupted
d)None of the mentioned
Answer: b
Explanation: Thread.sleep(1000) has caused all the threads to be suspended for some
time, hence onj1.t.isAlive() returns false.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g false
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
19. {
20. newthread obj1 = new newthread("one");
21. newthread obj2 = new newthread("two");
22. try
23. {
24. System.out.print(obj1.t.equals(obj2.t));
25. }
26. catch(Exception e)
27. {
29. }
30. }
31. }
a)true
b)false
c)Main thread interrupted
d)None of the mentioned
Answer: b
Explanation: Both obj1 and obj2 have threads with different name that is “one” and
“two” hence obj1.t.equals(obj2.t) returns false.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g false
2. {
3. Thread t;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
20. {
22. }
23. }
a)true
b)false
c)truetrue
d)falsefalse
Answer: d
Explanation: This program was previously done by using Runnable interface, here we
have used Thread class. This shows both the method are equivalent, we can use any of
them to create a thread.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g falsefalse
1.Which of this method can be used to make the main thread to be executed last among all
the threads?
a)stop()
b)sleep()
c)join()
d)call()
Answer: b
Explanation: By calling sleep() within main(), with long enough delay to ensure that all
child threads terminate prior to the main thread.
2.Which of this method is used to find out that a thread is still running or not?
a)run()
b)Alive()
c)isAlive()
d)checkRun()
Answer: c
Explanation: The isAlive( ) method returns true if the thread upon which it is called
is still running. It returns false otherwise.
Answer: c
Explanation: None.
Answer: c
Explanation: The default value of priority given to a thread is 5 but we can explicitly
change that value between the permitted values 1 & 10, this is done by using the
method setPriority().
Answer: a
Explanation: When two or more threads need to access the same shared resource, they
need some way to ensure that the resource will be used by only one thread at a time, the
process by which this is achieved is called synchronization
2. {
3. newthread()
4. {
5. super("My Thread");
6. start();
7. }
9. {
10. System.out.println(this);
11. }
12. }
16. {
18. }
19. }
a)My Thread
b)Thread[My Thread,5,main]
c)Compilation Error
d)Runtime Error
Answer: b
Explanation: Although we have not created any object of thread class still we can make a
thread pointing to main method, we can refer it by using this.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[My
Thread,5,main].
2. {
3. Thread t;
4. newthread()
5. {
6. t = new Thread(this,"My Thread");
7. t.start();
8. }
10. {
11. try
12. {
13. t.join()
14. System.out.println(t.getName());
15. }
16. catch(Exception e)
17. {
18. System.out.print("Exception");
19. }
20. }
21. }
23. {
25. {
26. new newthread();
27. }
28. }
a)My Thread
b)Thread[My Thread,5,main]
c)Exception
d)Runtime Error
Answer: d
Explanation: join() method of Thread class waits for thread being called to finish or
terminate, but here we have no condition which can terminate the thread, hence code
‘t.join()’ leads to runtime error and nothing will be printed on the screen.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
2. {
3. Thread t;
4. newthread()
5. {
6. t = new Thread(this,"New Thread");
7. t.start();
8. }
10. {
11. System.out.println(t.isAlive());
12. }
13. }
15. {
17. {
19. }
20. }
a)0
b)1
c)true
d)false
Answer: c
Explanation: isAlive() method is used to check whether the thread being called is running
or not, here thread is the main() method which is running till the program is terminated
hence it returns true.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g true
2. {
3. Thread t1,t2;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
18. {
20. {
22. }
23. }
a)true
b)false
c)truetrue
d)falsefalse
Answer: d
Explanation: This program was previously done by using Runnable interface, here we
have used Thread class. This shows both the method are equivalent, we can use any of
them to create a thread.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g falsefalse
TOPIC 4.6 INTER-THREAD COMMUNICATION, DAEMON THREADS, THREAD GROUPS
Answer: b
Explanation: To implement Runnable interface, a class needs only to implement a single
method called run().
Answer: b
Explanation: None.
Answer: d
Explanation: run() method is used to define the code that constitutes the new thread, it
contains the code to be executed. start() method is used to begin execution of the thread
that is execution of run(). run() itself is never used for starting execution of the thread.
2. {
3. Thread t;
4. newthread()
5. {
6. t = new Thread(this,"My Thread");
7. t.start();
8. }
10. {
11. System.out.println(t.getName());
12. }
13. }
14. class multithreaded_programing
15. {
17. {
19. }
20. }
a)My Thread
b)Thread[My Thread,5,main]
c)Compilation Error
d)Runtime Error
Answer: a
Explanation:
None.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g My Thread
2. {
3. Thread t;
4. newthread()
5. {
6. t = new Thread(this,"My Thread");
7. t.start();
8. }
10. {
11. System.out.println(t);
12. }
13. }
15. {
17. {
19. }
20. }
a)My Thread
b)Thread[My Thread,5,main]
c)Compilation Error
d)Runtime Error
Answer: b
Explanation:
None.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[My
Thread,5,main]
2. {
3. Thread t;
4. newthread()
5. {
6. t = new Thread(this,"My Thread");
7. t.start();
8. }
9. }
11. {
13. {
15. }
16. }
a)My Thread
b)Thread[My Thread,5,main]
c)Compilation Error
d)Runtime Error
Answer: c
Explanation: Thread t has been made by using Runnable interface, hence it is necessary
to use inherited abstract method run() method to specify instructions to be implemented
on the thread, since no run() method is used it gives a compilation error.
Output:
$ javac multithreaded_programing.java
The type newthread must implement the inherited abstract method Runnable.run()
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. t.setPriority(Thread.MAX_PRIORITY);
12. System.out.println(t);
13. }
14. }
16. {
18. {
20. }
21. }
a)Thread[New Thread,0,main]
b)Thread[New Thread,1,main]
c)Thread[New Thread,5,main]
d)Thread[New Thread,10,main]
Answer: d
Explanation: Thread t has been made with default priority value 5 but in run method
the priority has been explicitly changed to MAX_PRIORITY of class thread, that is
10 by code ‘t.setPriority(Thread.MAX_PRIORITY);’ using the setPriority function
of thread t.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g Thread[New
Thread,10,main]
2. {
3. Thread t;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
11. public void run()
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
20. {
22. }
23. }
a)true
b)false
c)truetrue
d)falsefalse
Answer: d
Explanation: Threads t1 & t2 are created by class newthread that is implementing
runnable interface, hence both the threads are provided their own run() method
specifying the actions to be taken. When constructor of newthread class is called first
the run() method of t1 executes than the run method of t2 printing 2 times “false” as
both the threads are not equal one is having different priority than other, hence
falsefalse is printed.
Output:
$ javac multithreaded_programing.java
$ java
multithreaded_programin
g falsefalse
1. import java.util.*;
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <String> gs = new
genericstack<String>();
20. gs.push("Hello");
21. System.out.println(gs.pop());
22. }
23. }
a)H
b)Hello
c)Runtime Error
d)Compilation Error
Answer: b
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output
Hello
1. import java.util.*;
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
22. }
23. }
a)0
b)36
c)Runtime Error
d)Compilation Error
Answer: b
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output 36
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <String> gs = new genericstack<String>();
20. gs.push("Hello");
21. System.out.print(gs.pop() + " ");
22. genericstack <Integer> gs = new genericstack<Integer>();
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a)Error
b)Hello
c)36
d)Hello 36
Answer: d
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output
Hello 36
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <Integer> gs = new genericstack<Integer>();
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a)H
b)Hello
c)Runtime Error
d)Compilation Error
Answer: d
Explanation: genericstack’s object gs is defined to contain a string parameter but we
are sending an integer parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output
1. import java.util.*;
2. public class genericstack <E>
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <Integer> gs = new genericstack<Integer>();
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a)H
b)Hello
c)Runtime Error
d)Compilation Error
Answer: d
Explanation: generic stack object gs is defined to contain a string parameter but we
are sending an integer parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output
Answer: a
Explanation: Cannot Overload a Method Where the Formal Parameter Types of Each
Overload Erase to the Same Raw Type.
Answer: c
Explanation: Generic methods are methods that introduce their own type parameters. This
is similar to declaring a generic type, but the type parameter scope is limited to the method
where it is declared. Static and non-static generic methods are allowed, as well as generic
class constructors.
2.Which of these type parameters is used for a generic methods to return and accept any type
of object?
a)K
b)N
c)T
d)V
Answer: c
Explanation: T is used for type, A type variable can be any non-primitive type you
specify: any class type, any interface type, any array type, or even another type variable.
3.Which of these type parameters is used for a generic methods to return and accept a
number?
a)K
b)N
c)T
d)V
Answer: b
Explanation: N is used for Number.
4.Which of these is an correct way of defining
generic method? a) <T1, T2, …, Tn>
name(T1, T2, …, Tn) { /* … */ }
b) public <T1, T2, …, Tn> name<T1, T2, …, Tn> { /* … */ }
c) class <T1, T2, …, Tn> name[T1, T2, …, Tn] { /* … */ }
d) <T1, T2, …, Tn> name{T1, T2, …, Tn} { /* … */ }
Answer: b
Explanation: The syntax for a generic method includes a type parameter, inside angle
brackets, and appears before the method’s return type. For static generic methods, the
type parameter section must appear before the method’s return type.
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <String> gs = new genericstack<String>();
20. gs.push("Hello");
21. System.out.println(gs.pop());
22. }
23. }
a)H
b)Hello
c)Runtime Error
d)Compilation Error
Answer: b
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output
Hello
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <Integer> gs = new genericstack<Integer>();
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a)0
b)36
c)Runtime Error
d)Compilation Error
Answer: b
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output 36
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <String> gs = new genericstack<String>();
20. gs.push("Hello");
21. System.out.print(gs.pop() + " ");
22. genericstack <Integer> gs = new genericstack<Integer>();
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a)Error
b)Hello
c)36
d)Hello 36
Answer: d
Explanation:
None.
Output:
$ javac Output.javac
$ java
Output
Hello 36
Answer: c
Explanation: None.
Answer: c
Explanation: It is not possible to create generic type instances. Example – “E obj = new
E()” will give a compilation error.
Answer: a
Explanation: None.
2. {
4. java.util.List<Box<U>> boxes)
5. {
6. Box<U> box = new Box<>();
7. box.set(u);
8. boxes.add(box);
9. }
11. {
12. int counter = 0;
13. for (Box<U> box: boxes)
14. {
15. U boxContents = box.get();
16. System.out.println("Box #" + counter + " contains [" +
boxContents.toString() + "]");
17. counter++;
18. }
19. }
25. }
26. }
a) 10
b) Box #0 [10]
c)Box contains [10]
d)Box #0 contains [10]
Answer: d
Explanation:
None.
Output:
$ javac Output.java
$ java Output
Box #0 contains [10]
1. import java.util.*;
2. public class genericstack <E>
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
18. {
19. genericstack <String> gs = new genericstack<String>();
20. gs.push("Hello");
21. System.out.print(gs.pop() + " ");
22. genericstack <Integer> gs = new genericstack<Integer>();
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a)Error
b)Hello
c)36
d)Hello 36
Answer: d
Explanation:
None.
Output:
$ javac Output.java
$ java
Output
Hello 36
1. import java.util.*;
2. class Output
3. {
5. {
6. double s = 0.0;
7. for (Number n : list)
8. s += n.doubleValue();
9. return s;
10. }
12. {
13. List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);
14. System.out.println(sumOfList(ld));
15. }
16. }
a) 5.0
b) 7.0
c) 8.0
d) 6.0
Answer: b
Explanation:
None.
Output:
$ javac Output.java
$ java
Output
7.0
1. import java.util.*;
2. class Output
3. {
5. {
6. for (int i = 1; i <= 10; i++)
7. {
8. list.add(i);
9. }
10. }
12. {
13. List<Double> ld = Arrays.asList();
14. addnumbers(10.4);
15. System.out.println("getList(2)");
16. }
17. }
a)1
b)2
c)3
d)6
Answer: a
Explanation:
None.
Output:
$ javac Output.java
$ java
Output 1
1. import java.util.*;
2. public class genericstack <E>
3. {
4. Stack <E> stk = new Stack <E>();
5. public void push(E obj)
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
11. E obj = stk.pop();
12. return obj;
13. }
14. }
16. {
17. public static void main(String args[])
18. {
19. genericstack <Integer> gs = new genericstack<Integer>();
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a)H
b)Hello
c)Runtime Error
d)Compilation Error
Answer: d
Explanation: generic stack object gs is defined to contain a string parameter but we
are sending an integer parameter, which results in compilation error.
Output:
$ javac Output.java
2) Implement the Listener interface and overrides its methods is required to perform
in event handling.
a.True
b.False
ANSWER: True
3) Which is the container that doesn't contain title bar and MenuBars but it can
have other components like button, textfield etc?
a.Window
b.Frame
c.Panel
d.Container
ANSWER: Panel
4) These two ways are used to create a Frame
ANSWER: True
6) Which method is used to set the graphics current color to the specified color in the
graphics class?
a.public abstract void setFont(Font font)
b.public abstract void setColor(Color c)
c.public abstract void drawString(String str, int x, int y)
d.None of the above
7) The Java Foundation Classes (JFC) is a set of GUI components which simplify
the development of desktop applications.
a.True
b.False
ANSWER: True
8) In Graphics class which method is used to draws a rectangle with the specified width
and height?
a.public void drawRect(int x, int y, int width, int height)
b.public abstract void fillRect(int x, int y, int width, int height)
c.public abstract void drawLine(int x1, int y1, int x2, int y2)
d.public abstract void drawOval(int x, int y, int width, int height)
ANSWER: public void drawRect(int x, int y, int width, int height)
9) Which object can be constructed to show any number of choices in the visible
window?
a.Labels
b.Choice
c.List
d.Checkbox
ANSWER: List
10) Which is used to store data and partial results, as well as to perform
dynamic linking, return values for methods, and dispatch exceptions?
a.Window
b.Panel
c.Frame
d.Container
ANSWER: Frame
ANSWER: Button,List,MenuItem
a.setText()
b.getText()
c.All the above
d.None of the above
ANSWER: setText()
13) Which is a component in AWT that can contain another components like buttons,
textfields, labels etc.?
a.Window
b.Container
c.Panel
d.Frame
ANSWER: Container
14) AWT has more powerful components like tables, lists, scroll panes, color chooser,
tabbed pane etc.
a.True
b.False
ANSWER: True
15) Which are passive controls that do not support any interaction with the user?
a.Choice
b.List
c.Labels
d.Checkbox
ANSWER: Labels
ANSWER: 7
17) The following
a)It is lightweight.
b) It supports pluggable look and feel.
c)It follows MVC (Model View
Controller) architecture are the
advantages of .
a.Swing
b.AWT
c.Both A & B
d.None of the above
ANSWER: Swing
18) The ActionListener interface is not used for handling action events.
a.True
b.False
ANSWER: False
19) Which package provides many event classes and Listener interfaces for event
handling?
a.java.awt
b.java.awt.Graphics
c.java.awt.event
d.None of the above
ANSWER: java.awt.event
20) Swing is not a part of JFC (Java Foundation Classes) that is used to create GUI
application
a.True
b.False
ANSWER: False
ANSWER: java.awt.Graphics
ANSWER: True
25) The ActionListener interface is not used for handling action events
a.True
b.False
ANSWER: False