[go: up one dir, main page]

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

E SPR Ess O

Java

Uploaded by

balajithiru454
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 views24 pages

E SPR Ess O

Java

Uploaded by

balajithiru454
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/ 24

SORRYYYYYYY ;-;-;-;-;-;-;

1.Define object-oriented programming (OOP): Object-Oriented Programming (OOP) is a


programming paradigm based on the concept of "objects," which are instances of classes. It
focuses on organizing software design around data, or objects, rather than functions and logic.
OOP principles include encapsulation, inheritance, polymorphism, and abstraction.

2. Describe the structure of a Java source file: A Java source file typically has the following
structure:

○ Package declaration (optional)


○ Import statements (optional)
○ Class declaration (must include the class keyword followed by the class name)
○ Main method (if the program is executable)
○ Other methods and fields.

Example:

package mypackage; // optional


import java.util.Scanner; // optional

public class MyClass { // class declaration


public static void main(String[] args) { // main method
// code goes here
}
}

3. Two Java Access Specifiers:

● public: This access specifier allows the member (class, method,


or variable) to be accessible from any other class or package.
● private: This access specifier restricts the member to be
accessible only within the class it is defined in.

4. What is the role of the Java Virtual Machine (JVM)? The JVM is responsible for running
Java programs. It provides an environment that translates compiled bytecode into machine
code, which can then be executed by the host system. The JVM also manages memory,
garbage collection, and other system resources for Java applications.
5. What is the function of the main method in a Java program? The main method is the
entry point of any Java program. It is where the execution of the program begins. The JVM calls
this method to start the program when running the class.

Example:

public static void main(String[] args) {


// program starts here
}

6. Differentiate between static and non-static members in Java:

○ Static members: Belong to the class, not instances of the class. They can be
accessed without creating an object of the class. Static members are shared
among all instances of the class.
○ Non-static members: Belong to individual instances of the class. They require
an object of the class to be accessed.

7. Enlist the various data types in Java:

○ Primitive data types:


■ byte
■ short
■ int
■ long
■ float
■ double
■ char
■ boolean
○ Reference data types:
■ Arrays
■ Objects (instances of classes)

8. Give any four examples of JavaDoc Comments: JavaDoc comments are special
comments used to generate documentation. They are written with /** and */ and typically
appear above classes, methods, or fields. Example:
/**
* This is a class representing a person.
*/
public class Person {
/**
* This method returns the name of the person.
* @return the person's name
*/
public String getName() {
return name;
}
}

9. Mention the various properties of constructors in Java:

○ A constructor has the same name as the class.


○ It is used to initialize objects of a class.
○ It doesn't have a return type, not even void.
○ If no constructor is defined, a default constructor is provided by Java.
○ Constructors can be overloaded, meaning multiple constructors can exist with
different parameters.

10. How a Java program is compiled and executed:

○ The Java source code (with .java extension) is written.


○ The source code is compiled using the javac compiler into bytecode (with
.class extension).
○ The bytecode is executed on the Java Virtual Machine (JVM) using the java
command, which interprets and runs the bytecode on the underlying system.

11. Write a Java program to check whether a given number is Prime or Not:

import java.util.Scanner;

public class PrimeCheck {


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

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0) {
isPrime = false;
break;
}
}

if (num < 2) {
isPrime = false;
}

if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}

12. Write a Java program to generate Fibonacci Series:

