[go: up one dir, main page]

0% found this document useful (0 votes)
22 views15 pages

Important Question Answers

The document contains a series of questions and answers related to Java programming concepts, including loops, keywords, bytecode, exception handling, and JavaFX. It covers topics such as the execution of statements, the use of 'this' and 'super' keywords, types of inheritance, and the differences between interfaces and abstract classes. Additionally, it discusses features of Java, types of exceptions, and provides code examples for various concepts.

Uploaded by

xbu029
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)
22 views15 pages

Important Question Answers

The document contains a series of questions and answers related to Java programming concepts, including loops, keywords, bytecode, exception handling, and JavaFX. It covers topics such as the execution of statements, the use of 'this' and 'super' keywords, types of inheritance, and the differences between interfaces and abstract classes. Additionally, it discusses features of Java, types of exceptions, and provides code examples for various concepts.

Uploaded by

xbu029
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/ 15

Q1. How many times is the println statement executed?

for (int i = 0; i < 10; i++)


for (int j = 0; j < i; j++)
System.out.println(i * j);

Explanation:

 The outer loop (i) runs from 0 to 9 (10 iterations).


 The inner loop (j) runs from 0 to i - 1.
 This means:
 When i = 0 → 0 times
 When i = 1 → 1 time
 When i = 2 → 2 times
 …
 When i = 9 → 9 times
 Total iterations = 1 + 2 + 3 + ... + 9 = 45

✅ Answer: The println statement is executed 45 times.

Q2. What is the use of this keyword? How is it different from super keyword?

this Keyword:

Used to refer to the current class object. Common uses:

 To distinguish between instance variables and parameters


 To call constructors or methods of the same class

Example:

class Student {
int id;
Student(int id) {
this.id = id; // Refers to current object
}
}

super Keyword:

Used to refer to the parent class object. Common uses:

 To call superclass methods/constructors


 To access overridden methods or hidden variables

Example:

class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
System.out.println(this.x); // Child’s x
System.out.println(super.x); // Parent’s x
}
}
Keyword Refers To Usage
this Current class Access variables, methods, constructors
super Parent (super) class Access overridden or hidden members

Q3. What is Java Bytecode? What is its extension? Which software is needed
to run it?

Java Bytecode:

 Intermediate code generated by the Java compiler (javac).


 It is not platform-specific; it runs on the Java Virtual Machine (JVM).
 Secure and portable format.

Extension of Bytecode file:

 .class

Software needed to run:

 JVM (Java Virtual Machine) – part of the Java Runtime Environment (JRE).

✅ Example:

javac Hello.java // Compiles to Hello.class


java Hello // Runs using JVM

Q4. Program demonstrating import, new, this, break, continue. How to compile
and run.
import java.util.Scanner; // import

class Demo {
int num;

Demo(int num) {
this.num = num; // this
}

void show() {
for (int i = 1; i <= num; i++) {
if (i == 3) continue; // continue
if (i == 6) break; // break
System.out.println("i = " + i);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

Demo d = new Demo(n); // new


d.show();
}
}

How to Compile and Run:

javac Demo.java // Compile


java Demo // Run

Q5. Consider class A as parent of B. Which will cause a compilation error?

Given:

class A {}
class B extends A {}

Now, evaluate:

1. ✅A a = new A(); – Valid


2. ✅A a = new B(); – Valid (polymorphism)
3. ❌B b = new A(); – Invalid (cannot assign parent object to child reference)
4. ✅B b = new B(); – Valid

✅ Answer: Statement iii) B b = new A(); will cause a compilation error.

Q6. Java Program to evaluate math expression from command line

Code:

java
Copy code
public class EvaluateExpression {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java EvaluateExpression num1
operator num2");
return;
}

double result = 0;
double num1 = Double.parseDouble(args[0]);
char operator = args[1].charAt(0);
double num2 = Double.parseDouble(args[2]);

switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num2 != 0 ? num1 / num2 : Double.NaN; break;
default: System.out.println("Invalid operator"); return;
}

System.out.println("Result = " + result);


}
}

How to Run:

bash
Copy code
javac EvaluateExpression.java
java EvaluateExpression 10 + 5

Q7. Layout Panes in JavaFX

JavaFX provides layout panes to manage the position and size of UI elements.

Layout Pane Description

HBox Places elements in a horizontal row

VBox Places elements in a vertical column

BorderPane Divides layout into top, bottom, left, right, center

GridPane Organizes components in a grid of rows and columns

FlowPane Lays out components in a flow that wraps at boundary

StackPane Stacks components on top of each other

AnchorPane Anchors nodes to edges of the pane

✅ Each is useful based on the layout needed in the application.

Q8. List features of Java and explain any two

Features of Java:

