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

OOP questions and answers[1]

The document covers key concepts of Object-Oriented Programming (OOP) in Java, including abstraction, encapsulation, inheritance, polymorphism, exception handling, and the use of strings and arrays. It explains various features such as abstract classes, interfaces, exception types, garbage collection, and the differences between mutable and immutable strings. Additionally, it outlines the syntax and practical applications of these concepts, providing a comprehensive overview of Java programming principles.

Uploaded by

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

OOP questions and answers[1]

The document covers key concepts of Object-Oriented Programming (OOP) in Java, including abstraction, encapsulation, inheritance, polymorphism, exception handling, and the use of strings and arrays. It explains various features such as abstract classes, interfaces, exception types, garbage collection, and the differences between mutable and immutable strings. Additionally, it outlines the syntax and practical applications of these concepts, providing a comprehensive overview of Java programming principles.

Uploaded by

rivinduosada1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

OOP Features II –Abstraction and Encapsulation

● Q: What is abstraction in Java?

○ A: Abstraction is a process of hiding the implementation details and showing only functionality to the user12.

● Q: What are the two ways to achieve abstraction in Java?3

○ A: Abstraction can be achieved with either abstract classes or interfaces4.

● Q: What is an abstract class in Java?

○ A: An abstract class is a class that is declared with the abstract keyword and may have abstract and non-abstract methods5.

● Q: What is an abstract method in Java?

○ A: An abstract method is a method that is declared with the abstract keyword and does not have a body6.

● Q: What is an interface in Java?

○ A: An interface is a blueprint of a class that has static constants and abstract, default, static and private methods7.

● Q: What are the advantages of using interfaces in Java?

○ A: Interfaces can be used to achieve abstraction, multiple inheritance, loose coupling and polymorphism 9.

● Q: What is the difference between abstract classes and interfaces in Java?

○ A: Some differences are: abstract classes can have constructors, non-abstract methods and non-static variables, while interfaces
cannot; abstract classes can extend another class and implement multiple interfaces, while interfaces can only extend another
interface; abstract classes can have protected and default access modifiers, while interfaces can only have public access
modifiers.

● Q: What are default and static methods in interfaces?

○ A: Default methods are methods that have a body and are tagged with the default keyword. Static methods are methods that
have a body and are tagged with the static keyword. Both methods can be invoked without creating an object of the interface.

● Q: What is encapsulation in Java?

○ A: Encapsulation is a process of wrapping code and data together into a single unit and hiding the data from the outside.

● Q: How can we achieve encapsulation in Java?

○ A: We can achieve encapsulation by making the data members of a class private and providing public setter and getter methods
to access and modify them1111.

● Q: What are the benefits of encapsulation in Java?

○ A: Encapsulation can provide data security, data validation, control over the data, ease of testing and maintenance, and
modularity of the code.

● Q: What is the difference between read-only and write-only classes in Java?

○ A: A read-only class is a class that has only getter methods and no setter methods. A write-only class is a class that has only
setter methods and no getter methods.

● Q: What is multiple inheritance in Java?

○ A: Multiple inheritance is a feature that allows a class or an interface to inherit from more than one parent class or interface.

● Q: How can we support multiple inheritance in Java?8

○ A: Multiple inheritance can be supported by using interfaces, as a class can implement multiple interfaces or an interface can
extend multiple interfaces12[12]1313.

● Q: What is the relationship between classes and interfaces in Java?

○ A: A class can extend another class, an interface can extend another interface, but a class can only implement an
interface15[15]1616. A class that implements an interface must provide the implementation for all the abstract methods of the
interface1717.
Exception Handling

• Q: What is an exception?
o A: An exception is an unexpected, unwanted event that disturbs the normal flow of the program 3.
• Q: What is the main objective of exception handling?
o A: The main objective of exception handling is graceful termination of the program 4.
• Q: What are the two types of exceptions in Java?
o A: The two types of exceptions in Java are checked and unchecked exceptions 5.
• Q: What is the difference between checked and unchecked exceptions?
o A: Checked exceptions are those that are checked by the compiler for smooth execution of the program, and must be handled either
by try-catch or throws keyword6. Unchecked exceptions are those that are not checked by the compiler, and are usually caused by
logical errors or runtime conditions7.
• Q: What is the root class of Java exception hierarchy?
o A: The root class of Java exception hierarchy is java.lang.Throwable, which is inherited by two subclasses: Exception and Error8.
• Q: What is the difference between Exception and Error?
o A: Exception is a problem that can be handled by the programmer, and is usually caused by the program logic or input. Error is a
problem that cannot be handled by the programmer, and is usually caused by the lack of system resources or environment issues.
• Q: What is the syntax of try-catch-finally block?9
o A: The syntax of try-catch-finally block is:

