0% found this document useful (0 votes)
30 views23 pages

Java Answers

The document provides a comprehensive overview of various Java programming concepts, including command line arguments, threads, exception handling, and object-oriented principles such as inheritance and encapsulation. It includes code examples for better understanding and highlights key differences between related concepts, such as classes and abstract classes, as well as interfaces and abstract methods. Additionally, it discusses Java's platform independence, garbage collection, and the significance of keywords like 'final', 'finally', and 'super'.

Uploaded by

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

Java Answers

The document provides a comprehensive overview of various Java programming concepts, including command line arguments, threads, exception handling, and object-oriented principles such as inheritance and encapsulation. It includes code examples for better understanding and highlights key differences between related concepts, such as classes and abstract classes, as well as interfaces and abstract methods. Additionally, it discusses Java's platform independence, garbage collection, and the significance of keywords like 'final', 'finally', and 'super'.

Uploaded by

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

1.

Command Line Arguments in Java

Ans:

public class CommandLineArgs {

public static void main(String[] args) {

for (String arg : args) {

System.out.println(arg);

2. What is a Thread?

A thread is a lightweight process that can run concurrently with other threads. Threads can be
created in two ways:

- Extending the Thread class

- Implementing the Runnable interface

3. Example of Thread and Advantages of Multithreading

Ans:

class MyThread extends Thread {

public void run() {

System.out.println("Thread is running");

public class ThreadExample {

public static void main(String[] args) {

MyThread t = new MyThread();

t.start();

Advantages of Multithreading:

- Improved performance

- Resource sharing

- Simplified program structure


4. Use of Finally

Ans:

public class FinallyExample {

public static void main(String[] args) {

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("Arithmetic Exception");

} finally {

System.out.println("This block always executes");

5. Unicode in Java

Ans:

Unicode is a character encoding standard that allows Java to support internationalization. It enables
the representation of characters from multiple languages.

6. Difference Between Class and Abstract Class

Ans:

- Class: Can be instantiated, can have concrete methods.

- Abstract Class: Cannot be instantiated, can have abstract methods.

Example:

abstract class Animal {

abstract void sound();

class Dog extends Animal {

void sound() {

System.out.println("Bark");

}
7. Print Pattern

Ans:

import java.util.Scanner;

public class Pattern {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of lines: ");

int n = sc.nextInt();

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(j + " ");

System.out.println();

8. Constructor Overloading

Ans:

Constructor overloading allows a class to have more than one constructor with different parameters.

class Box {

Box() {

System.out.println("Default constructor");

Box(int length) {

System.out.println("Length: " + length);

9. Super Keyword

Ans: The `super` keyword is used to refer to the immediate parent class. Its purposes include:

- Accessing parent class methods


- Accessing parent class constructors
- Accessing parent class fields
10. Sort Array in Ascending Order

Ans:

import java.util.Arrays;

public class SortArray {

public static void main(String[] args) {

int[] arr = {5, 2, 8, 1, 3};

Arrays.sort(arr);

System.out.println(Arrays.toString(arr));

11. Garbage Collection and finalize() Method

Ans:

Garbage collection is the process of automatically freeing memory by removing objects that are no
longer in use. The `finalize()` method is called by the garbage collector before an object is removed.

12. Thread Creation (Repeated)

Refer to answer 2.

13. Interfaces and Multiple Inheritance

Ans:

Java does not support multiple inheritance directly but allows it through interfaces.

interface A {

void methodA();

interface B {

void methodB();

class C implements A, B {

public void methodA() {

System.out.println("Method A");

public void methodB() {

System.out.println("Method B"); }
}
14. Explain the each word in the statement public static void main (String args[])

Ans:

- public: Access modifier

- static: Can be called without creating an instance

- void: No return value

- main: Entry point of the program

- String args[]: Array of strings for command line arguments

15. Difference Between Abstract Class and Interface

Ans:

- Abstract Class: Can have method implementations, can have state (fields).

- Interface: Cannot have method implementations (until Java 8), only method signatures.

16. Print Pattern

Ans:

import java.util.Scanner;

public class Pattern2 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number of lines: ");

int n = sc.nextInt();

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i + " ");

System.out.println();

}
17. Constructor and Its Role

Ans:

A constructor initializes an object when it is created.

class Car {

Car() {

System.out.println("Car created");

18. StringBuffer length() vs capacity()

Ans:

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

System.out.println("Length: " + sb.length());

System.out.println("Capacity: " + sb.capacity());

19. Hierarchical Inheritance

Ans:

class A {

void display() {

System.out.println("Class A");

class B extends A {

void display() {

System.out.println("Class B");

class C extends A {

void display() {
System.out.println("Class C");

public class Test {

public static void main(String[] args) {

A obj = new B();

obj.display(); // Dynamic dispatch

20. Copy Constructor

Ans:

A copy constructor creates a new object as a copy of an existing object.

class Box {

int length;

Box(Box b) {

this.length = b.length;

21. Final Keyword

Ans:

The `final` keyword can be used to:

- Declare constants

- Prevent method overriding

- Prevent inheritance
22. Base Class Constructor

Ans:

In multilevel inheritance, the base class constructor is called automatically.

class A {

A() {

System.out.println("Class A Constructor");

class B extends A {

B() {

System.out.println("Class B Constructor");

class C extends B {

C() {

System.out.println("Class C Constructor");

}
23. Summation Series

Ans:

import java.util.Scanner;

public class SeriesSum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter n: ");

int n = sc.nextInt();

double sum = 0;

for (int i = 1; i <= n; i++) {

sum += (i % 2 == 0 ? -1 : 1) * (double) i / (i + 1);

System.out.println("Sum: " + sum);

24. Encapsulation and Data Hiding

Ans:

class Encapsulated {

private int data;

public void setData(int data) {

this.data = data;

public int getData() {

return data;

}
25. Static Data Member

Ans:

Static data members are shared among all instances of a class.

Static Method vs Non-Static Method:

- Static methods can be called without an instance.

- Non-static methods require an instance to be called.

26. Multilevel Inheritance

Ans:

class A {

class B extends A {

class C extends B {

27. Catch Multiple Exceptions

Ans:

public class MultipleExceptions {

public static void main(String[] args) {

try {

int a = 10 / 0;

String s = null;

s.length();

} catch (ArithmeticException | NullPointerException e) {

System.out.println(e);

}
Access Specifiers: Control the visibility of class members.

- Public: Accessible from anywhere.

- Private: Accessible only within the class.

- Protected: Accessible within the package and subclasses.

28. User Defined Exception

Ans:

class MyException extends Exception {

public MyException(String message) {

super(message);

public class TestException {

public static void main(String[] args) {

try {

throw new MyException("Custom Exception");

} catch (MyException e) {

System.out.println(e.getMessage());

29. Box Class

Ans:

class Box {

int length, breadth, height;

Box(int l, int b, int h) {

length = l;

breadth = b;
height = h;

int volume() {

return length * breadth * height;

public class BoxTest {

public static void main(String[] args) {

Box box1 = new Box(1, 2, 3);

Box box2 = new Box(4, 5, 6);

System.out.println("Volume of box1: " + box1.volume());

System.out.println("Volume of box2: " + box2.volume());

30. Platform Independence and Byte Code

Ans:

Java's Platform Independence

Java is called a platform-independent language because of its ability to "Write Once, Run Anywhere"
(WORA). This means that Java code compiled on one system can run on any other system with a Java
Virtual Machine (JVM) installed, regardless of the underlying operating system or hardware
architecture.

How does it work?

1. Compilation: When you compile Java source code, it's not directly translated into machine
code specific to a particular operating system. Instead, it's compiled into bytecode.

2. Bytecode: Bytecode is an intermediate code that's independent of the underlying hardware


and operating system. It's a set of instructions that can be understood and executed by the
JVM.

3. JVM: The JVM is a software layer that sits between the bytecode and the operating system.
It acts as an interpreter for the bytecode, translating it into machine code that the specific
operating system can understand and execute.
31. Generic Catch Block

Ans:

Justification:

• Order of Execution: In a try-catch block, the catch blocks are executed in the order they
appear.

• Specificity: Specific catch blocks (e.g., catch(IOException e)) handle specific types of
exceptions.

• Generic Catch Block: The generic catch(Exception e) block catches any exception that occurs
within the try block.

Why Place Generic Catch Last?

1. Specificity: If a specific catch block can handle an exception, it will be executed before the
generic catch block. This ensures that the most specific and relevant handling logic is applied.

2. Avoiding Incorrect Handling: Placing the generic catch block first would cause it to catch all
exceptions, even those that could be handled more specifically by other catch blocks. This
might lead to improper or incomplete handling of the exception.

32. Mutable vs Immutable Strings

Ans:
- Mutable: Can be changed (e.g., StringBuilder).

- Immutable: Cannot be changed (e.g., String).

Difference between equals() and ==:

- `equals()`: Compares content.

- `==`: Compares references.

33. Factorial Program

Ans:

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = sc.nextInt();
int fact = 1;

for (int i = 1; i <= n; i++) {

fact *= i;

System.out.println("Factorial: " + fact);

34. Single Level Inheritance

Ans:

class Parent {

class Child extends Parent {

35. Throws Keyword

Ans:

class Test {

void method() throws Exception {

throw new Exception("Exception thrown");

public class ThrowsExample {

public static void main(String[] args) {

Test t = new Test();

try {

t.method();

} catch (Exception e) {

System.out.println(e.getMessage());

}
36. Access Specifiers (Repeated)

Ans: Refer to answer 27.

37. User Defined Exception (Repeated)

Ans: Refer to answer 28.

38. Abstract Class Shape

Ans:

abstract class Shape {

abstract double area();

class Rectangle extends Shape {

double length, width;

Rectangle(double l, double w) {

length = l;

width = w;

double area() {

return length * width;

class Triangle extends Shape {

double base, height;

Triangle(double b, double h) {

base = b;

height = h;

double area() {

return 0.5 * base * height;

}
public class ShapeTest {

public static void main(String[] args) {

Shape rect = new Rectangle(5, 10);

Shape tri = new Triangle(5, 10);

System.out.println("Rectangle Area: " + rect.area());

System.out.println("Triangle Area: " + tri.area());

39. String vs StringBuffer

Ans:

- String: Immutable, cannot be changed after creation.

- StringBuffer: Mutable, can be modified.

40. Print Prime Numbers within 500

Ans:

public class PrimeNumbers {

public static void main(String[] args) {

for (int i = 2; i < 500; i++) {

boolean isPrime = true;

for (int j = 2; j <= Math.sqrt(i); j++) {

if (i % j == 0) {

isPrime = false;

break;

if (isPrime) {

System.out.print(i + " ");

}
}

41. final, finally, finalize

Ans:

- final: Used to declare constants or prevent overriding.

- finally: Block that executes after try-catch, regardless of exceptions.

- finalize(): Method called by the garbage collector before an object is removed.

42. Objects Passed by Reference

Ans:

class MyClass {

int value;

MyClass(int value) {

this.value = value;

public class ReferenceExample {

public static void main(String[] args) {

MyClass obj = new MyClass(10);

modify(obj);

System.out.println(obj.value); // Output: 20

static void modify(MyClass obj) {

obj.value = 20;

43. Advantages of 'this' Keyword

Ans:

- Distinguishes between class fields and parameters.

- Refers to the current object.


- Can be used to call other constructors

44. Why interface data are public,static and final?


Ans:
1. Public

• Reason: Interface members are meant to define a contract that is accessible to all
implementing classes. Making them public ensures that they are universally visible to any
class implementing the interface.

• Implication: There is no need to explicitly use the public modifier; it is implied.

2. Static

• Reason: Interface fields are constants and do not belong to any specific instance. They are
associated with the interface itself, rather than with objects of the implementing classes.

• Implication: This ensures that the variable can be accessed without creating an instance of
the interface.

3. Final

• Reason: Interface fields are constants by design. They are meant to represent fixed values
that cannot be changed. The final modifier ensures that the value of the variable cannot be
modified after initialization.

• Implication: This enforces immutability for interface fields, ensuring consistency across all
uses.

45. Why interface methods are abstract and final?

Ans:

1. Abstract (by default)

• Reason: Methods in an interface define a contract or blueprint that any implementing class
must follow. Declaring them as abstract (implicitly) means that they do not have a method
body in the interface itself and must be implemented by the classes that implement the
interface.

• Implication:

o It ensures that the implementing classes provide their own implementation for the
method.

o Starting from Java 8, interfaces can also have default methods (with method bodies)
and static methods, which are exceptions to the "abstract by default" rule.

2. Final (Not Allowed)

• Reason: Declaring interface methods as final would contradict the purpose of an interface.
An interface is designed to allow implementing classes to provide their own implementation
of the methods. The final modifier, on the other hand, prevents overriding, which would
make the interface unusable as a contract for implementation.
• Why Final Is Not Allowed:

o If a method in an interface were declared final, no class could provide its own
implementation for that method, defeating the purpose of the interface itself.

o Interfaces promote flexibility and polymorphism, which require methods to be


overridden.

46. Differentiate between Error and Exception class in Java.

Ans:

47. Define abstraction. State how it differs from encapsulation.

Ans:

Abstraction

• Definition: Abstraction is the process of simplifying complex systems by focusing on the


essential features while hiding unnecessary1 details.2 It's about presenting only the necessary
information to the user, making it easier to understand and interact with.3

• Focus: What the object does, not how it does it.4

• Implementation: Achieved through abstract classes and interfaces.5

Encapsulation

• Definition: Encapsulation is the mechanism of bundling data (attributes) and methods


(functions) that operate on the data within a single unit (class).6 It controls access to the
data, protecting it from unauthorized modification and misuse.7

• Focus: How the object's data is accessed and manipulated.8

• Implementation: Achieved through access modifiers (public, private, protected).9

Key Differences
• Focus: Abstraction focuses on what the object does, while encapsulation focuses on how the
object's data is accessed and manipulated.10

• Implementation: Abstraction is achieved through abstract classes and interfaces, while


encapsulation is achieved through access modifiers.1112

• Purpose: Abstraction simplifies complex systems by hiding unnecessary details, while


encapsulation protects data integrity and provides controlled access.13

In essence:

• Abstraction is about simplifying the user experience by hiding complexity.14

• Encapsulation is about protecting data and controlling access.15

While they are distinct concepts, they often work together. Encapsulation can be used to implement
abstraction by hiding the internal details of a class and providing a controlled interface for accessing
its functionality.16

48. “In a two-dimensional array in JAVA, the length of every 1D array may differ”- justify the
statement with a program.

Ans:

In Java, a two-dimensional array can indeed consist of rows that vary in length, which is commonly
referred to as a *jagged array*. This is because a two-dimensional array in Java is essentially an array
of arrays, allowing each inner array (or row) to have a different number of elements.

Justification of the Statement

The statement that "the length of every 1D array may differ" in a two-dimensional array can be
demonstrated through the concept of jagged arrays. In contrast to rectangular arrays where each
row has the same number of columns, jagged arrays allow for flexibility in the number of elements
per row.

Example Program

Here’s a simple Java program for a jagged array:

public class JaggedArrayExample {

public static void main(String[] args) {

int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[2];

jaggedArray[1] = new int[4];


jaggedArray[2] = new int[3];

jaggedArray[0][0] = 1;

jaggedArray[0][1] = 2;
jaggedArray[1][0] = 3;

jaggedArray[1][1] = 4;

jaggedArray[1][2] = 5;

jaggedArray[1][3] = 6;

jaggedArray[2][0] = 7;

jaggedArray[2][1] = 8;

jaggedArray[2][2] = 9;

for (int i = 0; i < jaggedArray.length; i++) {

for (int j = 0; j < jaggedArray[i].length; j++) {

System.out.print(jaggedArray[i][j] + " ");

System.out.println();

Output:

When this program is executed, it will produce the following output:

12

3456

789

Explanation:

- Declaration: The `jaggedArray` is declared as an array of arrays (`int[][]`), where each element can
be initialized separately.

- Initialization: Each row of the `jaggedArray` is initialized with different lengths:

- The first row has 2 elements.

- The second row has 4 elements.


- The third row has 3 elements.

- Accessing Elements: The program uses nested loops to access and print the elements of the jagged
array. Each inner loop iterates through the length of the current row, demonstrating that each row
can indeed have a different number of columns.

49. Frame a class Car which will contain a data member (id) which represents id of each car and a
static variable count whose value indicates total number of cars participating in the race. Write a
program in Java which will frame the above Car class and create three Car class objects and assign
their id through constructor. Also, add a static method carcount() inside the car class which will
display total number of cars in the race. Add a not static method disp() inside the Car class to
display id of the car objects.

Ans:

public class Car {

private int id;

private static int count = 0;

public Car(int id) {

this.id = id;

count++;

public static void carCount() {

System.out.println("Total number of cars in the race: " + count);

public void disp() {

System.out.println("Car ID: " + id);

public static void main(String[] args) {

Car car1 = new Car(101);

Car car2 = new Car(102);

Car car3 = new Car(103);

car1.disp();

car2.disp();

car3.disp();

Car.carCount();

}
}

Output:

Car ID: 101

Car ID: 102

Car ID: 103

Total number of cars in the race: 3

50. Differentiate between checked and unchecked exception in Java.

Ans:

You might also like