public class FibonacciSeries {


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

System.out.print("Fibonacci Series: ");


for (int i = 0; i < n; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}

13. Identify the various components of a package in Java:


○ Classes: The core components that hold data and methods.
○ Interfaces: Abstract type used to specify methods that can be implemented by
classes.
○ Sub-packages: A package can contain other sub-packages.
○ Access specifiers: These define how the components of a package can be

14. What is a package in Java?

A package in Java is a namespace that organizes a set of related classes and interfaces. It
helps in avoiding name conflicts and makes it easier to manage and maintain code. For
example, the java.util package contains utility classes like ArrayList, HashMap, etc.

15. Defining a 2D array in Java:

You can define a 2D array in Java like this:

int[][] array = new int[3][4]; // A 2D array with 3 rows and 4 columns

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

PART B
1. Explain how arrays are declared, initialized, and accessed in Java. Write a program to find
the maximum value in an integer array.

Declaration: Arrays in Java are declared using square brackets [].


int[] arr;
Initialization: You can initialize an array either during declaration or later.
arr = new int[5]; // Declare and allocate memory for 5 elements // OR int[]
arr = {10, 20, 30, 40, 50}; // Declare and initialize
Access: Access array elements using the index (starting from 0).
System.out.println(arr[0]); // Access the first element
Program to Find Maximum Value:
public class MaxValue {
public static void main(String[] args) {
int[] arr = {10, 20, 35, 50, 5}; // Example array
int max = arr[0]; // Assume the first element is the max

for (int i = 1; i < arr.length; i++) {


if (arr[i] > max) {
max = arr[i];
}
}

System.out.println("Maximum value in the array: " + max);


}
}

2. Brief about the significance of JavaDoc comments? Write a sample Java


class with properly documented JavaDoc comments.

● Significance: JavaDoc comments are used to generate documentation for Java code.
They are important for describing classes, methods, parameters, and return values in a
clear and standard format. This helps other developers understand your code better.
● Sample Java Class with JavaDoc Comments:

/**
* This class represents a simple calculator.
* It provides methods for addition and subtraction.
*/
public class Calculator {

/**
* Adds two integers.
*
* @param a the first integer
* @param b the second integer
* @return the sum of a and b
*/
public int add(int a, int b) {
return a + b;
}

/**
* Subtracts the second integer from the first.
*
* @param a the first integer
* @param b the second integer
* @return the difference of a and b
*/
public int subtract(int a, int b) {
return a - b;
}
}

3. Enlist and describe the various salient features of Java Language in detail
with suitable examples

Compiled and Interpreted

Java code is compiled into bytecode and interpreted by the JVM on any platform.

javac HelloWorld.java # Compiles to bytecode


java HelloWorld # Executes bytecode on any platform

Platform Independence

Java's bytecode can run on any device with a JVM, ensuring Write Once, Run Anywhere
(WORA).

Object-Oriented

Java follows OOP principles like inheritance and polymorphism.

class Animal { void sound() { System.out.println("Sound"); } }


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

Robust

Java’s memory management, exception handling, and strong typing make it less error-
prone.
Security

Java uses bytecode verification, security manager, and sandboxing to protect against
malicious code.

Automatic Memory Management

Java automatically handles memory via Garbage Collection, freeing unused objects.

Dynamic Binding

Java uses dynamic method calls (runtime method binding) for flexibility.

Animal myDog = new Dog();


myDog.sound(); // Output: Bark

High Performance

Java’s JIT compilation improves runtime performance by converting bytecode to machine code.

Multithreaded

Java supports multithreading for efficient concurrent execution.

class MyThread extends Thread { public void run() {


System.out.println("Running"); } }
new MyThread().start(); // Start a new thread

Some Dangerous Features in C/C++ Eliminated

Java eliminates manual memory management, and buffer overflows for safety.

This summary keeps the key points while simplifying the explanation.

4. Develop a Java program using constructors and suitable methods for


employee management system

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Employee {
int id;
String name, department;
double salary;

public Employee(int id, String name, String department, double salary) {


this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}

void display() {
System.out.println("ID: " + id + ", Name: " + name + ", Department: " + department
Salary: " + salary);
}
}

public class EmployeeManagementSystem {


private static List<Employee> employees = new ArrayList<>();
private static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {


while (true) {
System.out.println("\n1. Add Employee\n2. Display Employees\n3. Search by ID\
Salary\n5. Exit");
int choice = sc.nextInt();
if (choice == 5) break;

switch (choice) {
case 1: addEmployee(); break;
case 2: displayEmployees(); break;
case 3: searchById(); break;
case 4: updateSalary(); break;
default: System.out.println("Invalid option!"); break;
}
}
}

private static void addEmployee() {


System.out.print("ID: ");
int id = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Department: ");
String department = sc.nextLine();
System.out.print("Salary: ");
double salary = sc.nextDouble();
employees.add(new Employee(id, name, department, salary));
}

private static void displayEmployees() {


if (employees.isEmpty()) System.out.println("No employees found.");
else employees.forEach(Employee::display);
}

private static void searchById() {


System.out.print("Enter ID: ");
int id = sc.nextInt();
employees.stream().filter(emp -> emp.id == id).findFirst()
.ifPresentOrElse(Employee::display, () -> System.out.println("Employee
found."));
}

private static void updateSalary() {


System.out.print("Enter ID: ");
int id = sc.nextInt();
Employee emp = employees.stream().filter(e -> e.id == id).findFirst().orElse(null);
if (emp != null) {
System.out.print("New Salary: ");
emp.salary = sc.nextDouble();
System.out.println("Salary updated.");
} else {
System.out.println("Employee not found.");
}
}
}

5. Matrix Addition and Multiplication (if ye remember sem 2 this finna be ez af)

Addition
import java.util.Scanner;

public class MatrixAddition {

// Method for matrix addition


public static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int rows = matrix1.length;
int cols = matrix1[0].length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}

// Method to print the matrix


public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input matrix dimensions


System.out.print("Enter rows and columns for Matrix 1: ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();

System.out.print("Enter rows and columns for Matrix 2: ");


int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

// Matrix addition condition


if (rows1 != rows2 || cols1 != cols2) {
System.out.println("Matrices cannot be added due to different
dimensions.");
return;
}

// Input matrices
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];

System.out.println("Enter elements for Matrix 1:");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements for Matrix 2:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Matrix addition
int[][] result = addMatrices(matrix1, matrix2);

System.out.println("Result of Matrix Addition:");


printMatrix(result);
}
}
Multiplication
import java.util.Scanner;

public class MatrixMultiplication {

// Method for matrix multiplication


public static int[][] multiplyMatrices(int[][] matrix1, int[][]
matrix2) {
int rows = matrix1.length;
int cols = matrix2[0].length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
result[i][j] = 0;
for (int k = 0; k < matrix2.length; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}

// Method to print the matrix


public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input matrix dimensions


System.out.print("Enter rows and columns for Matrix 1: ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();

System.out.print("Enter rows and columns for Matrix 2: ");


int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

// Matrix multiplication condition (cols1 should be equal to rows2)


if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible due
to incompatible dimensions.");
return;
}

// Input matrices
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];
System.out.println("Enter elements for Matrix 1:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements for Matrix 2:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Matrix multiplication
int[][] result = multiplyMatrices(matrix1, matrix2);

System.out.println("Result of Matrix Multiplication:");


printMatrix(result);
}
}

6. the key features of Object-Oriented Programming (OOP) in Java:

Encapsulation

Encapsulation involves bundling data (variables) and methods that operate on the data into a
single unit (class). It also restricts direct access to some object components using access
modifiers (e.g., private, public).

class Employee {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}
Abstraction

Abstraction hides complex implementation details and exposes only essential features through
abstract classes or interfaces. It simplifies interaction with objects.

abstract class Animal {


abstract void sound();
}

class Dog extends Animal {


void sound() { System.out.println("Bark"); }
}

Inheritance

Inheritance allows a class to inherit properties and methods from another class, promoting code
reusability. The subclass can override methods of the superclass.

class Animal {
void eat() { System.out.println("Eating..."); }
}

class Dog extends Animal {


void eat() { System.out.println("Dog eating..."); }
}

Polymorphism

Polymorphism allows methods or objects to take multiple forms:

● Method Overloading (compile-time): Same method name, different parameters.


● Method Overriding (runtime): Subclass provides its own method implementation.

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

Association
Association defines relationships between objects. Types include:

● One-to-one, One-to-many, Many-to-many.

class Person {
Address address; // Association: Person has an Address
}

Composition

Composition is a stronger form of association, where one object is contained within another.
The contained object’s lifecycle is tied to the container object.

class Engine {
void start() { System.out.println("Engine starting..."); }
}

class Car {
Engine engine = new Engine(); // Car "Has-A" Engine
}

Delegation

Delegation is when an object relies on another object to perform tasks, promoting modularity
and code reuse.

class Printer {
void print(String message) { System.out.println(message); }
}

class Manager {
Printer printer = new Printer();
void delegatePrint(String msg) { printer.print(msg); }
}

7. Develop a Java program using packages for banking applications

Account.java
package com.bank.account;

public class Account {


private int accountNumber;
private String accountHolderName;
private double balance;

public Account(int accountNumber, String accountHolderName, double


balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

public void deposit(double amount) {


if (amount > 0) balance += amount;
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) balance -= amount;
}

public double getBalance() {


return balance;
}

public String getAccountHolderName() {


return accountHolderName;
}
}
SavingsAccount.java
package com.bank.account;

public class SavingsAccount extends Account {


private double interestRate;

public SavingsAccount(int accountNumber, String accountHolderName,


double balance, double interestRate) {
super(accountNumber, accountHolderName, balance);
this.interestRate = interestRate;
}
public void calculateInterest() {
System.out.println("Interest: " + getBalance() * interestRate / 100);
}
}
CurrentAccount.java
package com.bank.account;

public class CurrentAccount extends Account {


private double overdraftLimit;

public CurrentAccount(int accountNumber, String accountHolderName,


double balance, double overdraftLimit) {
super(accountNumber, accountHolderName, balance);
this.overdraftLimit = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (amount <= getBalance() + overdraftLimit) super.withdraw(amount);
else System.out.println("Exceeded overdraft limit.");
}
}
BankService.java
package com.bank.service;

import com.bank.account.Account;
import com.bank.account.SavingsAccount;
import com.bank.account.CurrentAccount;

public class BankService {

public void deposit(Account account, double amount) {


account.deposit(amount);
}

public void withdraw(Account account, double amount) {


account.withdraw(amount);
}

public void showBalance(Account account) {


System.out.println(account.getAccountHolderName() + " Balance: " +
account.getBalance());
}

public void calculateInterest(SavingsAccount account) {


account.calculateInterest();
}
}
BankApp.java
package com.bank.main;

import com.bank.account.SavingsAccount;
import com.bank.account.CurrentAccount;
import com.bank.service.BankService;

public class BankApp {


public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount(101, "Alice", 1000, 5);
CurrentAccount current = new CurrentAccount(102, "Bob", 500, 200);

BankService bankService = new BankService();

bankService.showBalance(savings);
bankService.showBalance(current);

bankService.deposit(savings, 200);
bankService.withdraw(savings, 150);
bankService.deposit(current, 100);
bankService.withdraw(current, 600);

bankService.calculateInterest(savings);
}
}

8.Write the step by step procedure for creating a package with a suitable example

Create a Package

To create a package, start by defining it at the top of your Java file using the package keyword.
The package name is usually written in lowercase to avoid conflicts with class names.

// File: Account.java
package com.example.bank;

public class Account {


private int accountNumber;
private String accountHolderName;
private double balance;

public Account(int accountNumber, String accountHolderName, double


balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

public void displayDetails() {


System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder Name: " + accountHolderName);
System.out.println("Balance: " + balance);
}
}

Save the File in the Correct Directory

After defining the package, save the Java file in the directory structure that matches the
package name. For example, for the package com.example.bank, save your file as:

com/example/bank/Account.java

The folder structure should mirror the package name.

Compile the Java File

Navigate to the root directory (the one above com) in the terminal and compile the file using
javac.

javac com/example/bank/Account.java

This will compile the Account.java file and create Account.class inside the corresponding
com/example/bank/ directory.
Use the Package in Another Class

To use the class defined in your package, you need to import it in another Java file. You can do
this by using the import statement.

// File: Test.java
import com.example.bank.Account;

public class Test {


public static void main(String[] args) {
Account account = new Account(101, "Alice", 1000);
account.displayDetails();
}
}

Save the Class in the Same Directory Structure

You should also save Test.java in the correct directory matching its package (if any). For
simplicity, we can save it in the root directory above com/.

Compile and Run the Program

Compile and run the program:

javac Test.java
java Test

Output:
Account Number: 101
Account Holder Name: Alice
Balance: 1000.0

PART - C
1 .Given an array of integers, rearrange the array in such a way that the first

element is first maximum and second element is first minimum.

Eg.) Input : {1, 2, 3, 4, 5, 6, 7} Output : {7, 1, 6, 2, 5, 3, 4}


import java.util.Arrays;

public class RearrangeArray {


public static void rearrange(int[] arr) {
// Step 1: Sort the array
Arrays.sort(arr);

int n = arr.length;
int[] result = new int[n];
int start = 0, end = n - 1;

// Step 2: Rearrange the array in the required order


for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
// Even index: Take from the end (maximum elements)
result[i] = arr[end];
end--;
} else {
// Odd index: Take from the start (minimum elements)
result[i] = arr[start];
start++;
}
}

// Output the rearranged array


System.out.println("Rearranged Array: " + Arrays.toString(result));
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5, 6, 7};
rearrange(arr); // Call the rearrange function
}
}

2. Given an array as input, The condition is if the number is repeated you


must add thenumber and put the next index value to 0. If the number is 0
print it at the last
Egarr[]={0,2,2,2,0,6,6,0,8}Output : { 4 ,2 ,12,8,0,0,0,0,0}

import java.util.*;

public class RearrangeArray {


public static void rearrange(int[] arr) {
// Step 1: Traverse the array and sum repeated elements
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
continue; // Skip 0s for now
}
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
arr[i] += arr[j]; // Sum the repeated number
arr[j] = 0; // Set the next occurrence to 0
}
}
}

// Step 2: Move all zeros to the end


int nonZeroIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[nonZeroIndex] = arr[i];
if (nonZeroIndex != i) {
arr[i] = 0;
}
nonZeroIndex++;
}
}

// Step 3: Output the modified array


System.out.println("Rearranged Array: " + Arrays.toString(arr));
}

public static void main(String[] args) {


int[] arr = {0, 2, 2, 2, 0, 6, 6, 0, 8};
rearrange(arr); // Call the rearrange function
}
}

You might also like