[go: up one dir, main page]

0% found this document useful (0 votes)
3 views11 pages

Java Notes

The document covers various Java programming concepts including the working of the Java Virtual Machine (JVM), Fibonacci series, dynamic binding, wrapper classes, thread creation, compile-time polymorphism, and exception handling. It provides code examples for each topic, demonstrating key features such as object-oriented principles, multilevel inheritance, and custom exceptions. Additionally, it explains the lifecycle of threads and differences between checked and unchecked exceptions.

Uploaded by

sancharim2233
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)
3 views11 pages

Java Notes

The document covers various Java programming concepts including the working of the Java Virtual Machine (JVM), Fibonacci series, dynamic binding, wrapper classes, thread creation, compile-time polymorphism, and exception handling. It provides code examples for each topic, demonstrating key features such as object-oriented principles, multilevel inheritance, and custom exceptions. Additionally, it explains the lifecycle of threads and differences between checked and unchecked exceptions.

Uploaded by

sancharim2233
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/ 11

1. With neat diagram briefly describe the working of JVM.

Java Virtual Machine (JVM) is a virtual machine that enables a computer to run Java programs. It
works in the following steps:

1.​ Loading: The class loader loads the bytecode of the class into memory.
2.​ Verification: The bytecode verifier checks the bytecode for correctness and security.
3.​ Preparation: The JVM allocates memory for static variables.
4.​ Initialization: The JVM initializes static variables and executes static blocks.
5.​ Execution: The JVM interprets the bytecode and executes it.

2. Write a java program to print the Fibonacci series.

public class FibonacciSeries {


public static void main(String[] args) {
int n = 10; // Number of terms
int firstTerm = 0, secondTerm = 1;

System.out.print("Fibonacci Series: " + firstTerm + " " + secondTerm);

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


int nextTerm = firstTerm + secondTerm;
System.out.print(" " + nextTerm);
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

3. With suitable code examples briefly describe dynamic binding of methods.


Answer:
class Parent {
void method() {
System.out.println("Parent method");
}
}
class Child extends Parent {
void method() {
System.out.println("Child method");
}
}
public class DynamicBinding {
public static void main(String[] args) {
Parent obj = new Child();
obj.method();
}
}

4. Write short note on wrapper classes with example code.

In Java, wrapper classes are used to convert primitive data types into objects. Each primitive data
type (like int, char, float, etc.) has a corresponding wrapper class. These classes are part of the
java.lang package and provide methods to convert between primitive values and objects.

The wrapper classes in Java are:

●​ Byte (for byte)


●​ Short (for short)
●​ Integer (for int)
●​ Long (for long)
●​ Float (for float)
●​ Double (for double)
●​ Character (for char)
●​ Boolean (for boolean)

public class WrapperExample {


public static void main(String[] args) {
int num = 10;
Integer numObj = num;
int unboxedNum = numObj;

System.out.println("Primitive: " + num);


System.out.println("Wrapper Object: " + numObj);
System.out.println("Unboxed Value: " + unboxedNum);
}
}
5. Write a java code to create a thread from a runnable interface.
class MyThread implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}

public class ThreadExample {


public static void main(String[] args) {
Thread thread = new Thread(new MyThread());
thread.start();
}
}

6. With suitable code example briefly describe compile time polymorphism.

class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double values


double add(double a, double b) {
return a + b;
}
}

public class CompileTimePolymorphismExample {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Calling different overloaded methods


System.out.println("Sum of two integers: " + calc.add(10, 20));
System.out.println("Sum of three integers: " + calc.add(10, 20, 30));
System.out.println("Sum of two doubles: " + calc.add(5.5, 3.2));
}
}

shape.draw(); }
}

7. Briefly describe how JVM makes the java platform independent.


The JVM acts as an intermediary between the Java program and the underlying operating system.
It translates the bytecode into machine code that is specific to the target platform. This allows
Java programs to run on any platform with a compatible JVM.

8. Write a java program to count the number of objects instantiated from a user defined

class MyClass {
static int count = 0;
MyClass() {
count++;
}
}

public class ObjectCount {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println("Number of objects: " + MyClass.count);
}
}

9. Briefly describe the difference between abstract classes and interfaces with suitable
code.