1. Platform Independent
2. Object-Oriented
3. Simple
4. Secure
5. Robust
6. Multithreaded
7. High Performance
8. Dynamic and Extensible
Explaining Two:

1. Platform Independent:
o Java code is compiled into bytecode (.class file) which can run on any system with a
JVM.
o "Write Once, Run Anywhere"
2. Object-Oriented:
o Everything in Java is treated as an object.
o It supports concepts like inheritance, encapsulation, abstraction, and polymorphism.

Q9. Architecture of JavaFX

JavaFX architecture has several layers:

1. JavaFX API: The topmost layer providing GUI components like shapes, charts, controls.
2. Quantum Toolkit: Acts as a bridge between JavaFX API and the operating system.
3. Prism: Graphics pipeline that uses DirectX/OpenGL for rendering.
4. Glass Windowing Toolkit: Handles native windowing, input, and events.
5. Java Runtime: Underlying Java Virtual Machine (JVM).

✅ This layered architecture enables cross-platform support and hardware acceleration.

Q10. Access Specifiers and Modifiers in Java

Access Specifiers:

Control the visibility of classes and members.

Specifier Scope

public Accessible everywhere

private Within the class only

protected Same package or subclass

(default) Within same package only

Modifiers:

 Non-access modifiers that define behavior.


 Examples: final, static, abstract, synchronized, volatile

✅ Example:

java
Copy code
public class MyClass {
private static final int VALUE = 10;
}

Q11. Types of Inheritance in Java

1. Single Inheritance:
o One subclass inherits from one superclass.

java
Copy code
class A {}
class B extends A {}

2. Multilevel Inheritance:
o Chain of inheritance.

java
Copy code
class A {}
class B extends A {}
class C extends B {}

3. Hierarchical Inheritance:
o Multiple classes inherit from one base class.

java
Copy code
class A {}
class B extends A {}
class C extends A {}

✅ Note: Java does not support multiple inheritance using classes (to avoid ambiguity), but interfaces
can be used.

Q12. Try-catch for Hierarchical Exception Handling


java
Copy code
public class HierarchicalExceptionExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 100 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception Caught");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Exception Caught");
} catch (Exception e) {
System.out.println("General Exception Caught");
}
}
}
 The most specific exception should be caught first.
 Catching parent Exception first will cause compilation error.

Q13. Constructors: Default, Parameterized, Shallow and Deep Copy

Default Constructor:

No arguments.

java
Copy code
class A {
A() {
System.out.println("Default Constructor");
}
}

Parameterized Constructor:

With arguments.

java
Copy code
class A {
A(int x) {
System.out.println("x = " + x);
}
}

Shallow Copy:

Copies references.

java
Copy code
A a1 = new A();
A a2 = a1; // Both point to same object

Deep Copy:

Copies actual values (new object).

java
Copy code
A a2 = new A(a1); // Copy constructor

Q14. Define Interface and Difference from Class

Interface:
A blueprint for a class with abstract methods.

java
Copy code
interface Animal {
void sound();
}

Differences from Class:

Feature Interface Class

Instantiation Cannot be instantiated Can be instantiated

Methods Only abstract/default/static Concrete methods allowed

Inheritance Multiple interfaces allowed Single class inheritance only

✅ Interfaces enable abstraction and multiple inheritance.

Q15. Syntax, Runtime, and Logic Errors

1. Syntax Error (Compile-time):


o Errors in code structure.

java
Copy code
int a = ; // Missing value

2. Runtime Error:
o Occur during execution.

java
Copy code
int a = 10 / 0; // ArithmeticException

3. Logic Error:
o Produces wrong output.

java
Copy code
System.out.println("Sum = " + (a - b)); // Should be a + b

✅ Compiler detects syntax errors, runtime and logic must be tested.

Q16. Difference between String and StringBuffer

Feature String StringBuffer

Mutability Immutable Mutable


Feature String StringBuffer

Thread-Safe Not thread-safe Thread-safe

Performance Slower for many modifications Faster due to in-place changes

Package java.lang.String java.lang.StringBuffer

Example:

java
Copy code
String s = "Hello";
s.concat("World"); // s remains "Hello"

StringBuffer sb = new StringBuffer("Hello");


sb.append("World"); // sb becomes "HelloWorld"

✅ Use StringBuffer when multiple string manipulations are needed.

Q17. throw and throws with Example

throw:

 Used to explicitly throw an exception.

java
Copy code
throw new ArithmeticException("Divide by Zero");

throws:

 Declares exceptions a method might throw.

java
Copy code
void check() throws IOException {
// code that might throw exception
}

Example Program:

java
Copy code
class Example {
static void validate(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible");
}

public static void main(String[] args) {


validate(15);
}
}

✅ throw = throw an exception


✅ throws = declare a method might throw exception

Q18. Program: StopWatch Class


