0% found this document useful (0 votes)
18 views

Codeinwithjava

Uploaded by

Epshita Moitra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Codeinwithjava

Uploaded by

Epshita Moitra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

CODE IN WITH JAVA

CHAPTER-1
1.What is Object-Oriented Programming Language?

ANS: An object-oriented programming language (OOPL) is a type of programming language


that is based on the concept of objects, which can contain data in the form of fields (attributes
or properties), and code in the form of procedures (methods). The primary goal of OOPLs is
to increase the flexibility and maintainability of programs by grouping related data and
operations into objects.

2. Why Java is an Object-Oriented Programming Language?

ANS: Java is considered an object-oriented programming language because it follows all the
principles of object-oriented programming:

• Encapsulation: Bundling data and methods that operate on the data into a single unit
(class).
• Inheritance: Mechanism by which one class can inherit properties and methods of
another class.
• Polymorphism: Ability of objects of different classes to be treated as objects of a
common superclass.

Java supports the creation and manipulation of objects, inheritance through class
hierarchies, and polymorphism through interfaces and abstract classes.

3. Difference between Procedural Programming Language and Object-


Oriented Programming Language

ANS: Procedural Programming:

• Focuses on functions or procedures that operate on data.


• Data is often shared between functions using global variables.
• Emphasizes procedures or routines that perform operations on data.
• Examples: C, Fortran.

Object-Oriented Programming:

• Focuses on objects that contain data and methods to manipulate that data.
• Data is encapsulated within objects and accessed via methods.
• Emphasizes data and operations on the data as a single unit.
• Examples: Java, C++, Python.

4. Difference between Abstraction and Class and Object

ANS: Abstraction:
• Abstraction is the concept of hiding the complex implementation details and showing
only the essential features of the object.
• Achieved using abstract classes and interfaces in Java.
• It helps in managing complexity and also improves maintainability by reducing code
redundancy.

Class:

• A class is a blueprint or template for creating objects in Java.


• It defines the structure and behavior (methods) that objects of the class will have.
• A class can contain fields (attributes) and methods.

Object:

• An object is an instance of a class.


• It has state (attributes) and behavior (methods).
• Objects are created using the new keyword followed by a constructor of the class.

5. What is the difference between Abstract class and Interface in Java?

ANS: Abstract Class:

• Can have both abstract (incomplete) and concrete (complete) methods.


• Can have instance variables.
• Cannot be instantiated, but can be subclassed.
• Used to provide a common superclass for a set of subclasses.

Interface:

• Contains only abstract methods (methods without a body) and static final constants.
• Cannot have instance variables (before Java 8).
• Cannot be instantiated, but can be implemented by classes.
• Used to achieve abstraction and multiple inheritance in Java.

6. What are the basic features of OOP?

ANS: The basic features of Object-Oriented Programming (OOP) are:

• Encapsulation: Bundling of data and methods that operate on the data into a single
unit (class).
• Inheritance: Mechanism by which one class can inherit properties and methods of
another class.
• Polymorphism: Ability to process objects of different classes through a common
interface (method overriding and method overloading).
• Abstraction: Hiding the complex implementation details and showing only the
essential features of the object.
• Class: Blueprint or template for creating objects.
• Object: Instance of a class.
• Message Passing: Objects communicate with each other through message passing.
7. Write a small Java code which will print the message “Hello World”.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

8. Write a small Java Code and mention the steps to compile and execute of
your code.

ANS: Java Code (HelloWorld.java):


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

Steps to compile and execute the code:

1. Compilation: Open a terminal or command prompt and navigate to the directory


containing HelloWorld.java.

javac HelloWorld.java

This will compile HelloWorld.java and generate a bytecode file


HelloWorld.class.

2. Execution: After successful compilation, execute the program using the java
command:

java HelloWorld

Output:

Hello World

9. How we are achieving data security in OOP?

