JAVA QUESTION ANSWERS
JAVA QUESTION ANSWERS
2 MARKS
Q1 What is Object Oriented programming?
Ans.
Object-Oriented Programming or OOPs refers to languages that use objects in
programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is
to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function.
Mainly used C++ is mainly used for system Java is mainly used for application
for programming. programming. It is widely used in Windows-
based, web-based, enterprise, and mobile
applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter
applications programming. It was an for printing systems but later extended as a
extension of the C programming support network computing. It was designed to
language. be easy to use and accessible to a broader
audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance through class. It can be achieved by
using interfaces in java.
Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can write Java supports pointer internally. However, you
a pointer program in C++. can't write the pointer program in java. It means
java has restricted pointer support in java.
Q12 Write java program to check given year is leap year or not.
Ans.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
}
Q21 Write java program to find factorial of ‘4’ using for loop.
Ans.
public class FactorialExample {
public static void main(String[] args) {
int number = 4; // Number for which we need to find the factorial
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i; // factorial = factorial * i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
Q2 Write java program to display given number is positive or negative.[no taken from
user using Scanner class]
Ans.
import java.util.Scanner;
Relational and logical operators are fundamental in decision-making and flow control
constructs such as if, while, for, etc., in Java programming.
3. switch Statement:
o The switch statement evaluates an expression and executes the code
block associated with the matched case.
o It provides an alternative to multiple if-else if statements when testing the
same variable.
o Example:
switch (expression) {
case value1:
// code block to be executed if expression matches value1
break;
case value2:
// code block to be executed if expression matches value2
break;
default:
// code block to be executed if expression doesn't match any case
}
These decision-making constructs enable you to write Java programs that can make
choices based on specific conditions, allowing for flexible and controlled execution
paths.
Q5 How to create object of Student class using new keyword and call default
constructor.
Ans.
To create an object of the Student class using the new keyword and call the default
constructor, follow these steps:
1. Define the Student class with a default constructor (a constructor with no
parameters).
2. Use the new keyword followed by the class name and parentheses to
instantiate the object.
3. Assign the newly created object to a reference variable of type Student.
4. Optionally, access the methods or fields of the Student class through the object
reference variable.
Here's an example:
// Define the Student class
class Student {
// Default constructor
public Student() {
System.out.println("Default constructor called");
}
}
Q6 Give the importance of ‘this’ keyword for changing the scope of the variables.
Ans.
The this keyword in Java is primarily used to refer to the current instance of the class.
While it's not directly used to change the scope of variables, it plays a crucial role in
disambiguating between instance variables and local variables with the same name,
thereby preventing shadowing and ensuring correct variable resolution.
Importance of this Keyword:
1. Disambiguation:
o In methods or constructors where local variables have the same name as
instance variables, using this allows you to differentiate between them.
o It helps resolve naming conflicts and ensures that the correct variable is
accessed or modified.
2. Clarity and Readability:
o Explicitly using this makes the code more readable by clearly indicating
that the variable being referenced belongs to the current object.
o It improves code comprehension and reduces ambiguity, especially in
large codebases or when collaborating with others.
3. Avoiding Shadowing:
o Without this, if a local variable shadows an instance variable, the instance
variable becomes inaccessible within that scope.
o By using this, you can access the instance variable even if it's shadowed
by a local variable, thus avoiding unintentional variable hiding.
4. Constructor Chaining:
o In constructors, this can be used to call another constructor in the same
class, facilitating constructor chaining.
o This allows for code reuse and helps in initializing objects with different
parameters while avoiding duplicate initialization logic.
5. Passing the Current Object:
o In certain scenarios, such as passing the current object as an argument to
another method or constructor, this is used to refer to the current
instance.
While the primary role of this is not to change the scope of variables, it plays a critical
role in maintaining clarity, avoiding variable shadowing, and ensuring correct variable
resolution in object-oriented Java programming.
Q8 What is meant by interface? State its need and write syntax and features of
interface.
Ans.
An interface in Java is like a contract or a blueprint that defines a set of methods that
a class must implement. It establishes a way for classes to adhere to a specific set of
behaviors without specifying how those behaviors are implemented.
Features of Interface:
1. Methods: Interfaces can have abstract methods that do not have a method body.
These methods must be implemented by the classes that implement the interface.
2. Constants: Interfaces can have constants, which are implicitly static and final. These
constants can be accessed using the interface name.
3. Default Methods: Starting from Java 8, interfaces can have default methods with a
default implementation. Classes implementing the interface can choose to override
these default methods.
4. Static Methods: Interfaces can also have static methods that are associated with
the interface itself and can be called using the interface name.
By using interfaces, you can define a contract that classes must adhere to, promoting
code reusability and flexibility in your Java programs. If you have any more questions
or need further clarification, feel free to ask!
Isolation and memory protection Isolation and memory protection does not
9.
exist in multitasking. exist in multithreading.
Q12 Write java program to display multiplication table of 4 using for loop.
Ans.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 4; // The number for which we want to print the multiplication
table
If the class does not have the implementation of all the methods of the interface, we
should declare the class as abstract. It provides complete abstraction. It means that
fields are public static and final by default and methods are empty.
Q18 What is package? State how to create and access user defined package in Java.
Ans.
A package in Java is a namespace that organizes related classes and interfaces. Similar
to the folders on your computer, packages are a way to group related Java classes and
interfaces. This makes it easier to find, locate, and use them. User-defined packages
are similar to built-in packages. They can be imported into other classes and used in
the same way as built-in packages.
To create a user-defined package in Java, you need to follow these steps:
1. Create a directory with the package name.
2. Place the Java files (classes) inside this directory.
3. Add the package declaration at the beginning of each Java file.
• Here is an example of creating a user-defined package named com.example:
// File: com/example/MyClass.java
package com.example;
1. start(): This method is used to start the execution of a thread. When start() is
called, the JVM calls the run() method of the thread.
2. run(): The run() method contains the code that constitutes the thread's task. It is
where the actual work of the thread is defined.
3. sleep(long millis): This method pauses the execution of the current thread for the
specified number of milliseconds. It's commonly used for introducing delays in a
thread's execution.
4. join(): The join() method allows one thread to wait for the completion of another
thread. When a thread calls join() on another thread, it waits until that thread
completes its execution.
5. isAlive(): This method checks if a thread is still alive. A thread is considered alive
from the moment start() is called until the run() method completes execution.
6. interrupt(): The interrupt() method interrupts a thread, causing it to stop what it's
doing and either throw an InterruptedException or exit.
7. yield(): The yield() method suggests to the scheduler that the current thread is
willing to yield its current use of the processor. It's a way to give other threads a
chance to run.
These methods provide developers with powerful tools to control thread execution,
synchronization, and communication in Java programs.
Q21 Why java is not a fully object oriented programming language? Elaborate your
answer.
Ans.
Java is often considered an object-oriented programming (OOP) language, and it does
adhere to many principles of object-oriented design. However, it's also true that Java
is not a "pure" or "fully" object-oriented language. Here's why:
1.Primitive Data Types: Java includes primitive data types like int, double, boolean,
etc., which are not objects. These primitive types do not inherit from a common class,
unlike objects, and do not have methods or fields.
2. Static Members: Java allows the use of static methods and variables, which belong
to the class itself rather than to instances of the class. Static members are not
associated with objects and can be accessed without creating an instance of the class.
3. Procedural Programming: Java supports procedural programming concepts
alongside object-oriented programming. This means you can write code that focuses
on procedures and functions rather than solely on objects and classes.
4. Direct Memory Manipulation: Java does not allow direct memory manipulation like
some lower-level languages do. In pure object-oriented languages, all operations are
performed on objects, and direct memory access is restricted.
While Java may not be entirely object-oriented due to the presence of primitive types
and static members, it remains a powerful language for building object-oriented
applications.
Q23 Write java program to perform factorial of given number [ no taken from user by
using Scanner class]
Ans.
import java.util.Scanner;
Q28 Give the difference between method overloading & method overriding.
Ans.
Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
Q29 Briefly explain the advantages about synchronization in thread.
Ans.
Synchronization in threads is super important because it helps in preventing conflicts
and issues when multiple threads are trying to access shared resources
simultaneously. Here are some advantages of synchronization:
1. Prevents Data Corruption: Synchronization ensures that only one thread can access
a shared resource at a time, preventing data corruption and maintaining data
integrity.
2. Avoids Race Conditions: Race conditions occur when the outcome of a program
depends on the execution order of threads. Synchronization helps in avoiding race
conditions by controlling the access to shared resources.
In this example:
1. We create a class `MyRunnable` that implements the `Runnable` interface. This
class contains the `run()` method, which defines the task the thread will execute.
3. We then create a new `Thread` object `myThread` and pass the `MyRunnable`
instance to it in the constructor.
4. Finally, we start the thread using `myThread.start()`, which will execute the `run()`
method of `MyRunnable`.
When you run this program, it will create a new thread that prints "Thread is
running!" to the console. This demonstrates the basic concept of creating and running
a thread in Java using the `Runnable` interface.