0% found this document useful (0 votes)
7 views18 pages

CT 1 Contents - OOPS - Java

Java is platform-independent due to its WORA nature, allowing bytecode to run on any system with a JVM. Developed by James Gosling at Sun Microsystems in 1995, Java is popular for its simplicity, security features, and strong community support. Key components of the Java environment include JDK, JRE, and JVM, with JDK providing development tools and JRE offering the runtime environment for executing Java applications.
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)
7 views18 pages

CT 1 Contents - OOPS - Java

Java is platform-independent due to its WORA nature, allowing bytecode to run on any system with a JVM. Developed by James Gosling at Sun Microsystems in 1995, Java is popular for its simplicity, security features, and strong community support. Key components of the Java environment include JDK, JRE, and JVM, with JDK providing development tools and JRE offering the runtime environment for executing Java applications.
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/ 18

UNIT 1

Why Java?

1. Why is Java considered platform-independent?


o Java is platform-independent because of its "Write Once, Run Anywhere" (WORA)
nature, as Java programs are compiled into bytecode that can run on any system with a
JVM.
2. What makes Java a popular programming language?
o Java is popular due to its simplicity, object-oriented approach, platform independence,
security features, and strong community support.

History of Java

3. Who developed Java and when?


o Java was developed by James Gosling and his team at Sun Microsystems in 1995.
4. What was Java initially called?
o Java was initially called Oak, but it was later renamed Java due to trademark issues.

JVM (Java Virtual Machine)

5. What is the role of the JVM in Java?


o The JVM executes Java bytecode, enabling Java applications to run on different
platforms without modification.
6. Is JVM platform-dependent or independent?
o JVM is platform-dependent, as different operating systems have their own
implementations of JVM.

JRE (Java Runtime Environment)

7. What is the purpose of JRE?


o JRE provides the necessary libraries and JVM required to run Java applications but
does not include development tools.
8. How is JRE different from JDK?
o JRE contains only the runtime environment for executing Java programs, whereas JDK
includes JRE along with development tools like the compiler.

Java Environment

9. What are the key components of the Java environment?


o The Java environment consists of JDK, JRE, and JVM.
10. What is the role of JDK in the Java environment?

 The JDK (Java Development Kit) provides tools for developing, compiling, and debugging
Java programs.

Java Source File Structure

11. What is the default extension of a Java source file?


 The default extension of a Java source file is .java.

12. What must a Java source file contain?

 A Java source file must contain at least one class definition, and it may include a public class
with a main method.

Compilation in Java

13. Which command is used to compile a Java program?

 The javac command is used to compile a Java program.

14. What is the output of Java compilation?

 Java compilation generates bytecode in a .class file, which can be executed by the JVM.

Defining Classes in Java

1. What is a class in Java?


o A class in Java is a blueprint or template for creating objects. It defines the properties
(fields) and behaviors (methods) of objects.
2. How do you define a class in Java?
o A class is defined using the class keyword followed by the class name.

class Example {
int x;
}

Constructors

3. What is a constructor in Java?


o A constructor is a special method that is automatically called when an object is created.
It initializes the object.
4. How is a constructor different from a method?
o A constructor has the same name as the class and does not have a return type, while a
method has a return type and can have any name.

Methods

5. What is a method in Java?


o A method is a block of code that performs a specific task and can be called multiple
times.
6. What are the two types of methods in Java?
o Built-in methods (e.g., Math.sqrt()) and user-defined methods (created by the
programmer).

Access Specifiers

7. What are the four access specifiers in Java?


public, private, protected, and default (no modifier).
o
8. Which access specifier allows access only within the same class?
o private

Static Members

9. What is a static member in Java?


o A static member belongs to the class rather than an instance of the class and is shared
among all objects.
10. How do you access a static method in Java?

 A static method is accessed using the class name:

ClassName.methodName();

Final Members

11. What is the purpose of the final keyword in Java?

 The final keyword is used to declare constants, prevent method overriding, and prevent class
inheritance.

12. Can a final variable be reassigned in Java?

 No, a final variable cannot be reassigned once initialized.

Comments