ANS: In OOP, data security is achieved primarily through the concept of Encapsulation.
Encapsulation ensures that the internal state of an object is protected from unwanted access
and modification. Here’s how it helps in achieving data security:

• Access Modifiers: Java provides access modifiers (e.g., private, protected,


public) to restrict access to variables and methods.
• Getters and Setters: Encapsulation encourages the use of getters (methods to access
data) and setters (methods to modify data) to control access to the fields of a class.
• Information Hiding: It hides the internal details of how an object works, reducing
system complexity and promoting module reuse.
10. How we are achieving platform independence in Java?

ANS: Java achieves platform independence through the following mechanisms:

• Bytecode: Java source code is compiled into bytecode instead of native machine code.
• Java Virtual Machine (JVM): Bytecode is platform-independent and can be executed
on any system that has a Java Virtual Machine (JVM).
• Write Once, Run Anywhere (WORA): The compiled bytecode can run on any
platform that supports Java without recompilation.

11. What is JDK and what is JRE?

• JDK (Java Development Kit): JDK is a software development kit used for developing
Java applications. It includes the JRE, an interpreter/loader (Java), a compiler (javac),
an archiver (jar), a documentation generator (Javadoc), and other tools needed for
Java development.
• JRE (Java Runtime Environment): JRE is a software package that provides the
libraries, Java Virtual Machine (JVM), and other components to run applications
written in Java.

12. What is JVM and why we are using JVM?

• JVM (Java Virtual Machine): JVM is an abstract computing machine that enables a
computer to run Java programs as well as programs written in other languages that are
compiled to Java bytecode.
• Why use JVM?
o Provides platform independence: Java programs compiled into bytecode can
run on any system with a JVM.
o Memory management: JVM handles memory allocation and garbage
collection.
o Security: JVM provides a secure environment for executing Java applications.

13. Why we declare the main() method as public, static, void?

• public: main() method must be public so that JVM can access it.
• static: main() method is called by the JVM before any objects are instantiated, so it
must be static to run the program without creating an instance of the class.
• void: main() method does not return any value.

14. What will happen if we declare the main() method as private?

If main() method is declared as private:

public class Test {

private static void main(String[] args) {

System.out.println("Hello World");

}
}

Attempting to run this program will result in an error:

Error: Main method not found in class Test, please define the main method as:

public static void main(String[] args)

This is because the JVM requires the main() method to be public and static in order to run the
program. Making it private will prevent the JVM from finding and executing it.

CHAPTER-2
1. Write a Java code to print 1 to 50 in separate lines.
public class PrintNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 50; i++) {
System.out.println(i);
}
}
}

2. Write a Java code to find out if a number is even or odd.


import java.util.Scanner;

public class EvenOdd {


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

if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}

scanner.close();
}
}

3. Write a Java code to calculate the sum of the series: 1 + 2 + 3 + ... + n.


import java.util.Scanner;

public class SumSeries1 {


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

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

System.out.println("Sum of the series 1 + 2 + ... + " + n + " = " +


sum);

scanner.close();
}
}

4. Write a Java code to calculate the sum of the series: 1 - 2 + 3 - 4 + 5 - 6 + ...


+ n.
import java.util.Scanner;

public class SumSeries2 {


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

int sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum -= i; // Subtract if i is even
} else {
sum += i; // Add if i is odd
}
}

System.out.println("Sum of the series 1 - 2 + 3 - 4 + ... + " + n +


" = " + sum);

scanner.close();
}
}

5. What are the differences between while and do-while loops?

• while loop: Checks the condition before entering the loop body.

java
Copy code
while (condition) {
// Loop body
}

• do-while loop: Executes the loop body first and then checks the condition.

java
Copy code
do {
// Loop body
} while (condition);

6. Write a small Java code to implement nested loop concept.


