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

java ut1

The document compares vectors and arrays, highlighting that vectors have dynamic sizes and are thread-safe, while arrays have fixed sizes and are faster. It includes Java programming examples for Armstrong and prime number checks, explains Java concepts like JVM, bytecode, JDK, and exception handling, and discusses object-oriented programming features such as inheritance, polymorphism, abstraction, and encapsulation. Additionally, it provides details on creating user-defined packages, custom exceptions, and thread management in Java.

Uploaded by

exesuhxxn
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)
4 views

java ut1

The document compares vectors and arrays, highlighting that vectors have dynamic sizes and are thread-safe, while arrays have fixed sizes and are faster. It includes Java programming examples for Armstrong and prime number checks, explains Java concepts like JVM, bytecode, JDK, and exception handling, and discusses object-oriented programming features such as inheritance, polymorphism, abstraction, and encapsulation. Additionally, it provides details on creating user-defined packages, custom exceptions, and thread management in Java.

Uploaded by

exesuhxxn
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/ 16

Q1) Compare vectors and arrays

ASPECT VECTORS ARRAYS


SIZE Dynamic size Fixed size
SYNCHRONIZATION Synchronizes (thread safe) Not synchronized
PERFORMANCE Slower due to synchroniza on Faster without synchroniza on
overhead
USAGE Provides built-in methods for Basic with direct index
manipula on

Q2) write a program to print the Armstrong number.


import java.u l.Scanner;

public class ArmstrongNumber {


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

int originalNumber = number;


int sum = 0;
int digits = Integer.toString(number).length();

while (number != 0) {
int digit = number % 10;
sum += Math.pow(digit, digits);
number /= 10;
}

if (sum == originalNumber) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}
}
}

Q3) State the significance of JVM,Byte code, and JDK


1. Java Virtual Machine (JVM):

o Significance: The JVM is an engine that provides a run me environment to execute


Java bytecode. It is a crucial part of the Java Run me Environment (JRE). The JVM
allows Java programs to be pla orm-independent by conver ng bytecode into
machine-specific code. This means that Java applica ons can run on any device or
opera ng system that has a JVM implementa on.
2. Bytecode:

o Significance: Bytecode is the intermediate representa on of a Java program,


generated a er the compila on of source code. It is a highly op mized set of
instruc ons that can be executed by the JVM. The use of bytecode enables Java's
"write once, run anywhere" capability, as bytecode can be executed on any pla orm
with a compa ble JVM. Bytecode enhances security and portability by abstrac ng
the underlying hardware.

3. Java Development Kit (JDK):

o Significance: The JDK is a so ware development kit used to develop Java


applica ons and applets. It includes the Java Run me Environment (JRE), a set of
development tools (like the compiler javac, the debugger jdb, and others), and
addi onal libraries needed for Java development. The JDK provides everything
needed for Java development, from wri ng and compiling code to debugging and
packaging Java applica ons.

Q4) write the use of/ purpose of this keyword, sta c keyword and
final keyword
this keyword:

 Purpose: The this keyword is used to refer to the current instance of a class. It is mainly used
in constructors and methods to dis nguish between class a ributes and parameters with the
same name. It can also be used to invoke other constructors in the same class.

sta c keyword:

 Purpose: The sta c keyword is used to define class-level variables and methods, which
belong to the class itself rather than to any specific instance of the class. Sta c members are
shared among all instances of the class.

final keyword:

 Purpose: The final keyword is used to define constants, prevent method overriding,
and prevent inheritance. It can be applied to variables, methods, and classes.

Q5) explain single and multilevel inheritance with example


Single Inheritance:

 In single inheritance, a class (child) inherits from only one parent (superclass).
 This is the simplest form of inheritance, providing a straightforward way to extend the
functionality of an existing class.
 For instance, if Dog is a subclass of Animal, the Dog class can access the methods
and properties of the Animal class.
Multilevel Inheritance:

 In multilevel inheritance, a class is derived from another derived class, creating a


hierarchy.
 For example, class Puppy inherits from class Dog, which inherits from class Animal.
 This creates a chain where the Puppy class has access to both Dog and Animal class
methods and properties.

Q6) Difference between method overloading and method


overriding
Aspect Method Overloading Method Overriding
Defining multiple methods with the same Defining a method in a subclass with
Definition name but different parameters within the the same signature as a method in its
same class. superclass.
To increase the readability of the To provide a specific
Purpose program and provide multiple ways to implementation of a method that is
call a method with different parameters. already defined in its superclass.
Must have different parameters (type, Must have the same parameters
Parameters
number, or order). (same signature).
Return Must have the same return type
Can have different return types.
Type (from Java 5 onwards).
Doesn't require inheritance; methods can Requires inheritance; involves a
Inheritance
be in the same class. superclass and a subclass.

Q7) Describe packages and interface (definition syntax and


examples)
Packages:

 Definition: A package is a namespace that groups related classes and interfaces


together. It helps to organize the code and avoid naming conflicts. Packages also
make it easier to manage and maintain large codebases.
 Syntax

package packageName;

Example