Abstract Class Example


abstract class Animal {
void eat() {
System.out.println("This animal eats food.");
}
abstract void sound(); // Abstract method
}
class Dog extends Animal {
void sound() {
System.out.println("The dog barks.");
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Calls concrete method from the abstract class
dog.sound(); // Calls the overridden method
}
}
Output:
This animal eats food.
The dog barks.

Interface Example
interface AnimalActions {
void move(); // Abstract method

default void sleep() { // Default method


System.out.println("This animal sleeps.");
}
}

class Bird implements AnimalActions {


public void move() {
System.out.println("The bird flies.");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Bird bird = new Bird();
bird.move(); // Calls the implemented method
bird.sleep(); // Calls the default method from the interface
}
}

Output:
The bird flies.
This animal sleeps.
10. Write a java program to find the number of digits of a given number inputted though
command line argument.

public class DigitCount {


public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int count = 0;
while (num > 0) {
num /= 10;
count++;
}
System.out.println("Number of digits: " + count);
}
}

11. Write a complete java program to generate custom exception while divide by zero is
attempted using a user defined exception class.

class DivideByZeroException extends Exception {


public DivideByZeroException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
int a = 10, b = 0;
try {
if (b == 0) {
throw new DivideByZeroException("Division by zero");}
int result = a / b;
} catch (DivideByZeroException e) {
System.out.println(e.getMessage());
}
}
}

12. Write a java applet to draw a rectangle with red color on green background.

import java.applet.Applet;
import java.awt.*;
public class RectangleApplet extends Applet {
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(0, 0, 300, 200);
g.setColor(Color.RED);
g.drawRect(50, 50, 200, 100);
}
}
13. Write a java program to find the factorial of given number inputted through command
line argument.

public class Factorial {


public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int factorial = 1;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.println("Factorial of " + num + " = " + factorial);
}
}

14. Write a short note on exception handling in java.

Exception handling in Java is a mechanism to handle runtime errors and ensure the smooth
execution of a program. It provides a way to respond to unexpected situations, such as invalid
user input, file not found, or network issues, without abruptly terminating the application.

public class ExceptionExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
}
}

15. With suitable java code explain the differences between ClassNotFoundException and
NoClassDefFoundError?
ClassNotFoundException Example:

public class ClassNotFoundExceptionExample {


public static void main(String[] args) {
try {
Class.forName("com.nonexistent.ClassName");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException occurred: " + e.getMessage());
}
}
}

NoClassDefFoundError:

public class NoClassDefFoundErrorExample {


public static void main(String[] args) {
MissingClassExample example = new MissingClassExample();
example.display();
}
}

class MissingClassExample {
void display() {
System.out.println("Class is available.");
}
}
16. Write a java program to find whether a given string is palindrome or not.

public class PalindromeCheck {


public static void main(String[] args) {
String str = args[0];
int i = 0, j = str.length() - 1;
boolean isPalindrome = true;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
isPalindrome = false;
break;
}
i++;
j--;
}
if (isPalindrome) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");
}
}
}

17. Describe key features of object-oriented paradigm.

Encapsulation: Bundling data and methods within a class.


Inheritance: Creating new classes based on existing ones.
Polymorphism: The ability of objects to take on many forms.
Abstraction: Hiding implementation details and exposing only essential features.
18. Briefly describe the lifecycle of thread.

New: Thread is created but not started.


Active: The thread moves to the active state after invoking the start() method.
-​ Runnable: Thread is ready to run but waiting for CPU time.
-​ Running: Thread is executing its task.
Blocked/Waiting: The thread is temporarily inactive, waiting for a resource or signal.
-​ Blocked: Waiting for a resource (e.g., printer)
-​ Waiting: Paused indefinitely until notified (e.g., join() for a child thread).
Timed Waiting:The thread waits for a specific time to avoid indefinite waiting (e.g., sleep(time))

Terminated: The thread completes execution or ends due to an exception. It is permanently dead
and cannot be restarted.
19. Differentiate between Checked Exception and Unchecked Exceptions in Java

20. With suitable code example describe multilevel inheritance.

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("This mammal walks on land.");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}
public class MultilevelInheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();

dog.eat();
dog.walk();
dog.bark();
}
}

You might also like