public class NestedLoop {
public static void main(String[] args) {
// Example of nested loops to print a rectangle
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

7. What is a constructor?
A constructor in Java is a special method that is automatically invoked when an object of a
class is instantiated. It is used to initialize objects. It has the same name as the class and does
not have a return type.

8. What is default constructor? Explain with a suitable Java small program.

A default constructor is a no-argument constructor provided by Java if no other constructor is


defined explicitly.

public class Person {


private String name;
private int age;

// Default constructor
public Person() {
name = "Unknown";
age = 0;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Person person = new Person(); // Default constructor called
person.display(); // Output: Name: Unknown, Age: 0
}
}

9. What is a static member?

A static member (variable or method) belongs to the class rather than to any specific instance
of the class. It is shared among all instances of the class.

10. How can we access from outside of the class? Explain with a suitable
example.

Static members can be accessed directly using the class name, without creating an instance of
the class.

public class Counter {


static int count = 0;

public Counter() {
count++; // Increment count each time an object is created
}

public static void main(String[] args) {


Counter c1 = new Counter();
Counter c2 = new Counter();

System.out.println("Number of instances created: " +


Counter.count); // Accessing static member
}
}
11. What are the different accessibility modifiers in Java?

Java provides several access modifiers to set access levels for classes, variables, methods, and
constructors:

• private: Accessible only within the same class.


• default (no modifier): Accessible only within the same package.
• protected: Accessible within the same package and by subclasses.
• public: Accessible from anywhere.

12. Write a parameterized static method/function to calculate !n (Factorial of


n) in a class and call the method/function from another class.
public class Factorial {
// Static method to calculate factorial
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}

public class FactorialMain {


public static void main(String[] args) {
int n = 5; // Calculate factorial of 5
int result = Factorial.factorial(n);
System.out.println("Factorial of " + n + " is: " + result);
}
}

13. How can we create objects in Java?

Objects in Java are created using the new keyword followed by a constructor of the class.

ClassName obj = new ClassName();

14. Why do we use “String args[]” as parameter in main() method in Java


code? Explain with a suitable example.

String args[] is used to pass command line arguments to the main() method in Java.

public class CommandLineArguments {


public static void main(String[] args) {
// Print all command line arguments
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i+1) + ": " + args[i]);
}
}
}

15. Difference between member variable and local variable?


• Member Variable:
o Declared inside a class but outside any method, constructor, or block.
o Exist throughout the lifetime of the object.
o Has default values if not initialized explicitly.
• Local Variable:
o Declared inside a method, constructor, or block.
o Exist only within the scope of the method, constructor, or block.
o Must be initialized before use.

16. What is the significance of using “this” operator? Explain with a suitable
Java code.

The this keyword in Java is used to refer to the current object. It is primarily used to:

• Differentiate between instance variables and local variables that have the same name.
• Call one constructor from another constructor in the same class.

public class Student {


private String name;
private int age;

public Student(String name, int age) {


this.name = name; // Refers to instance variable 'name'
this.age = age; // Refers to instance variable 'age'
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student("Alice", 20);
s1.display();
}
}

17. What is the significance of using “this()” method? Explain with a suitable
code.

this() is used to call one constructor from another constructor in the same class.

public class Rectangle {


private int length;
private int width;

public Rectangle() {
this(0, 0); // Calls the parameterized constructor with length and
width set to 0
}

public Rectangle(int length, int width) {


this.length = length;
this.width = width;
}
public void display() {
System.out.println("Length: " + length + ", Width: " + width);
}

public static void main(String[] args) {


Rectangle rect1 = new Rectangle();
rect1.display(); // Output: Length: 0, Width: 0

Rectangle rect2 = new Rectangle(5, 3);


rect2.display(); // Output: Length: 5, Width: 3
}
}
CHAPTER-3
1. What are the differences between String and StringBuffer?

• String:
o Immutable (unchangeable) sequence of characters.
o Once created, its value cannot be modified.
o Concatenation results in a new String object.
o Thread-safe.
o Example:

String str = "Hello";

• StringBuffer:
o Mutable (changeable) sequence of characters.
o Can be modified after creation.
o Efficient for concatenating strings in a loop.
o Not thread-safe.
o Example:

StringBuffer buffer = new StringBuffer("Hello");


buffer.append(" World");

2. Write a small Java code which will concatenate two given strings “Hello!”
and “This is java language”.
public class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello!";
String str2 = "This is java language";

String result = str1 + " " + str2;


System.out.println(result);
}
}

3. Write a small Java code how to read lines and print these to the standard
output stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadLines {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));

System.out.println("Enter lines (type 'end' to finish): ");


String line;
while (!(line = reader.readLine()).equalsIgnoreCase("end")) {
System.out.println(line);
}
reader.close();
}
}

4. Short note on:

• a. charAt(int)

Returns the character at the specified index in a String.

String str = "Hello";


char ch = str.charAt(0); // 'H'

• b. indexOf(String)

Returns the index within the string of the first occurrence of the specified substring.

String str = "Hello";


int index = str.indexOf("l"); // 2

• c. substring(int, int)

Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex and extends to the character at index endIndex - 1.

String str = "Hello";


String sub = str.substring(2, 4); // "ll"

• d. replace(CharSequence, CharSequence)

Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.

String str = "Hello";


String replaced = str.replace("l", "X"); // "HeXXo"

5. How can we find out the length of an array? Explain with a small Java
code.
public class ArrayLength {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int length = array.length;
System.out.println("Length of the array: " + length);
}
}

6. How can we find out the length of a String? Explain with a small Java code.
public class StringLength {
public static void main(String[] args) {
String str = "Hello";
int length = str.length();
System.out.println("Length of the string: " + length);
}
}

7. Write a small Java code using Integer.parseInt() method.


public class ParseIntExample {
public static void main(String[] args) {
String numberStr = "123";
int number = Integer.parseInt(numberStr);
System.out.println("Parsed number: " + number);
}
}

8. What is a wrapper class?

A wrapper class is a class that wraps around a primitive data type and provides utility
methods to operate on that data type. For example, Integer, Double, Boolean are wrapper
classes for int, double, boolean respectively.

9. Write a small Java code to use toLowerCase() and toUpperCase() methods.


public class ChangeCase {
public static void main(String[] args) {
String str = "Hello World";

// Convert to lower case


String lowerCase = str.toLowerCase();
System.out.println("Lower case: " + lowerCase);

// Convert to upper case


String upperCase = str.toUpperCase();
System.out.println("Upper case: " + upperCase);
}
}

10. Write a small Java code which will import java.io package.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ImportPackage {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter something: ");
String input = reader.readLine();
System.out.println("You entered: " + input);
reader.close();
}
}

These examples should help clarify the concepts and provide a foundation for further
understanding Java programming. Let me know if you have any further questions or need
more explanations!
CHAPTER-4
1. What is a constructor?

A constructor in Java is a special type of method that is used to initialize objects. It is called
when an object of a class is created. Constructors have the same name as the class and do not
have a return type, not even void.

2. What is default constructor? What is non-default constructor? Explain with


a suitable Java code.

• Default Constructor:
o A constructor that is automatically created by Java if no other constructor is
defined.
o It initializes the object with default values.
• Non-default Constructor:
o A constructor that is explicitly defined in the class.
o It allows you to initialize the object with custom values.

// Example of default and non-default constructors


public class Car {
String color;
int year;

// Default constructor (implicitly provided)


public Car() {
color = "White";
year = 2020;
}

// Non-default constructor
public Car(String c, int y) {
color = c;
year = y;
}

public void display() {


System.out.println("Car Color: " + color + ", Year: " + year);
}

public static void main(String[] args) {


Car car1 = new Car(); // Using default constructor
car1.display(); // Output: Car Color: White, Year: 2020

Car car2 = new Car("Red", 2021); // Using non-default constructor


car2.display(); // Output: Car Color: Red, Year: 2021
}
}

3. How can we create an object in Java? Explain with a suitable Java code.