13. What are the types of comments in Java?

 Single-line (//), multi-line (/* */), and documentation comments (/** */).

14. What is the purpose of comments in Java?

 Comments improve code readability and help in documentation.

Data Types

15. What are the two categories of data types in Java?

 Primitive data types and reference data types.

16. Give an example of a primitive data type in Java.

 int, char, double, boolean, etc.

Variables

17. What is a variable in Java?


 A variable is a container that stores data of a specific type.

18. What are the different types of variables in Java?

 Local variables, instance variables, and static variables.

Operators

19. What is the purpose of the && operator in Java?

 The && (logical AND) operator returns true if both conditions are true.

20. What is the difference between == and = in Java?

 = is an assignment operator, while == is a comparison operator.

Control Flow

21. Name two control flow statements in Java.

 if-else and switch.

22. What is the difference between while and do-while loops?

 while checks the condition before execution, whereas do-while executes at least once before
checking the condition.

Arrays & Strings

23. How do you declare an array in Java?

 int[] arr = new int[5];

24. What is the difference between an array and a string in Java?

 An array is a collection of elements of the same type, whereas a string is a sequence of


characters.

Here are 10 tricky 2-mark questions on the given Java topics:

1. What will be the output of the following code?

java

class Test {
int x = 10;
public static void main(String[] args) {
Test obj = new Test();
System.out.println(obj.x);
}
}

Answer:

 Output: 10
 Explanation: x is an instance variable, and it is accessed using the object obj.

2. Can a constructor be final in Java? Why or why not?

Answer:

 No, a constructor cannot be final.


 Explanation: Constructors cannot be inherited, so marking them final makes no sense.

3. What happens if you call a non-static method inside a static method?

Answer:

 Compilation error unless you create an object of the class.


 Explanation: Non-static methods require an instance, whereas static methods belong to the
class.

4. What is the output of the following code?

java

class Demo {
static int x = 10;
static {
x = 20;
}
public static void main(String[] args) {
System.out.println(x);
}
}

Answer:

 Output: 20
 Explanation: The static block executes before main(), updating x to 20.

5. Can you overload a main method in Java?


Answer:

 Yes, we can overload main(), but JVM only calls public static void main(String[] args).

6. What will be the output of the following code?

class Test {
public static void main(String[] args) {
int a = 5;
System.out.println(a++ + ++a);
}
}

Answer:

 Output: 5 + 7 = 12
 Explanation:
o a++ (post-increment) returns 5, then a becomes 6.
o ++a (pre-increment) increments a to 7 before returning it.

7. What happens if a class has only private constructors?

Answer:

 The class cannot be instantiated outside its own class.


 Explanation: This is used in singleton design patterns.

8. What is the output of this program?

public class Test {


public static void main(String[] args) {
System.out.println(10 + 20 + "Java" + 10 + 20);
}
}

Answer:

 Output: 30Java1020
 Explanation:
o 10 + 20 (addition) = 30
o "Java" is a string, so 30 + "Java" results in "30Java"
o "Java" + 10 results in "30Java10", and "30Java10" + 20 gives "30Java1020".
9. What will be the output of this code?

class Test {
public static void main(String[] args) {
int arr[] = new int[5];
System.out.println(arr[0]);
}
}

Answer:

 Output: 0
 Explanation: Arrays in Java are automatically initialized to default values (0 for int).

10. Can you declare multiple classes in a single Java file?

Answer:

 Yes, but only one class can be public.


 Explanation: A Java file can have multiple classes, but only one can match the filename and be
public.

What will be the output of the following code?

class Test {
public static void main(String[] args) {
int x = 10;
int y = x++ + ++x;
System.out.println(y);
}
}

Answer:

 Output: 10 + 12 = 22
 Explanation:
o x++ (post-increment) returns 10, then x becomes 11.
o ++x (pre-increment) increases x to 12 before using it.

2. Can we declare a static variable inside a method? Why or why not?

Answer:

 No, we cannot declare a static variable inside a method.


 Explanation: Static variables belong to the class and must have a single memory allocation, but
method variables are created in stack memory each time the method is called.
3. What will be the output of this program?

class Demo {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7);
}
}

Answer:

 Output: 8
 Explanation:
o First condition (x > 2) is true, so it checks the second condition.
o x < 4 is false, so it returns 8.

4. What will be the output of this code?

class Test {
public static void main(String[] args) {
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
}
}

Answer:

 Output: false
 Explanation:
o s1 is stored in the string pool, while s2 is created in heap memory.
o == checks memory reference, not value.

5. Can a final method be overloaded?

Answer:

Yes, a final method can be overloaded.

Explanation: Overloading is method signature-based, while final prevents only overriding in


