0% found this document useful (0 votes)
8 views13 pages

2023 Winter

The document contains various programming concepts and examples in Java, including logical and bitwise operators, constructors, array initialization, thread lifecycle, file reading, ATM functionality, method overloading vs overriding, applet lifecycle, type conversion, vector usage, interest calculations, exception handling, and complex number operations. It provides code snippets for practical implementation of these concepts. Additionally, it discusses errors in programming and thread priority management.

Uploaded by

pranjalghatge18
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)
8 views13 pages

2023 Winter

The document contains various programming concepts and examples in Java, including logical and bitwise operators, constructors, array initialization, thread lifecycle, file reading, ATM functionality, method overloading vs overriding, applet lifecycle, type conversion, vector usage, interest calculations, exception handling, and complex number operations. It provides code snippets for practical implementation of these concepts. Additionally, it discusses errors in programming and thread priority management.

Uploaded by

pranjalghatge18
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/ 13

Q.

a)Enlist any two logical operators and two bitwise operators.

Logical Operators:
 && (Logical AND)
 || (Logical OR)
Bitwise Operators:
 & (Bitwise AND)
 | (Bitwise OR)
b) Define constructor.

A constructor is a special method used to initialize objects of a class when they


are created. It has the same name as the class and is called automatically when
an object is instantiated.

c) Write down the syntax of array declaration, initialization.

dataType[] arrayName;

dataType[] arrayName = new dataType[size];

d) List out different ways to access package from another package.

Using import Statement:

java
Copy code
import packageName.ClassName;
or
import packageName.*;

Using Fully Qualified Name:

java
Copy code
packageName.ClassName obj = new packageName.ClassName();

e) Differentiate between starting thread with run ( ) method and start ( ) method.
Q.2

a)Write a program to display ASCII value of a number 9.

public class AsciiValue {

public static void main(String[] args) {

char number = '9'; // Character '9'

int ascii = (int) number; // Cast to int to get ASCII value

System.out.println("The ASCII value of '9' is: " + ascii);

b) Write a program to sort the elements of an array in ascending order.

import java.util.Arrays;

public class SortArray {

public static void main(String[] args) {

int[] numbers = {5, 2, 8, 1, 3};

Arrays.sort(numbers); // Sort the array in ascending order

System.out.println("Sorted array: " + Arrays.toString(numbers));

c) Define Thread. Draw life cycle of Thread

A thread is a lightweight sub-process and the smallest unit of a process. It enables concurrent
execution of tasks within a program.

New: A thread is created using Thread class but hasn't started.

Runnable: The thread is ready to run and waiting for CPU allocation

Running: The thread is currently executing.

Blocked/Waiting: The thread is temporarily inactive and waiting for a resource or a signal.

Terminated: The thread has finished execution.


d) Write a program to read a file and then count number of words.

import java.io.*;

import java.util.Scanner;

public class WordCount {

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

File file = new File("example.txt"); // File to read

Scanner scanner = new Scanner(file);

int wordCount = 0;

while (scanner.hasNext()) {

scanner.next();

wordCount++;

scanner.close();

System.out.println("Number of words: " + wordCount);

Q.3

a) Write a program which displays functioning of ATM machine, (Hint : Withdraw, Deposit, Check
Balance and Exit)

import java.util.Scanner;

public class SimpleATM {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double balance = 0.0;

int choice;

do {

System.out.println("\n1. Withdraw\n2. Deposit\n3. Check Balance\n4. Exit");

System.out.print("Choose an option: ");

choice = scanner.nextInt();
switch (choice) {

case 1:

System.out.print("Enter amount to withdraw: ");

double withdrawAmount = scanner.nextDouble();

if (withdrawAmount > balance) {

System.out.println("Insufficient balance!");

} else {

balance -= withdrawAmount;

System.out.println("New balance: " + balance);

break;

case 2:

System.out.print("Enter amount to deposit: ");

balance += scanner.nextDouble();

System.out.println("New balance: " + balance);

break;

case 3:

System.out.println("Current balance: " + balance);

break;

case 4:

System.out.println("Thank you for using the ATM.");

break;

default:

System.out.println("Invalid choice!");

} while (choice != 4);

scanner.close();

}
b).Differentiate between method overloading and method overriding.

c).Explain applet life cycle in detail

1. Initialization (init() method)


 The first method called when an applet is created
 Executed only once during runtime
 Used to initialize variables and set up initial applet configurations

2. Starting (start() method)


 Called immediately after the init() method
 Invoked when the browser is maximized

3. Painting (paint() method)


 Responsible for displaying content on the applet
 Takes Graphics class as a parameter

4. Stopping (stop() method)


 Invoked when the browser is minimized
 Pauses the applet's execution

5. Destruction (destroy() method)