Objects in Java are created using the new keyword followed by a constructor of the class.

// Creating an object in Java


public class MyClass {
int x; // Instance variable

// Constructor
public MyClass(int val) {
x = val;
}

public static void main(String[] args) {


// Creating an object of MyClass
MyClass myObj = new MyClass(10);
System.out.println("Value of x: " + myObj.x); // Output: Value of
x: 10
}
}

4. What is constructor overloading? Explain with a Java code.

Constructor overloading is a concept where a class can have more than one constructor with
different parameter lists.

// Example of constructor overloading


public class Employee {
private String name;
private int age;
private double salary;

// Default constructor
public Employee() {
name = "Unknown";
age = 0;
salary = 0.0;
}

// Parameterized constructor 1
public Employee(String n, int a) {
name = n;
age = a;
salary = 0.0;
}

// Parameterized constructor 2
public Employee(String n, int a, double s) {
name = n;
age = a;
salary = s;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age + ", Salary:
$" + salary);
}

public static void main(String[] args) {


Employee emp1 = new Employee();
Employee emp2 = new Employee("John", 30);
Employee emp3 = new Employee("Alice", 25, 50000.0);

emp1.display(); // Output: Name: Unknown, Age: 0, Salary: $0.0


emp2.display(); // Output: Name: John, Age: 30, Salary: $0.0
emp3.display(); // Output: Name: Alice, Age: 25, Salary: $50000.0
}
}

5. What is method overloading? Explain with a Java code.

Method overloading is a feature in Java where a class can have multiple methods with the
same name but different parameter lists.

// Example of method overloading


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

// Method to add three integers


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

// Method to add two doubles


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

public static void main(String[] args) {


Calculator calc = new Calculator();

System.out.println("Sum of 5 and 10: " + calc.add(5, 10)); //


Output: 15
System.out.println("Sum of 5, 10, and 15: " + calc.add(5, 10, 15));
// Output: 30
System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5)); //
Output: 6.0
}
}

6. What is constructor chaining?

Constructor chaining is the process of calling one constructor from another constructor in the
same class hierarchy.

7. Write a Java code to implement constructor chaining using this().


// Example of constructor chaining using this()
public class Vehicle {
private String type;
private int year;

// Default constructor
public Vehicle() {
this("Car", 2020); // Calling parameterized constructor
}

// Parameterized constructor
public Vehicle(String t, int y) {
type = t;
year = y;
}

public void display() {


System.out.println("Type: " + type + ", Year: " + year);
}

public static void main(String[] args) {


Vehicle vehicle = new Vehicle();
vehicle.display(); // Output: Type: Car, Year: 2020
}
}

8. What is polymorphism?

Polymorphism in Java allows an object to take on many forms. There are two types of
polymorphism in Java: compile-time polymorphism (method overloading) and runtime
polymorphism (method overriding).

9. Is the return type of methods considered in method overloading? Explain


with suitable Java code.

No, the return type alone is not considered for method overloading. Method overloading is
determined by the method signature (name and parameter types).

// Example of method overloading based on parameters, not return type


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

// Method to add two doubles


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

public static void main(String[] args) {


Calculation calc = new Calculation();

System.out.println("Sum of integers: " + calc.add(5, 10)); //


Output: 15
System.out.println("Sum of doubles: " + calc.add(2.5, 3.5)); //
Output: 6.0
}
}

10. What is static polymorphism?

Static polymorphism is achieved through method overloading or operator overloading in


Java. It is resolved at compile-time.

11. Write a Java code to implement method overloading concept on area()


method to calculate the area of a rectangle, square, and circle.
// Example of method overloading to calculate area
public class Shape {
// Method to calculate area of a rectangle
public double area(double length, double width) {
return length * width;
}

// Method to calculate area of a square


public double area(double side) {
return side * side;
}

// Method to calculate area of a circle


public double area(double radius, String type) {
if (type.equalsIgnoreCase("circle")) {
return Math.PI * radius * radius;
}
return 0;
}

public static void main(String[] args) {


Shape shape = new Shape();

System.out.println("Area of Rectangle: " + shape.area(5.0, 4.0));


// Output: 20.0
System.out.println("Area of Square: " + shape.area(5.0)); //
Output: 25.0
System.out.println("Area of Circle: " + shape.area(3.0, "circle"));
// Output: 28.274333882308138
}
}

