JAVA Ia1
JAVA Ia1
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
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`.
- 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
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
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
}
}
- 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
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
Expected Output
Animal constructor called
Dog constructor called
Animals make different sounds
Dogs bark