package com.example.myapp;

public class MyClass {

public void display() {

System.out.println("Hello from MyClass!");


}

public class AnotherClass {

public void show() {

System.out.println("Hello from AnotherClass!");

Interfaces:

 Definition: An interface is a reference type in Java, similar to a class, that can contain only
abstract methods (methods without a body) and static constants. Interfaces are used to
achieve abstraction and multiple inheritance in Java.

Syntax

interface InterfaceName {

// Abstract method

void methodName();

Example

interface Animal {

void eat();

void sleep();

class Dog implements Animal {

@Override

public void eat() {

System.out.println("Dog is eating.");

}
@Override

public void sleep() {

System.out.println("Dog is sleeping.");

public class InterfaceExample {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat();

dog.sleep();

Q8) Enlist 4 compile time error


Syntax Errors

Type Mismatch Errors

Undeclared Variable Errors

Method Not Found Errors

Q9) write a program to check whether the number is prime or not


import java.util.Scanner;

public class PrimeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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


int number = scanner.nextInt();

scanner.close();

boolean isPrime = true;

if (number <= 1) {

isPrime = false;

} else {

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

if (number % i == 0) {

isPrime = false;

break;

if (isPrime) {

System.out.println(number + " is a prime number.");

} else {

System.out.println(number + " is not a prime number.");

4 Marks :-

Q1) Explain exception handling mechanism with respect to try,


catch, throw,throws,multithreading,miltitasking and finally
Exception Handling Mechanism in Java
Exception handling is a powerful mechanism in Java that handles runtime errors to maintain the
normal flow of the application. It allows a program to deal with unexpected conditions (like division
by zero, file not found, etc.) without crashing. In Java, exception handling is done using try, catch,
throw, throws, and finally blocks.

Let's break down the key components of exception handling and also explain the concepts of
multithreading and multitasking in the context of Java.

. try Block:

The try block is used to enclose the code that might throw an exception. The code within this block is
monitored for exceptions, and if an exception occurs, it is passed to the catch block for handling.

catch Block:

The catch block follows the try block and is used to handle exceptions. If an exception is thrown
inside the try block, the flow of control is transferred to the catch block. Multiple catch blocks can be
used to handle different types of exceptions.

throw Keyword:

The throw keyword is used to explicitly throw an exception from a method or a block of code. It is
used when you want to throw a custom exception or an exception manually based on a condition.

throws Keyword:

The throws keyword is used in method declarations to specify which exceptions may be thrown by
that method. It is used when a method might throw an exception, but the method itself doesn't
handle it.

finally Block:

The finally block is optional and contains code that will be executed regardless of whether an
exception occurs or not. It is commonly used for cleanup activities such as closing database
connections, file streams, etc.

Multithreading and Exception Handling:

Multithreading is a concept where multiple threads (small units of a process) are executed
concurrently. It allows for performing multiple operations simultaneously, improving the
performance and responsiveness of applications.

In multithreading, exception handling becomes more critical because each thread operates
independently. If an exception occurs in one thread, it may affect other threads or the overall
program.

Multitasking refers to the ability of a CPU to execute multiple tasks or processes at the same time. In
Java, multitasking can be achieved using multithreading where multiple threads are used to perform
tasks concurrently.
Java's multitasking capabilities allow for efficient resource utilization, where tasks that are
independent of each other can run simultaneously.

Q2) Define an exception called no match exception that is thrown


when password accepted is not equal to msbte
In Java, you can define a custom exception by extending the Exception class. Here's an example of
how you could define the NoMatchException and throw it when the password doesn't match
"msbte":

class NoMatchException extends Exception {

public NoMatchException(String message) {

super(message); // Pass the message to the parent Exception class

public class PasswordChecker {

public static void checkPassword(String password) throws NoMatchException {

if (!password.equals("msbte")) {

throw new NoMatchException("Password is incorrect, expected 'msbte'.");

} else {

System.out.println("Password accepted!");

public static void main(String[] args) {

try {

String userPassword = "somepassword"; // You can replace this with input from the user
checkPassword(userPassword);

} catch (NoMatchException e) {

System.out.println("Error: " + e.getMessage());

 NoMatchException class: This is a custom exception that extends the Exception class. The
constructor takes a message as an argument and passes it to the superclass Exception constructor.

 checkPassword method: This method checks if the provided password equals "msbte". If it
doesn't, the NoMatchException is thrown with a specific error message.

 main method: In this method, we simulate checking the password by calling checkPassword. If the
password doesn't match "msbte", the NoMatchException is thrown and caught in the catch block,
where the error message is printed.

Q3) Define thread mention two ways to create a thread and give
syntax of notify, slip, run, and start method
n Java, a thread is a lightweight process that allows concurrent execution of code. You can create a
thread in Java in two main ways:

By Extending the Thread Class:

 You can create a new class that extends the Thread class and override its run() method

By Implementing the Runnable Interface:

 You can create a class that implements the Runnable interface and pass it to a Thread
object.

Methods Related to Threads:

1. start() Method:
o The start() method is used to begin the execution of a thread. It invokes the run()
method in a separate call stack.

Syntax

thread.start();

2. run() Method:
o The run() method is where the code to be executed by the thread is written. It
contains the logic that will run in the separate thread.
Syntax:

@Override

public void run() {

// code to run in the thread

3. notify() Method:
o The notify() method is used to wake up a single thread that is waiting on the object's
monitor (lock). It should be called from a synchronized block or method.

Syntax:

synchronized (object) {

object.notify();

4. sleep() Method:
o The sleep() method is used to pause the execution of the current thread for a
specified amount of time (in milliseconds).

Syntax:

Thread.sleep(milliseconds); // Throws InterruptedException

Q4) explain how to create a package (user define) and import it


with a suitable example
In Java, a package is a namespace that organizes a set of related classes and interfaces. You can
create your own (user-defined) package and import it into other classes to use its functionality.

Steps to Create and Use a User-Defined Package in Java:

1. Create a Package:
o A package is created using the package keyword at the beginning of a Java file. The
classes in the package should be placed in a directory corresponding to the package
name.
2. Import the Package:
o After creating the package, you can import the package into another class using the
import statement.

Example

1. Creating a Package (User-Defined)


package myutils; // Defining the package

public class Calculator {

public int add(int a, int b) {


return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
2. Importing the Package in Another Class

import myutils.Calculator; // Importing the user-defined package

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

int sum = calc.add(10, 5);

int diff = calc.subtract(10, 5);

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

System.out.println("Difference: " + diff); // Output: Difference: 5

Q5) explain the following features of oops(polymorphism,


inheritance, abstraction, encapsulation)with examples, write
features of java.
1. Polymorphism:

Polymorphism means "many forms". It allows a single entity to represent different types or
forms. In Java, polymorphism is achieved in two primary ways:
 Method Overloading (Compile-time polymorphism)
 Method Overriding (Runtime polymorphism)

 2. Inheritance:
 Inheritance is a mechanism where a new class inherits the properties (fields) and
behaviors (methods) of an existing class. The new class is called the subclass or child
class, and the class from which it inherits is called the superclass or parent class.

3. Abstraction:

Abstraction is the concept of hiding the implementation details and showing only the
essential features of an object. It simplifies complex systems by focusing on the high-level
operations. In Java, abstraction is achieved using:

 Abstract classes: Classes that cannot be instantiated on their own and may contain
abstract methods (methods without implementation).
 Interfaces: A collection of abstract methods that a class can implement.

4. Encapsulation:

Encapsulation is the technique of bundling the data (variables) and the methods that operate
on the data into a single unit, called a class. It also restricts access to some of the object's
components by using access modifiers like private, protected, and public.

Key Features of Java:

Simple Secure

Object-Oriented Distributed

Platform-Independent High Performance Dynamic

Q6) implement the following


Interface salary Class :- explayee

Basic_salary Name, age

Basic_sal() Display()

Class :- Gross_salary

TA, DA, HRA

Total_sal()

Solution:
1. Interface Salary:

The Salary interface will define the method Basic_sal() that needs to be implemented by any class that
implements this interface.

2. Class ExEmployee:

The ExEmployee class will implement the Salary interface. It will include the basic details like name
and age and the method Basic_sal() to return the basic salary. It will also have the display() method to
print the details.

3. Class GrossSalary:

The GrossSalary class will use the ExEmployee class and add allowances (TA, DA, HRA) to
calculate the total salary.

Example:-

// Define the Salary interface

interface Salary {

// Method to return basic salary

double Basic_sal();

// Class ExEmployee implements Salary interface

class ExEmployee implements Salary {

// Instance variables

String name;

int age;

// Constructor to initialize the name and age

public ExEmployee(String name, int age) {

this.name = name;

this.age = age;

}
// Implement Basic_sal() method from Salary interface

@Override

public double Basic_sal() {

// Returning a basic salary (for example purposes)

return 50000.00; // This is just an example value

// Method to display employee details

public void display() {

System.out.println("Employee Name: " + name);

System.out.println("Employee Age: " + age);

// Class GrossSalary extends ExEmployee

class GrossSalary extends ExEmployee {

// Instance variables for allowances

double TA; // Travel Allowance

double DA; // Dearness Allowance

double HRA; // House Rent Allowance

// Constructor to initialize name, age and allowances

public GrossSalary(String name, int age, double TA, double DA, double HRA) {

super(name, age); // Call to ExEmployee constructor

this.TA = TA;
this.DA = DA;

this.HRA = HRA;

// Method to calculate the total salary (Basic salary + TA + DA + HRA)

public double Total_sal() {

// Calculate the total salary by adding allowances to basic salary

return Basic_sal() + TA + DA + HRA;

public class Main {

public static void main(String[] args) {

// Create an object of GrossSalary class

GrossSalary employee = new GrossSalary("John Doe", 30, 8000.00, 5000.00, 10000.00);

// Display employee details

employee.display();

// Display the total salary

System.out.println("Total Salary: " + employee.Total_sal()); // Output will be total of Basic, TA,


DA, and HRA

You might also like