12. Write a suitable Java code to explain the public, private, default, and
protected accessibility modifiers.
// Example to demonstrate accessibility modifiers
public class AccessModifiers {
public int publicVar = 10; // Accessible everywhere
private int privateVar = 20; // Accessible only within the class
int defaultVar = 30; // Accessible within the package
protected int protectedVar = 40; // Accessible within the package and
by subclass

public void display() {


System.out.println("Public Variable: " + publicVar);
System.out.println("Private Variable: " + privateVar);
System.out.println("Default Variable: " + defaultVar);
System.out.println("Protected Variable: " + protectedVar);
}
}

class Subclass extends AccessModifiers {


public void displayProtected() {
System.out.println("Protected Variable (from subclass):
CHAPTER-5
1. Difference between abstract class and interface. Explain with suitable Java
code.

• Abstract Class:
o Can have abstract methods as well as concrete methods.
o Can have instance variables.
o Cannot be instantiated, but can be subclassed.
o Can have constructors.
o Supports method overriding.
• Interface:
o Can only have abstract methods (methods without a body) and constants
(public static final variables).
o Cannot have instance variables.
o Cannot be instantiated directly; a class must implement it.
o Cannot have constructors.
o Supports multiple inheritance through interfaces.

Java Code Example:

// Abstract class example


abstract class Animal {
abstract void makeSound(); // Abstract method

// Concrete method
void sleep() {
System.out.println("Zzz");
}
}

// Interface example
interface AnimalInterface {
void makeSound(); // Abstract method (implicitly public and abstract)
// Constants
int legs = 4;
}

// Implementing the abstract class and interface


class Dog extends Animal implements AnimalInterface {
public void makeSound() {
System.out.println("Bark bark");
}

public static void main(String[] args) {


Dog myDog = new Dog();
myDog.makeSound(); // Output: Bark bark
myDog.sleep(); // Output: Zzz
System.out.println("Number of legs: " + AnimalInterface.legs); //
Output: Number of legs: 4
}
}

2. Difference between final class and abstract class. Explain with suitable Java
code.
• Final Class:
o Cannot be subclassed/extended.
o All methods are implicitly final if the class is final.
o Used to prevent inheritance or extension.
• Abstract Class:
o Cannot be instantiated directly.
o Can have abstract methods (methods without a body).
o Used to provide a common interface for all subclasses.

Java Code Example:

// Example of final class


final class FinalClass {
// Final method
final void display() {
System.out.println("This is a final method.");
}
}

// Example of abstract class


abstract class AbstractClass {
// Abstract method
abstract void display();
}

// Subclassing AbstractClass
class ConcreteClass extends AbstractClass {
// Implementation of abstract method
void display() {
System.out.println("Implementation of abstract method.");
}
}

// Trying to extend FinalClass will result in compilation error


// class AnotherClass extends FinalClass {}

public class Main {


public static void main(String[] args) {
ConcreteClass obj = new ConcreteClass();
obj.display(); // Output: Implementation of abstract method.
}
}

3. Write a Java code to create an Applet and show a message “Welcome in


Java Applet”
import java.applet.Applet;
import java.awt.Graphics;

public class WelcomeApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Welcome in Java Applet", 20, 20);
}
}

4. What is Java applet?


Java applet is a small application that is written in Java and delivered to users in the form of
bytecode. Applets can run in a web browser using the Java Plugin. They are used to create
dynamic and interactive web applications.

5. Difference between a Java application program and a Java applet.

• Java Application:
o Standalone program that runs on the client machine.
o Executed using the java command on the command prompt.
o Does not require a web browser or a web server.
o Entry point is public static void main(String[] args).
• Java Applet:
o Small application that runs within a web browser.
o Executed using the <applet> tag in HTML.
o Requires a web browser with Java Plugin installed.
o Entry point is init(), start(), stop(), and destroy() methods.

6. Explain the life cycle of a Java applet.

The life cycle of a Java applet is controlled by methods defined in the Applet class:

• init(): Initializes the applet, called once when the applet is started.
• start(): Called after the init() method and each time the applet is revisited.
• paint(Graphics g): Called when the applet is rendered and needs to display some
output.
• stop(): Called when the user moves away from the page that contains the applet.
• destroy(): Called when the browser shuts down normally or when the applet is
removed from the page.

7. What are the rules of method overriding?

To override a method in Java, the subclass method must have the same:

• Name as the superclass method.


• Arguments as the superclass method.
• Return type (or subtype, known as covariant return type) as the superclass method.
• Access level (visibility) as the superclass method. It cannot be more restrictive.

8. What is dynamic polymorphism? How can we achieve it by method


overriding? Explain with a suitable Java code.

Dynamic polymorphism is also known as runtime polymorphism. It is achieved through


method overriding.

// Example to demonstrate dynamic polymorphism


class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String args[]) {
Animal myAnimal = new Dog(); // Reference of Animal type but object
of Dog
myAnimal.sound(); // Output: Dog barks
}
}