java
Copy code
class StopWatch {
private long startTime;
private long endTime;

public StopWatch() {
startTime = System.currentTimeMillis();
}

public void start() {


startTime = System.currentTimeMillis();
}

public void stop() {


endTime = System.currentTimeMillis();
}

public long getElapsedTime() {


return endTime - startTime;
}

public static void main(String[] args) throws InterruptedException {


StopWatch sw = new StopWatch();
Thread.sleep(1000); // Simulate time delay
sw.stop();
System.out.println("Elapsed Time: " + sw.getElapsedTime() + " ms");
}
}

✅ Uses System.currentTimeMillis() to measure elapsed time.

Q19. Difference: Checked vs Unchecked Exceptions

Feature Checked Exception Unchecked Exception

Check Time Compile-time Runtime

Handling
Must handle using try-catch Optional
Required?

IOException, NullPointerException,
Examples
SQLException ArithmeticException
Example:

java
Copy code
// Checked
FileReader fr = new FileReader("file.txt"); // Must handle

// Unchecked
int x = 10 / 0; // ArithmeticException

✅ Checked = Compiler forces handling


✅ Unchecked = Programmer responsibility

Q20. Throw and Throws (Repeated from Q17)

Q21. JavaFX Program: Red Circle


java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class RedCircle extends Application {


public void start(Stage primaryStage) {
Circle circle = new Circle(100); // radius
circle.setFill(Color.RED);

StackPane root = new StackPane(circle);


Scene scene = new Scene(root, 300, 300);

primaryStage.setTitle("Red Circle");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

✅ This will create a red-filled circle centered in the scene.

Q22. Try-catch with ArithmeticException and InputMismatchException


java
Copy code
import java.util.Scanner;
import java.util.InputMismatchException;

public class ExceptionDemo {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter number: ");
int num = sc.nextInt();

int result = 100 / num;


System.out.println("Result = " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} catch (InputMismatchException e) {
System.out.println("Invalid input type.");
}
}
}

Q23. Types of Constructors

1. Default Constructor:
o No arguments.

java
Copy code
class A {
A() { System.out.println("Default"); }
}

2. Parameterized Constructor:
o Takes arguments.

java
Copy code
A(int x) { this.x = x; }

3. Copy Constructor:
o Copies data from another object.

java
Copy code
A(A obj) { this.x = obj.x; }

✅ Java does not provide a built-in copy constructor, but you can define it manually.

Q24. Types of Polymorphism

1. Compile-time Polymorphism (Method Overloading):


o Same method name, different parameters.
java
Copy code
void show(int x)
void show(String y)

2. Run-time Polymorphism (Method Overriding):


o Method is redefined in subclass.

java
Copy code
class A {
void display() {}
}
class B extends A {
void display() {} // overridden
}

✅ Polymorphism allows the same method to behave differently.

Q25. Inheritance and Its Types

Inheritance allows one class to acquire properties of another.

Types:

 Single
 Multilevel
 Hierarchical

Example:

java
Copy code
class A {
void show() { System.out.println("A"); }
}
class B extends A {
void display() { System.out.println("B"); }
}

✅ Reusability and code maintainability are benefits of inheritance.

Q26. Final Class, Field, and Method

 final class: Cannot be inherited.

java
Copy code
final class A {} // class B extends A → Error

 final field: Cannot be changed.


java
Copy code
final int x = 10; // x = 20 → Error

 final method: Cannot be overridden.

java
Copy code
class A {
final void display() {}
}

✅ Final keyword enforces restriction.

Q27. JavaFX: Scene and Stage

 Creating Scene:

java
Copy code
Scene scene = new Scene(root, width, height);

 Setting Scene to Stage:

java
Copy code
stage.setScene(scene);
stage.show();

 Multiple Scenes: Yes, possible. You can switch scenes dynamically:

java
Copy code
stage.setScene(scene2);

✅ You can use multiple scenes for different views like login → dashboard.

Q28. Interface vs Abstraction

Feature Interface Abstract Class

Methods All are abstract by default Can have both concrete and abstract methods

Fields Only static & final Can have variables

Multiple Inheritance Yes No

Constructor Not allowed Allowed


✅ Use interface for full abstraction and multiple inheritance.

Q29. Abstraction with Example

Abstraction = hiding internal implementation, showing only essential features.

Using Abstract Class:

java
Copy code
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}

✅ You cannot create object of abstract class.

Q30. JavaFX Mouse and Key Event Handler

Mouse Events:

java
Copy code
circle.setOnMouseClicked(e -> {
System.out.println("Mouse Clicked");
});

Key Events:

java
Copy code
scene.setOnKeyPressed(e -> {
System.out.println("Key Pressed: " + e.getCode());
});

✅ JavaFX allows rich interactivity using event handlers for UI components.

You might also like