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

JAVA Ia1

Uploaded by

Arathi M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

JAVA Ia1

Uploaded by

Arathi M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU

DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

QUESTION – BANK
Slno QUESTIONS
1.
Explain the purpose and usage of labeled break and continue statements in Java,
along with an example for each.
Ans: In Java, labeled break and labeled `continue statements allow for more control over
nested loops, making it possible to break out of or continue specific outer loops rather
than just the innermost one.
Labeled `break` Statement:
The labeled `break` statement is used to **terminate a specific loop** when certain
conditions are met, even if that loop is nested within others. By using a label, we can
indicate which loop to break out of.
Syntax:
labelName:
// Start of the loop
for (/* loop conditions */) {
for (/* inner loop conditions */) {
if (/* condition to break */) {
break labelName; // breaks out of the labeled loop
}
}
}
Example:
public class LabeledBreakExample {
public static void main(String[] args) {
// Define a label for the outer loop
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
if (i == 2 && j == 2) {
// Use labeled break to exit the outer loop
break outerLoop;
}
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

}
}
System.out.println("Exited outer loop.");
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
Exited outer loop.
In this example, when `i == 2` and `j == 2`, the `break outerLoop` statement is triggered,
causing the program to exit the outer loop labeled `outerLoop`. This stops all iterations
of both loops.
Labeled `continue` Statement:
The labeled `continue` statement **skips the current iteration** of a specified loop and
proceeds to the next iteration of that loop. This is useful when you want to skip
iterations not only in an inner loop but also in a specific outer loop.
Syntax:
labelName:
// Start of the loop
for (/* loop conditions */) {
for (/* inner loop conditions */) {
if (/* condition to continue */) {
continue labelName; // continues with the next iteration of the labeled loop
}
}
}
Example:
public class LabeledContinueExample {
public static void main(String[] args) {
// Define a label for the outer loop
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// Use labeled continue to skip to the next iteration of the outer loop
continue outerLoop;
}
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
In this example, when `i == 2` and `j == 2`, the `continue outerLoop` statement is
triggered, skipping the remaining iterations of the inner loop and moving directly to the
next iteration of the outer loop (`i = 3`).
2.
Briefly describe the key features of the Java programming language that make it unique
and widely used.
Ans: 1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

2. Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behavior.
Advertisement
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation
3. Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
4. Secured:
Java includes built-in security features, such as bytecode verification and a security
manager, which protect against unauthorized access and ensure that Java applications
run in a secure environment.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.
5. Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
6. Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
8. High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
9. Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any machine on the internet.
10. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
11. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
Java supports dynamic compilation and automatic memory management (garbage
collection).

3.
What are a class and an object in the context of Object-Oriented Programming (OOP)?
How do they interact with each other in Java?
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Ans: In Object-Oriented Programming (OOP), a class and an object are fundamental


concepts that help in organizing and structuring code in a modular, reusable, and logical
way.
Class
A class is a blueprint or template that defines the structure and behavior of objects. It
describes the data (attributes) and actions (methods) that objects created from the class
will have. Think of it as a blueprint for creating multiple objects that share the same
properties and functionalities.
- **Attributes**: Variables defined within a class to represent the properties of objects
(e.g., `name`, `age`, `color`).
- **Methods**: Functions defined within a class to represent behaviors or actions that
objects of the class can perform (e.g., `speak()`, `move()`).
In Java, a class is defined using the `class` keyword:
public class Dog {
// Attributes
String name;
int age;
// Method
void bark() {
System.out.println(name + " is barking!");
}
}
In this example, `Dog` is a class with two attributes (`name` and `age`) and one method
(`bark()`).
Object
An object is an instance of a class. When a class is defined, no memory is allocated until
an object of that class is created. An object has the structure and behavior defined by its
class, and it represents a specific entity with actual values for the attributes defined in
the class.
To create an object in Java, the `new` keyword is used to instantiate a class.
public class Main {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog myDog = new Dog();
// Setting attributes for the object
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

myDog.name = "Buddy";
myDog.age = 3;
// Calling a method on the object
myDog.bark(); // Output: Buddy is barking!
}
}
Here, `myDog` is an object (or instance) of the `Dog` class. It has its own `name` and
`age` values, which can be different from those of other `Dog` objects.
Interaction between Class and Object
1. Object Creation: A class acts as a blueprint, and an object is created from that
blueprint using the `new` keyword.
2. Attribute and Method Access: An object uses the structure and behavior defined by its
class. Attributes are accessed and modified, and methods are called on the object to
perform actions.
3. Encapsulation: In Java, classes often use access modifiers (like `private` for attributes)
to enforce encapsulation, which hides the internal details and provides controlled access
through methods (getters and setters).
4.
A customer intends to open a savings account at a bank. To do so, the following
information is required: customer name, customer phone number, customer email ID,
customer address, and initial deposit amount (all mandatory). After the account is
created, the customer can perform the following operations:
a. View account balance
b. Deposit funds
c. Withdraw funds
Write a Java program to model this scenario, demonstrating the creation of an account
object and performing the specified operations.
5.
What is a constructor in Java? Provide an example to illustrate constructor overloading
in Java.
Ans: In Java, a constructor is a special method that is called when an object is created. It
initializes the new object by setting up the initial state or values for the object’s
attributes. Constructors have the same name as the class and do not have a return type,
not even `void`.

Key Points About Constructors


- Same name as the class: A constructor must have the same name as the class it’s in.
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

- No return type: Constructors do not have a return type.


- Automatic invocation: The constructor is called automatically when an object of the
class is created.
- Default Constructor: If no constructor is defined, Java provides a default no-argument
constructor.
Constructor Overloading
Constructor overloading is the technique of defining multiple constructors within the
same class, each having a different parameter list. Overloading allows flexibility in how
objects are created with different sets of initial values.
Example of Constructor Overloading in Java:
public class Car {
String model;
int year;
String color;
// Default constructor
public Car() {
this.model = "Unknown";
this.year = 2000;
this.color = "White";
}
// Constructor with one parameter
public Car(String model) {
this.model = model;
this.year = 2000;
this.color = "White";
}
// Constructor with two parameters
public Car(String model, int year) {
this.model = model;
this.year = year;
this.color = "White";
}
// Constructor with all three parameters
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

public Car(String model, int year, String color) {


this.model = model;
this.year = year;
this.color = color;
}
public void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year + ", Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
// Using the default constructor
Car car1 = new Car();
car1.displayInfo(); // Output: Model: Unknown, Year: 2000, Color: White
// Using the constructor with one parameter
Car car2 = new Car("Toyota");
car2.displayInfo(); // Output: Model: Toyota, Year: 2000, Color: White
// Using the constructor with two parameters
Car car3 = new Car("Honda", 2021);
car3.displayInfo(); // Output: Model: Honda, Year: 2021, Color: White
// Using the constructor with three parameters
Car car4 = new Car("Ford", 2018, "Blue");
car4.displayInfo(); // Output: Model: Ford, Year: 2018, Color: Blue
}
}
6.
What is the role of this keyword in Java? Explain how it is utilized within constructors
and methods.
Ans:
7.
What is inheritance in Java? Describe its various types with appropriate examples.
Inheritance is a fundamental concept in Java and object-oriented programming (OOP)
that allows one class (the child or subclass) to inherit the properties and behaviors
(methods) of another class (the parent or superclass). This promotes code reusability and
establishes a hierarchical relationship between classes.
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Key Points about Inheritance:


- Code Reusability**: Inheritance allows a new class to reuse the code of an existing
class, which reduces redundancy and promotes cleaner code.
- **Method Overriding**: Subclasses can provide specific implementations of methods
that are already defined in the parent class.
- **Hierarchical Relationships**: Inheritance can create a multi-level hierarchy of
classes.
Types of Inheritance in Java
1. Single Inheritance:
- A subclass inherits from one superclass only.
- **Example**:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
- Output:
Eating... Barking...
2. Multi-Level Inheritance:
- A class is derived from another class, which is also derived from another class,
creating a chain of inheritance.
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

- Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep(); // Puppy’s own method
}
}
- Output:
Eating... Barking… Weeping...
3. Hierarchical Inheritance:
- Multiple subclasses inherit from the same superclass.
- Example:
class Animal {
void eat() {
System.out.println("Eating...");
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Meowing...");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.eat(); // Inherited from Animal
dog.bark(); // Dog’s own method
cat.eat(); // Inherited from Animal
cat.meow(); // Cat’s own method
}
}
- Output:
Eating... Barking... Eating... Meowing...
8.
Design a class hierarchy for a university system where Person is the base class, and
Student and Professor are subclasses. Write a Java program to demonstrate this class
hierarchy and the inheritance relationships.
Ans:
// Base Class
class Person {
String name;
int age;
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display basic person information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Student class inheriting from Person
class Student extends Person {
String studentID;
String major;
// Constructor
public Student(String name, int age, String studentID, String major) {
super(name, age); // Call to the superclass (Person) constructor
this.studentID = studentID;
this.major = major;
}
// Method to display student information
public void displayInfo() {
super.displayInfo(); // Call Person's displayInfo method
System.out.println("Student ID: " + studentID);
System.out.println("Major: " + major);
}
}
// Professor class inheriting from Person
class Professor extends Person {
String employeeID;
String department;
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

// Constructor
public Professor(String name, int age, String employeeID, String department) {
super(name, age); // Call to the superclass (Person) constructor
this.employeeID = employeeID;
this.department = department;
}
// Method to display professor information
public void displayInfo() {
super.displayInfo(); // Call Person's displayInfo method
System.out.println("Employee ID: " + employeeID);
System.out.println("Department: " + department);
}
}
// Main class to demonstrate the hierarchy
public class UniversitySystem {
public static void main(String[] args) {
// Creating a Student object
Student student = new Student("Alice", 20, "S12345", "Computer Science");
// Creating a Professor object
Professor professor = new Professor("Dr. Smith", 45, "E56789", "Mathematics");
// Displaying student information
System.out.println("Student Information:");
student.displayInfo();
// Displaying professor information
System.out.println("\nProfessor Information:");
professor.displayInfo();
}
}
Explanation of the Code
- **Person Class**: `Person` has a constructor to initialize `name` and `age` and a
`displayInfo()` method to display basic information.
- **Student Class**: Inherits from `Person` and adds `studentID` and `major`. The
`displayInfo()` method is overridden to display additional student-specific information.
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

- **Professor Class**: Inherits from `Person` and adds `employeeID` and `department`.
The `displayInfo()` method is also overridden for professor-specific details.
Output
Student Information:
Name: Alice
Age: 20
Student ID: S12345
Major: Computer Science

Professor Information:
Name: Dr. Smith
Age: 45
Employee ID: E56789
Department: Mathematics
9.
What is type conversion in Java? Explain the difference between implicit and explicit
type casting with examples.
Ans: Type conversion in Java is the process of converting one data type into another. It
is especially useful in scenarios where one data type needs to be used as another, either
because of operations or when interfacing with code expecting a different type. Type
conversion can happen automatically or manually.
Types of Type Conversion in Java
1. Implicit Type Conversion (Automatic or Widening Casting)
2. Explicit Type Conversion (Manual or Narrowing Casting)
1. Implicit Type Conversion
Implicit type conversion, also known as automatic type conversion or **widening
casting**, happens when Java automatically converts a smaller data type into a larger
data type without the need for explicit instructions. This type of casting is safe and does
not lead to data loss.
Supported Conversions:
- **byte → short → int → long → float → double**
Example of Implicit Casting:
public class ImplicitCastingExample {
public static void main(String[] args) {
int intNumber = 50;
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

double doubleNumber = intNumber; // Automatic conversion from int to doubl


System.out.println("Integer value: " + intNumber);
System.out.println("Double value (after implicit casting): " + doubleNumber);
}
}
Output:
Integer value: 50
Double value (after implicit casting): 50.0
2. Explicit Type Conversion
Explicit type conversion, also known as **manual type conversion** or **narrowing
casting**, happens when a larger data type needs to be converted to a smaller data type.
Since this kind of conversion may lead to data loss, it requires explicit casting by the
programmer using parentheses to specify the target type.
Supported Conversions:
- **double → float → long → int → short → byte**
Example of Explicit Casting:
public class ExplicitCastingExample {
public static void main(String[] args) {
double doubleNumber = 55.55;
int intNumber = (int) doubleNumber; // Manual conversion from double to int
System.out.println("Double value: " + doubleNumber);
System.out.println("Integer value (after explicit casting): " + intNumber);
}
}
Output:
Double value: 55.55
Integer value (after explicit casting): 55
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

10.
Discuss the concept of arrays in Java. How do single-dimensional arrays differ from
multi-dimensional arrays?
Ans:
11.
Explain the significance of comments in Java programming. What are the different types
of comments supported by Java?
Ans: Significance of Comments in Java
 Code Readability: Comments improve the readability of the code by providing
context or explanations for complex logic, variables, or functions.
 Maintenance: When code needs to be maintained, comments help developers
understand the purpose and design of the code.
 Documentation: Comments can act as in-line documentation, helping new
developers or collaborators quickly understand the codebase.
 Debugging Assistance: Temporary comments can help during debugging by
documenting which parts of the code are currently being tested or which have
known issues.
Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
Java Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

public class CommentExample1


{
public static void main(String[] args)
{
int i=10; //Here, i is a variable
System.out.println(i);
}
}
Output: 10
Java Multi Line Comment
The multiline comment is used to comment multiple lines of code.
Syntax:
/* This is
multi line comment
*/
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let&#39;s declare and
print variable in java. */
int i=10; System.out.println(i);
}
}
Output: 10
Java Documentation Comment
The documentation comment is used to create documentation API. To create
documentation
API, you need to use javadoc tool.
Syntax:
/** This is documentation comment */
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Example:
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{
return a-b;
}
}
12.
What is the scope and lifetime of a variable in Java? How do local variables and instance
Jjjj
variables differ in terms of scope and lifetime?
In Java, scope and lifetime of a variable define where and for how long a variable can be
accessed and exists in memory.
Scope of a Variable
- Definition: The scope of a variable refers to the region or block of code within which
the variable can be accessed or used.
- Types of Scope:
- Local Scope: The scope of a local variable is limited to the block or method where it
is declared. It cannot be accessed outside of that block.
- Instance Scope: Instance variables (non-static fields) have a scope throughout the
class and are accessible from instance methods within the class.
- Class (Static) Scope: Class-level (static) variables are accessible across all instances
of the class and within any static or instance methods.

Lifetime of a Variable
Definition: The lifetime of a variable refers to the duration for which the variable exists
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

in memory.
- Local Variables: Created when a method or block is entered and destroyed when it is
exited. Their lifetime is tied to the method execution.
- Instance Variables: Created when an object of the class is instantiated and destroyed
when the object is garbage collected. They exist as long as the object exists.
- Static Variables: Created when the class is loaded and remain in memory until the
class is unloaded, usually at the end of the program's execution.
Differences Between Local Variables and Instance Variables
1. Scope:
- Local Variables: The scope is limited to the block, method, or constructor where they
are declared.
- Instance Variables: The scope is throughout the class, and they are accessible by any
non-static method in the class.

2. Lifetime:
- Local Variables: Their lifetime begins when the method or block is entered and ends
when the block or method is exited. They do not retain values between method calls.
- Instance Variables: Their lifetime begins when an object is created and ends when
the object is no longer referenced and is garbage collected. They retain values as long as
the object exists.

Java Example
public class ScopeLifetimeExample {
// Instance variable
int instanceVar = 10;
// Static variable
static int staticVar = 20;
public void demonstrateScope() {
// Local variable
int localVar = 30;
System.out.println("Inside method:");
System.out.println("Local Variable: " + localVar); // Accessible only within this
method
System.out.println("Instance Variable: " + instanceVar); // Accessible throughout
the class
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

System.out.println("Static Variable: " + staticVar); // Accessible throughout the


class
}
public static void main(String[] args) {
ScopeLifetimeExample example = new ScopeLifetimeExample();
// Accessing instance variable through an object
System.out.println("Instance Variable: " + example.instanceVar);
// Accessing static variable directly
System.out.println("Static Variable: " + staticVar);
// Demonstrating local variable scope
example.demonstrateScope();
// Uncommenting the below line would cause a compilation error as localVar is out
of scope
// System.out.println(localVar);
}
}
13.
What is garbage collection in Java? How does the Java Virtual Machine (JVM) manage
memory?
14.
Discuss the different levels of access control in Java. How do these levels affect the
visibility of class members?
Ans: In Java, access control levels (or access modifiers) determine the visibility and
accessibility of classes, methods, variables, and other members within different parts of
the code. These levels help in implementing encapsulation by restricting access to class
members and are defined by four main modifiers: `public`, `protected`, `default` (no
modifier), and `private`.
1. `public` Access Modifier
- Visibility: Accessible from anywhere in the program, across all classes and packages.
- Usage: Commonly used for classes and methods that need to be accessible to other
parts of the application or API consumers.
Example:
public class PublicClass {
public int publicVariable = 10;
public void publicMethod() {
System.out.println("Public method in PublicClass");
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

}
}
- Effect: The `publicVariable` and `publicMethod` are accessible from any class, even
outside the package containing `PublicClass`.
2. `protected` Access Modifier:
- Visibility: Accessible within the same package and subclasses in different packages.
- Usage: Primarily used for members intended to be accessible by subclasses, supporting
inheritance while restricting access to package or subclass only.
Example:
class ProtectedClass {
protected int protectedVariable = 20;
protected void protectedMethod() {
System.out.println("Protected method in ProtectedClass");
}
}
- Effect: `protectedVariable` and `protectedMethod` are accessible to other classes in the
same package and to subclasses in different packages. This is especially useful for
inheritance where you want to share methods or variables only with subclasses.
3. Default Access Modifier (Package-Private)
- Visibility: Accessible only within the same package. If no access modifier is specified,
the default level applies.
- Usage: Used when members are meant to be accessed only by classes within the same
package but not by subclasses outside the package.
Example:
class DefaultClass {
int defaultVariable = 30; // No access modifier means package-private
void defaultMethod() { // No access modifier means package-private
System.out.println("Default method in DefaultClass");
}
}
- Effect: `defaultVariable` and `defaultMethod` are accessible only to other classes
within the same package. They are not accessible from classes outside the package, even
if they are subclasses.
4. `private` Access Modifier
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

- Visibility: Accessible only within the same class.


- Usage: Used to restrict access to internal details of a class, ensuring encapsulation by
hiding implementation details from other classes.
Example:
class PrivateClass {
private int privateVariable = 40;
private void privateMethod() {
System.out.println("Private method in PrivateClass");
}
}
- Effect: `privateVariable` and `privateMethod` can only be accessed within
`PrivateClass` itself. They are not accessible from any other class, including subclasses
or classes within the same package.
15.
What are the rules for access control and inheritance in Java programming? How do
access modifiers (private, protected, public) influence these rules?
In Java programming, access control and inheritance play crucial roles in ensuring
encapsulation and determining the visibility and accessibility of classes, methods, and
variables. The access modifiers (`private`, `protected`, `public`, and default) influence
these rules significantly.
Access Control Rules and Inheritance
1. Private Access (`private`):
- Scope: Members marked as `private` are accessible only within the class where they
are declared.
- Inheritance: Private members are not inherited by subclasses and cannot be accessed
directly from them. However, a subclass can indirectly access `private` members via
public or protected methods provided in the superclass.
2. Default Access:
- Scope: Members with no explicit access modifier (default/package-private) are
accessible only within the same package.
- Inheritance: While package-private members can be inherited, they are only
accessible to subclasses that are within the same package.
3. Protected Access (`protected`):
- Scope: Members marked as `protected` are accessible within the same package and
to subclasses, even if they are in different packages.
- Inheritance: Subclasses can directly access protected members of their superclass,
allowing a controlled level of access for extending classes while still limiting full
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

exposure to the public.


4. Public Access (`public`):
- Scope: Members declared as `public` are accessible from any class, regardless of the
package.
- Inheritance: Public members are fully inherited and can be accessed and overridden
by subclasses without restrictions.

How Access Modifiers Influence Inheritance


- `private` members: Not visible to subclasses directly, but subclasses can use public or
protected methods to interact with them if such methods are provided.
- `protected` members: Can be accessed and overridden by subclasses, making this
modifier useful for giving subclasses more direct access while still restricting general
access to the package level.
- `public` members: Completely accessible to all classes and can be inherited and
overridden by any subclass, allowing full visibility.
- default members: Limits access to the same package, so subclasses in different
packages cannot access these members directly.

Example to Illustrate Access Control


// Superclass in package com.example.base
package com.example.base;
public class SuperClass {
private int privateValue = 10; // Only accessible within SuperClass
int defaultValue = 20; // Accessible within the same package
protected int protectedValue = 30; // Accessible in subclasses and same package
public int publicValue = 40; // Accessible from anywhere
public int getPrivateValue() {
return privateValue; // Public method to access privateValue
}
}
// Subclass in a different package com.example.sub
package com.example.sub;
import com.example.base.SuperClass;
public class SubClass extends SuperClass {
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

public void displayValues() {


// System.out.println(privateValue); // ERROR: privateValue is not accessible
// System.out.println(defaultValue); // ERROR: defaultValue is not accessible
(different package)
System.out.println(protectedValue); // Accessible: protectedValue is inherited
System.out.println(publicValue); // Accessible: publicValue is inherited
System.out.println(getPrivateValue()); // Indirect access through public method
}
}
Explanation
- The `privateValue` in `SuperClass` cannot be accessed directly by `SubClass` because
it is `private`.
- The `defaultValue` can only be accessed within the same package; therefore,
`SubClass`, which is in a different package, cannot access it.
- The `protectedValue` is accessible in `SubClass` due to inheritance, even though
`SubClass` is in a different package.
- The `publicValue` is accessible everywhere, so `SubClass` can directly access it.
- The `getPrivateValue()` method allows `SubClass` to indirectly access `privateValue`.
16.
What is the purpose of the super keyword in Java? How is it utilized in the context of
9
inheritance? Write a Java program that demonstrates the use of the super keyword to
invoke both a superclass constructor and a superclass method.
The `super` keyword in Java serves an essential purpose in the context of inheritance. It
allows a subclass to refer to its immediate superclass and can be used for the following
purposes:
1. Invoking the superclass constructor: The `super()` call is used within a subclass
constructor to explicitly call a constructor from its superclass. If no `super()` call is
specified, Java implicitly inserts a call to the no-argument constructor of the superclass.
2. Accessing superclass methods: The `super` keyword can be used to call a method
defined in the superclass that may be overridden in the subclass.
3. Accessing superclass variables: It can also be used to access variables from the
superclass when they are hidden by variables defined in the subclass.
Java Program to Demonstrate `super`
// Superclass definition
class Animal {
// Constructor of the superclass
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Animal() {
System.out.println("Animal constructor called");
}
// Method in the superclass
void sound() {
System.out.println("Animals make different sounds");
}
}
// Subclass definition
class Dog extends Animal {
// Constructor of the subclass
Dog() {
// Call to the superclass constructor using super()
super();
System.out.println("Dog constructor called");
}
// Overriding the method in the subclass
void sound() {
// Call the superclass method using super
super.sound();
System.out.println("Dogs bark");
}
}
// Main class to run the program
public class SuperKeywordExample {
public static void main(String[] args) {
// Create an instance of the subclass
Dog dog = new Dog();
// Call the overridden method
dog.sound();
}
}
ATRIA INSTITUTE OF TECHNOLOGY, BENGALURU
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

Explanation of the Program


1. Superclass `Animal`:
- Contains a constructor that prints a message.
- Has a method `sound()` that prints a generic statement.
2. Subclass `Dog`:
- The constructor of `Dog` calls the constructor of `Animal` using `super()`, ensuring
that the superclass is initialized first.
- Overrides the `sound()` method but uses `super.sound()` to invoke the `sound()`
method from `Animal` before adding subclass-specific behavior.
3. Main Method:
- Instantiates a `Dog` object, which triggers the constructor chain.
- Calls the overridden `sound()` method, demonstrating how `super.sound()` can be
used to access the superclass method.

Expected Output
Animal constructor called
Dog constructor called
Animals make different sounds
Dogs bark

You might also like