9. Write a Java and HTML code to create an applet of size 200 x 300. Applet
background color will be Red and on the applet a movable banner of a string
“Welcome to java applet”.

Java Code (WelcomeBannerApplet.java):

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class WelcomeBannerApplet extends Applet implements Runnable {


String message = "Welcome to Java Applet";
int x = 10, y = 100;
Thread t;

public void init() {


setBackground(Color.RED);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.BOLD, 20));
}

public void start() {


t = new Thread(this);
t.start();
}

public void stop() {


t = null;
}

public void run() {


while (true) {
repaint();
try {
Thread.sleep(100);
x += 5;
if (x > getWidth())
x = -100;
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public void paint(Graphics g) {
g.drawString(message, x, y);
}
}

HTML Code (WelcomeBannerApplet.html):

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Java Applet</title>
</head>
<body>
<applet code="WelcomeBannerApplet.class" width="200" height="300">
Your browser does not support Java applets.
</applet>
</body>
</html>

Compile the Java file (javac WelcomeBannerApplet.java) and then open


WelcomeBannerApplet.html in a web browser that supports Java applets.
CHAPTER-6
1) Write a java code to catch ArithmeticException and
ArrayIndexOutOfBoundsException with finally block.

ArrayIndexOutOfBoundsException exceptions, along with a finally block:

public class ExceptionHandlingDemo {


public static void main(String[] args) {
try {
// ArrayIndexOutOfBoundsException
int[] arr = { 1, 2, 3 };
System.out.println(arr[3]); // Trying to access out of bound
index

// ArithmeticException
int a = 5 / 0; // Division by zero
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException occurred!");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException occurred!");
} finally {
System.out.println("Inside finally block.");
}
}
}

Explanation:

• ArrayIndexOutOfBoundsException:
o This exception is caught when attempting to access an index that is out of the
bounds of the array arr.
• ArithmeticException:
o This exception is caught when dividing an integer by zero, which results in an
undefined arithmetic operation.
• Finally Block:
o The finally block is used to execute the cleanup code. It will always execute,
regardless of whether an exception is thrown or not.

Output:
ArrayIndexOutOfBoundsException occurred!
Inside finally block.

Notes:

• In this example, both exceptions are explicitly caught using separate catch blocks.
• The finally block is used to execute the cleanup code, ensuring that resources are
properly released, even if an exception occurs.

This example demonstrates how to handle multiple exceptions and ensure cleanup operations
are performed using the finally block in Java exception handling.

You might also like