subclasses.
Q: What is a class in object-oriented programming?
A: A class is a blueprint or template that defines the attributes (data members) and behaviors
(methods) of objects.
2. Object
Q: What is an object in object-oriented programming?
A: An object is an instance of a class that has its own state (attributes) and behaviors (methods).
3. Inheritance
Q: What is inheritance in object-oriented programming?
A: Inheritance is a mechanism where a new class (subclass) derives properties and behaviors from
an existing class (superclass).
4. Super Class
Q: What is a superclass?
A: A superclass is a parent class whose properties and methods are inherited by a subclass.
5. Sub Class
Q: What is a subclass?
A: A subclass is a derived class that inherits properties and behaviors from a superclass.
6. Overriding
Q: What is method overriding?
A: Method overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass.
7. Overloading
Q: What is method overloading?
A: Method overloading allows multiple methods in the same class to have the same name but
different parameter lists.
8. Encapsulation
Q: What is encapsulation in object-oriented programming?
A: Encapsulation is the process of restricting direct access to an object's data and allowing
controlled access through methods.
9. Polymorphism
Q: What is polymorphism in object-oriented programming?
A: Polymorphism allows objects of different classes to be treated as objects of a common
superclass, enabling method overriding and overloading.
10. Abstraction
Q: What is abstraction in object-oriented programming?
A: Abstraction hides the implementation details and only shows the necessary features of an
object.
11. Interfaces
Q: What is an interface in Java?
A: An interface is a collection of abstract methods that a class can implement to provide specific
functionality.
12. Abstract Class
Q: What is an abstract class?
A: An abstract class is a class that cannot be instantiated and may contain abstract methods that
must be implemented by subclasses.
What is a package in Java?
Answer: A package in Java is a namespace that organizes a set of related classes and interfaces. It
helps in avoiding name conflicts and provides better access control.
How do you set the CLASSPATH for a package in Java?
Answer: The CLASSPATH can be set using the -classpath or -cp option in the command line or
by setting the CLASSPATH environment variable to include the directory or JAR file containing
the package.
What is the purpose of a JAR file in Java?
Answer: A JAR (Java Archive) file is used to package multiple Java class files, metadata, and
resources into a single compressed file for easy distribution and usage.
How do you create a JAR file for a library package?
Answer: A JAR file can be created using the command:
shell

jar cf library.jar -C /path/to/package .


where library.jar is the JAR file name and /path/to/package is the package directory.
What is the difference between import and static import in Java?
Answer: The import statement is used to access classes from a package, while static import allows
direct access to static members (methods and variables) of a class without specifying the class
name.
Give an example of using static import in Java.
Answer:
import static java.lang.Math.*;
public class Example {
public static void main(String[] args) {
System.out.println(sqrt(16)); // No need to write Math.sqrt()
}
}

Advantages of Using static import in Java:

1. Reduces Code Length:


o You don’t need to prefix static methods or variables with their class name every time
you use them.
2. Improves Code Readability:
o Makes the code look cleaner and easier to read by eliminating repetitive class
references.
3. Enhances Code Maintainability:
o If multiple static members are used frequently, static import reduces redundancy and
makes maintenance easier.

Example of Using static import in Java:

java
import static java.lang.Math.*; // Static import of Math class

public class StaticImportExample {


public static void main(String[] args) {
// Directly using static members of Math class
System.out.println(sqrt(25)); // Instead of Math.sqrt(25)
System.out.println(pow(2, 3)); // Instead of Math.pow(2, 3)
System.out.println(PI); // Instead of Math.PI
}
}

Without static import:

java

public class WithoutStaticImport {


public static void main(String[] args) {
System.out.println(Math.sqrt(25));
System.out.println(Math.pow(2, 3));
System.out.println(Math.PI);
}
}

As you can see, static import removes the need to write Math. every time, making the code more
concise and readable. However, excessive use can reduce code clarity, especially if multiple static
imports create ambiguity.

Comparison among class, abstract class and interface:

Feature Class Abstract Class Interface


Definition Blueprint for creating objects Partially defined class Contract for classes to implement
Instantiation Can be instantiated Cannot be instantiated Cannot be instantiated
All methods are abstract (by
May have both default in older languages); can
Implementation
Has full method implemented and abstract have default methods in modern
implementations methods versions
Use of No (in Java and most OOP
Constructors Yes Yes languages)
Multiple inheritance (via
Inheritance Type
Single inheritance Single inheritance implementation)
Can have any (public, private,
Access Modifiers
etc.) Can have any Methods are public (by default)
Constants only (static final in
Fields/Variables
Can have instance variables Can have instance variables Java)
Base class for related
Purpose
General-purpose structure subclasses Define capability/behavior
Examples class Animal {} abstract class Animal {} interface Animal {}
UNIT 2
The Idea behind Exception

Q: What is an exception in Java?


A: An exception is an unwanted or unexpected event that occurs during the execution of a program,
disrupting its normal flow.

2. Exceptions & Errors

Q: How do exceptions differ from errors in Java?


A: Exceptions are recoverable issues that occur during runtime, whereas errors are serious problems
(like OutOfMemoryError) that are usually not recoverable.

3. Types of Exception

Q: What are the two main types of exceptions in Java?


A: The two main types are Checked Exceptions (handled at compile-time) and Unchecked
Exceptions (occur at runtime).

4. Control Flow in Exceptions

Q: What happens if an exception is not caught in a Java program?


A: If an exception is not caught, it propagates up the call stack until it reaches the JVM, which
terminates the program.

5. JVM Reaction to Exceptions

Q: What does the JVM do when an exception occurs and is not handled?
A: The JVM prints an error message, the exception type, and the stack trace, then terminates the
program.