 Completely closes and removes the applet from memory
 Can be invoked only once
 Cannot restore the applet after destruction

Q.4

a) Explain implicit and explicit type conversion with example in detail

Definition: Implicit type conversion, also known as widening or automatic conversion, occurs when
a lower data type is automatically converted into a higher data type without any explicit instructions
from the programmer.

Ex;public class ImplicitConversion {

public static void main(String[] args) {

int num = 100;

double result = num;

System.out.println("Integer value: " + num);

System.out.println("Converted to double: " + result);

Definition: Explicit type conversion, also known as narrowing or manual casting, occurs when a
higher data type is explicitly converted to a lower data type, which might result in a loss of data.

public class ExplicitConversion {

public static void main(String[] args) {

double num = 100.99;

int result = (int) num;

System.out.println("Original double value: " + num);

System.out.println("Converted to int: " + result);

b) Write a program to show the use of copy constructor


class Person {

String name;

int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

public Person(Person other) {

this.name = other.name;

this.age = other.age;

public void display() {

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

public class CopyConstructorExample {

public static void main(String[] args) {

Person person1 = new Person("Alice", 25);

Person person2 = new Person(person1);

person1.display();

person2.display();

c) Write a program to show the Hierarchical inheritance

class Animal {

void eat() {

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

class Dog extends Animal {

void bark() {
System.out.println("Dog is barking");

class Cat extends Animal {

void meow() {

System.out.println("Cat is meowing");

public class HierarchicalInheritance {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat();

dog.bark();

Cat cat = new Cat();

cat.eat();

cat.meow();

d) Explain any four font methods with example.

1.getName():Returns the name of the font.


2.getStyle():Returns the style of the font (such as Font.BOLD, Font.ITALIC,
or Font.PLAIN). It is used to find out whether the font is bold, italic, or plain.
3.getSize(): Returns the size (point size) of the font.
4.deriveFont(int style): Creates a new font object based on the current
font but with a different style
import java.awt.Font;

public class FontExample {

public static void main(String[] args) {

Font font = new Font("Arial", Font.PLAIN, 14);

System.out.println("Font Name: " + font.getName());

int style = font.getStyle();

System.out.println("Font Style: " + (style == Font.BOLD ? "Bold" : "Not Bold"));


System.out.println("Font Size: " + font.getSize());

Font boldFont = font.deriveFont(Font.BOLD);

System.out.println("Derived Font Style: " + boldFont.getStyle());

Q.5

a) Explain vector with the help of example. Explain any 3 methods of vector class.

A Vector is a part of the Java Collection Framework that implements a growable array of objects. It
is similar to an array but can dynamically resize itself when elements are added or removed.

It can hold any type of objects and provides methods to manipulate and access the elements.

Ex; import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

Vector<String> vector = new Vector<>();

vector.add("Apple");

vector.add("Banana");

vector.add("Cherry");

System.out.println("Vector: " + vector);

b) Develop and Interest Interface which contains Simple Interest and Compound Interest methods
and static final field of rate 25%. Write a class to implement those methods.

interface Interest {

static final double rate = 25.0;

double SimpleInterest(double principal, int time);

double CompoundInterest(double principal, int time);

class IntCalculator implements Interest {

public double SimpleInterest(double principal, int time) {

return (principal * rate * time) / 100;

public double CompoundInterest(double principal, int time) {


return principal * Math.pow((1 + rate / 100), time) - principal;

public class Example {

public static void main(String[] args) {

IntCalculator calc = new IntCalculator();

double principal = 1000.0;

int time = 2;

System.out.println(calc.SimpleInterest(principal, time));

System.out.println(calc.CompoundInterest(principal, time));

c) Write a program that throws an exception called “NoMatchException” when a string is not equal
to “India”.

class NoMatchException extends Exception {

public NoMatchException() {

super("String does not match 'India'");

public NoMatchException(String message) {

super(message);

public class StringMatchExceptionDemo {

public static void validateCountry(String country) throws NoMatchException {

if (!country.equals("India")) {

throw new NoMatchException("Entered country '" + country + "' is not India");

} else {

System.out.println("Country matched successfully: " + country);

public static void main(String[] args) {


try {

validateCountry("India");

validateCountry("USA");

} catch (NoMatchException e) {

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

Q.6

a) Write a program to print the sum, difference and product of two complex numbers by creating a
class named “Complex” with separate methods for each operation whose real and imaginary parts
are entered by user

import java.util.Scanner;

class Complex {

private int real, imag;

Complex(int real, int imag) {

this.real = real;

this.imag = imag;

Complex add(Complex c) {

return new Complex(this.real + c.real, this.imag + c.imag);

Complex subtract(Complex c) {

return new Complex(this.real - c.real, this.imag - c.imag);

Complex multiply(Complex c) {

return new Complex(this.real * c.real - this.imag * c.imag, this.real * c.imag + this.imag * c.real);
}

@Override

public String toString() {

return real + (imag >= 0 ? " + " : " - ") + Math.abs(imag) + "i";

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter real and imaginary parts of first complex number: ");

Complex c1 = new Complex(sc.nextInt(), sc.nextInt());

System.out.print("Enter real and imaginary parts of second complex number: ");

Complex c2 = new Complex(sc.nextInt(), sc.nextInt());

System.out.println("Sum: " + c1.add(c2));

System.out.println("Difference: " + c1.subtract(c2));

System.out.println("Product: " + c1.multiply(c2));

sc.close();

b)

i) Explain Errors and its types in detail.

ii) Explain thread methods to set and get priority.

Errors in programming refer to issues or faults that prevent a program from functioning correctly.
They can occur at different stages of the program execution: compilation, runtime, or during logical
operations

1. Syntax Errors:

 Definition: These errors occur when the rules of the programming language are violated.
2. Runtime Errors:

 Definition: These errors occur during the execution of a program.

3. Logical Errors:

 Definition: These errors occur when the program runs without crashing but produces
incorrect results.

In Java, threads can have priorities that influence the order in which threads are scheduled for
execution.

Thread priorities allow you to suggest to the thread scheduler which threads should get preference
for CPU time, but the final behavior depends on the operating system's thread scheduling
mechanism.

1. Setting Thread Priority

The setPriority(int priority) method is used to assign a priority to a thread.

thread.setPriority(int priority);

2. Getting Thread Priority

The getPriority() method retrieves the priority of a thread.

int priority = thread.getPriority();

You might also like