try {
// risky code
} catch (Exception e) {
// handling code
} finally {
// cleanup code
}

• Q: What is the use of finally block?


o A: The use of finally block is to execute some important code that must be executed whether exception is handled or not, such as
closing resources or releasing locks13.
• Q: What is the specialty of finally block?
o A: The specialty of finally block is that it will be executed always, irrespective of exception is raised or not raised, and whether
handled or not handled12.
• Q: What is the use of throw keyword?
o A: The use of throw keyword is to explicitly throw an exception, either existing or custom, from the program 1415.
• Q: What is the use of throws keyword?
o A: The use of throws keyword is to declare that a method may throw one or more exceptions, and to delegate the responsibility of
handling them to the caller method16.
• Q: What is a custom exception or user-defined exception?17
o A: A custom exception or user-defined exception is an exception that is created by the programmer to customize the exception
according to the application logic or requirement18.
• Q: How to create a custom exception?
o A: To create a custom exception, we need to define a class that extends from Exception or any of its subclasses, and provide a
constructor that invokes the super class constructor with the exception message.
• Q: What are the methods to print exception information?19
o A: The methods to print exception information are printStackTrace(), toString(), and getMessage(), which are defined in the
Throwable class.
• Q: What is the order of catch blocks when multiple exceptions are handled?
o A: The order of catch blocks when multiple exceptions are handled is from child to parent, that is, from more specific to more
general. Otherwise, we will get a compile time error saying "exception XXX has already been caught" 20.

• Q: What is the difference between final, finally, and finalize in Java? 1


o A: final is a keyword that is used to restrict the user from modifying a variable, method, or class. finally is a block that is
used to place important code, it will be executed whether exception is handled or not finalize is a method that is invoked just
before an object is garbage collected, it is used to perform cleanup activities 2.
• Q: What is the purpose of garbage collection in Java, and when is it used?
o A: Garbage collection is the process of reclaiming the runtime unused memory automatically. It is used to free up memory that is no
longer needed by objects that are not being used by the application anymore.
• Q: What is multithreading in Java?
o A: Multithreading is a feature in Java that allows concurrent execution of two or more parts of a program for maximum utilization
of CPU.
• Q: Can we start a thread twice in Java?
o A: No, once a thread is started, it cannot be started again. If we try to start a thread again, an
IllegalThreadStateException is thrown.
• Q: What are the ways in which you can implement a thread in Java?
o A: There are two ways to implement a thread in Java: by extending the Thread class and by implementing the Runnable
interface.
OOP Features I –Inheritance and Polymorphism

• Q: What is inheritance in Java?1