6. Use of try, catch, finally, throw, throws in Exception Handling

Q: What is the purpose of the finally block in Java exception handling?


A: The finally block is used to execute important cleanup code, such as closing resources, and runs
whether or not an exception occurs.

7. In-built and User Defined Exceptions

Q: How can you create a user-defined exception in Java?


A: A user-defined exception is created by extending the Exception class and providing a constructor to
initialize the error message.

8. Checked and Unchecked Exceptions


Q: Give an example of a checked and an unchecked exception in Java.
A: A checked exception example is IOException, while an unchecked exception example is
NullPointerException.

Question:
Consider the following Java program. What will be the output, and how does the JVM react to the
exception?
Modify the code to handle the exception properly.

java

public class ExceptionDemo {


public static void main(String[] args) {
int a = 10, b = 0;
int result = a / b; // This line causes an exception
System.out.println("Result: " + result);
}
}
Answer:
Output without handling:
php

Exception in thread "main" java.lang.ArithmeticException: / by zero


at ExceptionDemo.main(ExceptionDemo.java:5)

 JVM Reaction: The program terminates abruptly because division by zero causes an
ArithmeticException, and no exception handler (try-catch) is provided.

Modified Code with Exception Handling:

java

public class ExceptionDemo {


public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("Program continues...");
}
}

Output:

csharp

Exception caught: java.lang.ArithmeticException: / by zero


Program continues...

2. Types of Exception: Checked vs. Unchecked

Question:
The following program demonstrates checked and unchecked exceptions. Identify which exception is
checked and which is unchecked.

import java.io.*;

public class ExceptionTypeDemo {


public static void main(String[] args) {
// Unchecked Exception
int arr[] = new int[5];
System.out.println(arr[10]); // Causes an exception

// Checked Exception
FileReader file = new FileReader("test.txt"); // Causes an exception
}
}

Answer:

1. Unchecked Exception (Runtime Exception)


o System.out.println(arr[10]);
o Throws ArrayIndexOutOfBoundsException, which is a subclass of RuntimeException.
2. Checked Exception (Compile-time Exception)
o FileReader file = new FileReader("test.txt");
o Throws FileNotFoundException, which is a subclass of IOException.
o Needs to be handled using try-catch or throws in method signature.

Modified Code to Handle Both Exceptions:

java

import java.io.*;

public class ExceptionTypeDemo {


public static void main(String[] args) {
try {
// Handling Unchecked Exception
int arr[] = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught unchecked exception: " + e);
}

try {
// Handling Checked Exception
FileReader file = new FileReader("test.txt");
} catch (FileNotFoundException e) {
System.out.println("Caught checked exception: " + e);
}
}
}

3. Control Flow in Exception Handling

Question:
Analyze the control flow in the following program. Predict the output.

java

public class ControlFlowDemo {


public static void main(String[] args) {
try {
System.out.println("Try Block Start");
int data = 10 / 0; // Exception occurs
System.out.println("Try Block End");
} catch (ArithmeticException e) {
System.out.println("Catch Block Executed");
} finally {
System.out.println("Finally Block Executed");
}
System.out.println("Program Ends");
}
}

Answer:
Output:

mathematica

Try Block Start


Catch Block Executed
Finally Block Executed
Program Ends

Explanation:

"Try Block Start" prints first.

10 / 0 causes an ArithmeticException, so "Try Block End" is skipped.

Catch block executes, printing "Catch Block Executed".


finally block always executes, printing "Finally Block Executed".

The program continues after the try-catch-finally block.

4. Use of throw and throws

Question:
What will be the output of the following program? Modify the program to handle the exception using
throws.

java

public class ThrowExample {


static void checkAge(int age) {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
System.out.println("Eligible to vote");
}

public static void main(String[] args) {


checkAge(15);
System.out.println("Program Ends");
}
}

Answer:
Output (without handling):

php

Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote


at ThrowExample.checkAge(ThrowExample.java:4)
at ThrowExample.main(ThrowExample.java:9)

Modified Code Using throws:

java

public class ThrowExample {


static void checkAge(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
System.out.println("Program Ends");
}
}

Output (with handling):

pgsql

Caught Exception: Not eligible to vote


Program Ends

5. User-defined Exception

Question:
Create a custom exception InvalidAgeException and use it in a Java program to validate age.

Answer:

java

class InvalidAgeException extends Exception {


InvalidAgeException(String message) {
super(message);
}
}

public class CustomExceptionDemo {


static void validateAge(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Age must be 18 or above");
else
System.out.println("Age is valid");
}

public static void main(String[] args) {


try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Output:

php

Caught Exception: Age must be 18 or above

Explanation:

 InvalidAgeException extends Exception (checked exception).


 validateAge(16) throws InvalidAgeException, which is caught in the catch block.

You might also like