o A: Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object 23.
• Q: What is polymorphism in Java?
o A: Polymorphism is a concept by which we can perform a single action in different ways4.
• Q: What are the two types of polymorphism in Java?5
o A: The two types of polymorphism in Java are compile-time polymorphism and runtime polymorphism.
• Q: What is the difference between method overloading and method overriding? 6
o A: Method overloading is the concept of having multiple methods with the same name but different parameters, while method overriding is
the concept of having a subclass provide a specific implementation of a method that is already defined by its parent class78.
• Q: What is the use of super keyword in Java?
o A: Super keyword is a reference variable that is used to refer to the immediate parent class object 9. It can be used to invoke parent class
methods, constructors, and variables.
• Q: What is the use of final keyword in Java?
o A: Final keyword can be used to declare a variable, a method, or a class as final. A final variable cannot be changed, a final method cannot
be overridden, and a final class cannot be extended10.
• Q: What is the use of instanceof operator in Java?
o A: Instanceof operator is used to test whether an object is an instance of a specified type (class, subclass, or interface) 11.
• Q: What is static binding and dynamic binding in Java?
o A: Static binding is the process of resolving the method call at compile time, while dynamic binding is the process of resolving the method
call at run time12. Static binding is achieved by method overloading, while dynamic binding is achieved by method overriding.
• Q: What are the advantages of method overloading and method overriding in Java?13
o A: Method overloading increases the readability and flexibility of the program, while method overriding provides the specific
implementation of a method and supports runtime polymorphism14.
• Q: What are the rules for method overloading and method overriding in Java? 13
o A: The rules for method overloading are: the method name must be the same, the parameter list must be different, and the return type can be
the same or different. The rules for method overriding are: the method name must be the same, the parameter list must be the same, the
return type must be the same or covariant, and there must be an IS-A relationship between the classes.
• Q: What are the types of inheritance in Java?1
o A: The types of inheritance in Java are: single inheritance, multilevel inheritance, and hierarchical inheritance 15. Multiple inheritance and
hybrid inheritance are not supported in Java through classes, but they can be achieved through interfaces.
• Q: What is the syntax of inheritance in Java?1
o A: The syntax of inheritance in Java is: class Subclass-name extends Superclass-name { //methods and fields }
• Q: What is the meaning of extends keyword in Java?
o A: The extends keyword indicates that a class is derived from another class16. It means that the subclass inherits all the methods and fields of
the superclass, and can also add its own methods and fields.
• Q: What is the meaning of super() in Java?
o A: Super() is a special method that invokes the constructor of the parent class17. It is used to initialize the fields of the parent class from the
subclass constructor.
• Q: What is the meaning of toString() method in Java?
o A: ToString() method is a method of the Object class that returns the string representation of an object 18. It can be overridden by subclasses
to provide a custom string representation of the object.

• Q: What is the concept of data hiding in Java?


o A: Data hiding is a software development technique where implementation details are hidden from the user and only functionality is
provided to the user.
• Q: What is the difference between an object and a class in Java?
o A: A class is a blueprint or template from which objects are created. An object is an instance of a class1.
• Q: What is the purpose of a constructor in Java?
o A: A constructor in Java is a block of code that initializes the newly created object. It’s called when an instance of an object is created.
• Q: What is the difference between local variables and instance variables in Java?
o A: Local variables are declared inside methods, constructors, or blocks. Instance variables are declared inside a class but outside a method.
• Q: What is the purpose of static keyword in Java?
o A: The static keyword in Java is used for memory management. It can be applied with variables, methods, blocks, and nested classes.
• Q: What is the difference between static and non-static variables in Java?
o A: Static variables belong to the class rather than the object. Non-static variables belong to the object and each object has its own copy of it.
• Q: What is the purpose of this keyword in Java?
o A: The this keyword in Java is a reference variable that refers to the current object.
• Q: What is the concept of method overloading in Java?2
o A: Method overloading is a feature in Java that allows a class to have two or more methods having the same name but different parameter
lists3.
• Q: What is the concept of method overriding in Java?2
o A: Method overriding is a feature that allows a subclass to provide a specific implementation of a method that is already provided by its
parent class45.
• Q: What is the difference between early binding and late binding in Java?
o A: Early binding refers to assignment of values to variables during design time whereas Late binding refers to assignment of values to
variables during run time.
Java Strings and Arrays

• Q: What is a String in Java?


o A: A String is an object that represents a sequence of characters12.
• Q: How can we create a String using String literal?3
o A: We can create a String using double quotes, such as String first = “Java”;
• Q: What is the advantage of using String literal?
o A: String literal makes Java more memory efficient, as it reuses the same String object if it already exists in the string
constant pool.
• Q: How can we compare two Strings in Java?
o A: We can use the equals() or compareTo() methods to compare two Strings in Java4.
• Q: What is the difference between immutable and mutable Strings?
o A: Immutable Strings cannot be changed once created, while mutable Strings can be modified or changed 5.
• Q: What are the classes that can be used to create mutable Strings in Java?6
o A: StringBuffer and StringBuilder classes can be used to create mutable Strings in Java7.
• Q: What is the difference between StringBuffer and StringBuilder classes?
o A: StringBuffer is synchronized and thread-safe, while StringBuilder is not synchronized and faster than StringBuffer8.
• Q: What is an enum in Java?
o A: An enum is a special class that represents a group of constants which can be used to define our own data types 9.
• Q: How can we declare an enum in Java?
o A: We can use the enum keyword to declare an enum in Java, such as enum Size { SMALL, MEDIUM, LARGE,
EXTRALARGE }
• Q: How can we access the enum constants in Java?
o A: We can use the dot (.) operator to access the enum constants in Java, such as Size.SMALL or Size.LARGE.
• Q: What are the advantages of using enum in Java?
o A: Enum improves type safety, can be used in switch statements, can be traversed using values() method, and can have
attributes and methods.
• Q: What is an array in Java?
o A: An array is an object that stores similar types of elements in a contiguous memory location 1011.
• Q: How can we declare, instantiate, and initialize an array in Java?
o A: We can declare an array using square brackets, such as int[] arr; We can instantiate an array using the new keyword, such
as arr = new int5; We can initialize an array using the assignment operator, such as arr[0] = 10;
• Q: How can we find the length of an array in Java?
o A: We can use the length property of an array to find the number of elements stored in it, such as arr.length 12.
• Q: How can we loop through an array in Java?13
o A: We can use a for loop or a for-each loop to iterate over the elements of an array in Java, such as for (int i = 0; i <
arr.length; i++) or for (int x : arr)

• Q: What is a multidimensional array in Java?


o A: A multidimensional array is an array of arrays12. Each element of a multidimensional array is an array itself.
• Q: How can we declare, instantiate, and initialize a multidimensional array in Java?
o A: We can declare a multidimensional array using two sets of square brackets, such as int[][] arr; We can instantiate a
multidimensional array using the new keyword, such as arr = new int[3][3]; We can initialize a multidimensional array using
nested curly braces, such as arr = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
• Q: What is a wrapper class in Java?
o A: A wrapper class is a class that provides a way to use primitive data types as objects.
• Q: What are the eight wrapper classes in Java?
o A: The eight wrapper classes in Java are: Byte, Short, Integer, Long, Float, Double, Character, and Boolean.
• Q: What is autoboxing and unboxing in Java?
o A: Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes. Unboxing
is the automatic conversion of objects of a wrapper class to its corresponding primitive type.
• Q: What is a package in Java?
o A: A package is a group of similar types of classes, interfaces, and sub-packages. It provides a fully qualified name for a
class or interface, which makes it easier to access.
• Q: How can we create a package in Java?
o A: We can create a package in Java by using the package keyword followed by the name of the package at the beginning of
the Java source file.
• Q: How can we access a package in Java?
o A: We can access a package in Java by using the import keyword followed by the name of the package.
• Q: What is the difference between import and static import in Java?
o A: The import keyword is used to import a class or an entire package, while the static import keyword is used to import
static members of a class.
• Q: What is a Java API?
o A: A Java API is a collection of prewritten classes, interfaces, and algorithms that are ready for use by other programs. It
provides a large number of classes grouped into different packages according to functionality.
Multithreading and Memory Management

• Q: What is multithreading in Java?


o A: Multithreading in Java is a process where multiple threads are executed simultaneously 2.
• Q: What is a thread?
o A: A thread is a lightweight sub-process and is the smallest unit of processing3.
• Q: How can we create a thread in Java?
o A: A thread in Java can be created by either extending the Thread class or implementing the Runnable interface.
• Q: What is the difference between the start() and run() methods of a thread?
o A: The start() method invokes the run() method on a new call stack. The run() method executes on the current call stack.
• Q: What is the life cycle of a thread in Java?4
o A: The life cycle of a thread in Java consists of five states: New, Runnable, Running, Non-Runnable (Blocked), and Terminated.
• Q: What is thread priority and how can we set it? 1
o A: Thread priority is a number between 1 and 10 that indicates the order in which the thread scheduler selects the threads to run. We can set
the thread priority using the setPriority() method of the Thread class.
• Q: What is the join() method of a thread and what does it do?
o A: The join() method of a thread waits for the thread to die, or to complete its execution 5. It causes the currently running thread to pause
until the joined thread finishes its task.
• Q: What is a thread pool and how can we create it in Java?
o A: A thread pool is a group of worker threads that are waiting for the job and reuse many times6. We can create a thread pool in Java using
the Executors class, which provides various methods to create different kinds of thread pools.
• Q: What is the difference between preemptive and time slicing scheduling of threads? 7
o A: Preemptive scheduling is when the thread scheduler assigns the CPU to the thread with the highest priority, and can interrupt the running
thread if a higher priority thread becomes runnable. Time slicing scheduling is when the thread scheduler assigns the CPU to the threads for
a fixed amount of time, and switches between the threads in a round-robin fashion.
• Q: What is the sleep() method of a thread and what does it do?
o A: The sleep() method of a thread is used to make the thread pause its execution for a specified amount of time 8. It does not release the lock
or monitor that the thread may hold.
• What is thread scheduler in Java?
o Thread scheduler in Java is the part of the JVM that decides which thread should run 7.
• What are the three constant priorities of a thread in Java?
o The three constant priorities of a thread in Java are: MIN_PRIORITY (1), NORM_PRIORITY (5), and MAX_PRIORITY (10).
• How can we change the name and priority of a thread in Java?
o We can change the name and priority of a thread in Java by using the setName() and setPriority() methods of Thread class.
• What is the advantage of using thread pool in Java?
o The advantage of using thread pool in Java is that it saves the overhead of creating and destroying threads, and improves the
performance and responsiveness of the application.
• What is the role of garbage collector in Java?
o The role of garbage collector in Java is to find and delete the objects that are not reachable by any live thread, and free the
space in the heap memory14.
• How can an object be eligible for garbage collection in Java?15
o An object can be eligible for garbage collection in Java by nulling a reference, assigning a reference to another object, or
creating an anonymous object.

• What is synchronization in Java?


o Synchronization in Java is a capability to control the access of multiple threads to shared resources.
• What is deadlock in Java?
o Deadlock in Java is a part of multithreading, where two or more threads are blocked forever, waiting for each other.
• What is the difference between ArrayList and LinkedList in Java?
o ArrayList and LinkedList both implements List interface and maintains insertion order. The main difference between them is that ArrayList
is index-based data-structure backed by array, on the other hand LinkedList is doubly-linked list based data-structure.
• What is the difference between equals() and == in Java?
o In Java, equals() method compares the actual content of the string, whereas the ‘==’ operator compares the references of the objects.
• What is exception handling in Java?
o Exception handling in Java is a powerful mechanism to handle runtime errors so that normal flow of the application can be maintained.
• What is the difference between checked and unchecked exceptions in Java?
o Checked exceptions are checked at compile-time, while unchecked exceptions are checked at runtime.
• What is an interface in Java?
o An interface in Java is a blueprint of a class that has static constants and abstract methods.
• What is the difference between abstract class and interface in Java?
o The main difference between an abstract class and an interface in Java is that an abstract class can have default method
implementation while an interface cannot.
• What is a package in Java?
o A package in Java is a group of similar types of classes, interfaces and sub-packages.

• Method Overloading vs Method Overriding in Java:


o Overloading: Multiple methods in the same class share a name but have different parameters. Enhances program readability.
o Overriding: A subclass provides a unique implementation of a method from its parent class. Used for runtime polymorphism.
Wrapper Classes and Collections

• What is a wrapper class in Java?


o A wrapper class is a class that provides the mechanism to convert a primitive data type into an object and vice versa 1.
• What are the benefits of using wrapper classes?
o Wrapper classes make the primitive data types act as objects, which can be useful for storing them in collections, passing them as
parameters to methods, or performing operations on them2.
• What are the eight primitive data types and their corresponding wrapper classes in Java?
o The eight primitive data types and their wrapper classes are:
▪ byte and Byte char and Character
▪ short and Short int and Integer
▪ long and Long float and Float
▪ double and Double boolean and Boolean
• What is autoboxing and unboxing in Java?
o Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class object 34. Unboxing is the reverse
process of converting a wrapper class object into its primitive data type value.
• What is the difference between element() and peek() methods of the Queue interface? 5
o Both element() and peek() methods are used to view the head of the queue without removing it, but element() throws a
NoSuchElementException if the queue is empty, while peek() returns null in that case 78.
• What is the difference between remove() and poll() methods of the Queue interface?
o Both remove() and poll() methods are used to remove and return the head of the queue, but remove() throws a NoSuchElementException if
the queue is empty, while poll() returns null in that case67.
• What is the difference between HashSet, LinkedHashSet, and TreeSet classes? 9
o HashSet, LinkedHashSet, and TreeSet are all implementations of the Set interface, which represents a collection of unique elements. The
differences are:
▪ HashSet uses a hash table for storage and does not maintain any order of the elements 10.
▪ LinkedHashSet inherits from HashSet and maintains the insertion order of the elements11.
▪ TreeSet uses a balanced binary tree for storage and maintains the ascending order of the elements.
• What is the difference between HashMap, LinkedHashMap, and TreeMap classes? 12
o HashMap, LinkedHashMap, and TreeMap are all implementations of the Map interface, which represents a collection of key-value pairs13.
The differences are:
▪ HashMap uses a hash table for storage and does not maintain any order of the keys or values 10.
▪ LinkedHashMap inherits from HashMap and maintains the insertion order of the keys and values.
▪ TreeMap uses a balanced binary tree for storage and maintains the ascending order of the keys and values.
• What is the difference between List, Set, and Map interfaces? 14
o List, Set, and Map are all subinterfaces of the Collection interface, which represents a group of objects. The differences are:
▪ List allows duplicate elements and maintains the insertion order11. It provides a get() method to access the elements by index15.
▪ Set does not allow duplicate elements and does not maintain any order17. It does not provide a get() method to access the
elements by index16.
▪ Map does not allow duplicate keys but allows duplicate values1918. It does not maintain any order of the keys or values. It
provides a get() method to access the values by keys.
• How can you sort a collection in Java?
o You can use the java.util.Collections.sort() method to sort a collection in Java. It takes a list as a parameter and sorts it in ascending order
according to the natural ordering of the elements. You can also provide a custom comparator to define the sorting order.
• How can you reverse sort a collection in Java?
o You can use the java.util.Collections.sort() method with the Collections.reverseOrder() comparator to reverse sort a collection in Java. It
takes a list as a parameter and sorts it in descending order according to the natural ordering of the elements. You can also provide a custom
comparator to define the reverse sorting order.
• What is the difference between Iterator and ListIterator interfaces?
o Iterator and ListIterator are both interfaces that provide the facility of iterating over the elements of a collection 20. The differences are:
▪ Iterator can only traverse the elements in a forward direction, while ListIterator can traverse the elements in both forward and
backward directions.
▪ Iterator can only perform read and remove operations on the elements, while ListIterator can also perform add and set operations
on the elements.
▪ Iterator can be used for any collection, while ListIterator can only be used for lists.
• What is the difference between Collection and Collections in Java?
o Collection is an interface that represents a group of objects, while Collections is a utility class that provides static methods for manipulating
collections, such as sorting, searching, reversing, etc.
• What is the difference between array and ArrayList in Java?
o Array and ArrayList are both data structures that can store multiple elements of the same type. The differences are:
▪ Array has a fixed size, while ArrayList has a dynamic size that can grow or shrink as needed.
▪ Array can store both primitive and reference types, while ArrayList can only store reference types.
▪ Array can be accessed by using the [] operator, while ArrayList can be accessed by using the get() and set() methods.
▪ Array does not provide any methods for adding, removing, or inserting elements, while ArrayList provides methods such as
add(), remove(), and addAll().
• What is the difference between Collection and Collections in Java?
o Collection is an interface that represents a group of objects, while Collections is a utility class that provides static methods for manipulating
collections, such as sorting, searching, reversing, etc.
Java Classes and Objects

• What is the core concept of the object-oriented approach?2


o The core concept of the object-oriented approach is to break complex problems into smaller objects.
• What is a class in Java?
o A class in Java is a template or a set of instructions to build a specific type of object 3.
• What is a constructor in Java?
o A constructor is a block of code in Java that is used to initialize objects of a class 45.
• What is the difference between a static and a non-static variable in Java?
o A static variable belongs to the class and is shared by all objects of the class, while a non-static variable belongs to an individual object and
is not shared by other objects of the same class6.
• What is the difference between a static and a non-static method in Java?
o A static method can be invoked without creating an object of the class, while a non-static method can only be invoked by an object of the
class7.
• What is the purpose of the this keyword in Java?
o The this keyword is used to refer to the current object within a class or a constructor.
• What is a package in Java?
o A package in Java is a group of similar types of classes, interfaces, and sub-packages89.
• What are the benefits of using packages in Java?1
o Some benefits of using packages in Java are:
▪ They help to categorize the classes and interfaces and make them easier to maintain.
▪ They provide access protection for the classes and interfaces.
▪ They prevent naming collisions among the classes and interfaces.
• What is the syntax to declare a package in Java?
o The syntax to declare a package in Java is:
▪ package package_name;
• What is the syntax to import a class or a package in Java? 10
o The syntax to import a class or a package in Java is:
▪ import package_name.Class_name;
▪ or
▪ import package_name.*;
• What is the difference between a public and a private access modifier in Java?
o A public access modifier allows the access of a class, a method, or a variable from any other class or package, while a private access
modifier restricts the access of a class, a method, or a variable to the same class only.
• What is the difference between a protected and a default access modifier in Java?
o A protected access modifier allows the access of a class, a method, or a variable from the same package or a subclass in another package,
while a default access modifier allows the access of a class, a method, or a variable from the same package only.
• What is the difference between a final and a non-final variable in Java?
o A final variable is a constant variable whose value cannot be changed once assigned, while a non-final variable is a variable whose value
can be changed after assignment.
• What is the difference between a final and a non-final method in Java?
o A final method is a method that cannot be overridden by a subclass, while a non-final method is a method that can be overridden by a
subclass.
• What is the difference between a final and a non-final class in Java?
o A final class is a class that cannot be extended by another class, while a non-final class is a class that can be extended by another class.

• What is the effect of making a method final?


o A final method cannot be overridden by subclasses2.
• What is the effect of making a class final?
o A final class cannot be extended by other classes.
• Can we make constructors final?3
o No, because constructors are never inherited4.
• What is the difference between method overriding and method hiding?
o Method overriding is when a subclass defines a method with the same signature as a method in its superclass. Method hiding is when a
subclass defines a static method with the same signature as a static method in its superclass.
• What is the basic structure of a Java program? 5
o A Java program consists of one or more classes, each with zero or more fields, methods, constructors, and inner classes. One of the classes
must contain a main method, which is the entry point of the program.
• What are the optional components of a Java source file?
o A Java source file may contain a package statement, import statements, interface declarations, and enum declarations, in addition to class
declarations.
• What is the order of the components in a Java source file?
o The order is: package statement (at most one), import statements (any number), class/interface/enum declarations (any number).
• What is recursion?
o Recursion is the process of a function calling itself to solve smaller subproblems of the original problem6.
• What is the base case in recursion?7
o The base case is the simplest case of the problem, which can be solved directly without recursion.
Java Control Structures and Methods

• What are the types of control structures in Java?


o The types of control structures in Java are decision making statements, loop statements, and jump statements 1.

• What is the difference between a while loop and a do-while loop?


o A while loop checks the condition before executing the code block, while a do-while loop executes the code block at least once before
checking the condition6.
• What is the use of the break statement in a switch or a loop? 7
o The break statement is used to terminate the switch or the loop when the condition is satisfied or the case is matched.
• What is a method in Java?
o A method in Java is a collection of instructions or a block of code that performs a specific task 8.
• What are the components of a method declaration?
o The components of a method declaration are the modifier, the return type, the method name, the parameter list, and the method body.
• What are the types of methods in Java?9
o The types of methods in Java are predefined methods and user-defined methods.
• What is a static method in Java?
o A static method in Java is a method that belongs to a class rather than an instance of a class10. It can be called without creating an object of
the class11.
• What is a for-each loop in Java?
o A for-each loop in Java is a loop that is used to iterate through the elements of an array or a collection 12. It works on the basis of elements,
so no need of increment or decrement variables13.
• What is a nested for loop in Java?
o A nested for loop in Java is a loop that contains another loop inside it 14. The inner loop executes completely whenever the outer loop
executes15.

• Q: What is the purpose of the Date class in Java?


o A: The Date class provides methods to manipulate date and time, such as toString(), getTime(), equals(), and setTime().
• Q: What are the two types of methods in Java, and how are they different? 1
o A: The two types of methods in Java are predefined methods and user-defined methods. Predefined methods are built-in methods that are
provided by the standard library, such as sqrt() or println()2. User-defined methods are created by programmers based on the requirements,
such as getSquare() or greet()3.
• Q: What is the main topic of the web page summary?
o A: The web page summary reviews the main topics covered in the previous pages, such as decision making statements, loop statements,
switch statement, break and jump statements, and methods.
• Q: How can you define a static method in Java, and how can you invoke it?
o A: A static method in Java is defined by using the keyword static before the method name, such as public static void main(String[] args). A
static method can be invoked by using the class name followed by a dot and the method name, such as Math.sqrt(25) or
System.out.println(“Hello”).
• Q: What are the two exercises given at the end of the web page for the user to practice writing methods?
o A: The two exercises given at the end of the web page are:
1. Write a method to print a customized greeting message based on the time of the day 4.
2. Write a method to produce the power of 10 where power value is accepted through console 5.

You might also like