B.Tech (Fifth Semester) CBCS Summer 2023. (Information Technology)
Subject: Java Programming
Questions:
- Explain method overloading with example in java.
- Explain the following operators used in Java Programming
i) Arithmetic Operators
ii) Bitwise Operators
iii) Relational Operators
iv) Logical Operators - What is constructor? Explain the different types of constructor with example.
- With suitable Java program segment explain the keywords static & final.
- What is vector class in java? Write a program to demonstrate some of the methods associated with vector class.
- Define package. What are the types of Package? How to create and access the package?
- What is the significance of wrapper classes in java programs? Explain any one java wrapper class with suitable ova code.
- What is exception Handling in Java? Write a program to handle arithmetic exception.
- Write the two ways of creating threads in Java programming. Explain the methods isAlive() and join() and trace the output, when we use these methods in Java program.
- What do you mean by synchronization among the threads. Write a java program using synchronized keyword.
- What do you mean by multitasking and multithreading? Draw neatly the life cycle of a thread, explain with suitable Java program.
- Explain the following. i) Multithreading Applications in real life. ii) Sleep ( ) and suspend method.
- Write a java program which reads a string and then check whether the entered string is palindrome or not.
- Explain the methods of string class i) valueOf ii) toString
- Write a java Program in java, Calender class display the current date and display Date after 15 days, 4 month, 2 year later from current date.
- What is hashCode() method in Java? What is use of hashCode() method in Java” Write Java program to demonstrate working of hashCode() and toString().
- What is HashSet class? Write a program in Java to display elements in Hashset.
- What is Iterator Interface? Explain method defined in Iterator Interface.
- What is the collection interface? Explain method defined in collection interface.
- Write a program in Java to use of binary search method by using search algorithms in the collection Framework.
1. Method Overloading in Java
Method Overloading is compile-time polymorphism where multiple methods share the same name but differ in parameters (number, type, or order). It allows flexible method calls.
Example:
class OverloadDemo {
void display() { System.out.println("No args"); }
void display(int a) { System.out.println("Int: " + a); }
void display(String s) { System.out.println("String: " + s); }
}
public class Main {
public static void main(String[] args) {
OverloadDemo obj = new OverloadDemo();
obj.display(); // No args
obj.display(10); // Int: 10
obj.display("Hello"); // String: Hello
}
}
Output:
No args
Int: 10
String: Hello
2. Operators in Java
i) Arithmetic Operators: Perform mathematical operations.
+(addition),-(subtraction),*(multiplication),/(division),%(modulus).
Example:int a = 10 + 5; // 15
ii) Bitwise Operators: Operate on bits.
&(AND),|(OR),^(XOR),~(NOT),<<(left shift),>>(right shift),>>>(unsigned right shift).
Example:int b = 5 & 3; // 1
iii) Relational Operators: Compare values, return boolean.
==(equal),!=(not equal),>(greater),<(less),>=,<=.
Example:boolean c = 10 > 5; // true
iv) Logical Operators: Combine boolean expressions.
&&(AND),||(OR),!(NOT).
Example:boolean d = (true && false); // false
3. Constructor in Java
A constructor is a special method called when an object is created to initialize it. Same name as class, no return type.
Types:
- Default: No parameters, provided if none defined.
Example:class Test { Test() { System.out.println("Default"); } } - Parameterized: Accepts parameters.
Example:class Test { Test(int a) { System.out.println("Param: " + a); } } - Copy: Copies one object’s state to another.
Example:class Test { int x; Test(Test t) { x = t.x; } }
Full Example:
class Box {
int width;
Box() { width = 10; } // Default
Box(int w) { width = w; } // Parameterized
Box(Box b) { width = b.width; } // Copy
}
public class ConstructorDemo {
public static void main(String[] args) {
Box b1 = new Box(); // Default
Box b2 = new Box(20); // Parameterized
Box b3 = new Box(b2); // Copy
System.out.println("Widths: " + b1.width + ", " + b2.width + ", " + b3.width);
}
}
Output: Widths: 10, 20, 20
4. static & final Keywords
static: Belongs to class, not instances. Shared across objects, loaded once.
final: Constant; cannot be modified (variables), overridden (methods), or extended (classes).
Example:
class Demo {
static int count = 0; // Static variable
final int MAX = 100; // Final variable
static void increment() { // Static method
count++;
}
final void show() { // Final method
System.out.println("MAX: " + MAX + ", Count: " + count);
}
}
public class KeywordDemo {
public static void main(String[] args) {
Demo.increment(); // Static call
Demo obj = new Demo();
obj.show(); // Final method
}
}
Output: MAX: 100, Count: 1
5. Vector Class in Java
Vector is a dynamic array (java.util.Vector) that grows automatically, synchronized for thread-safety. Methods: add(), get(), remove(), size(), etc.
Program:
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<Integer> v = new Vector<>();
v.add(10); // add()
v.add(20);
System.out.println("Size: " + v.size()); // size()
System.out.println("Element at 0: " + v.get(0)); // get()
v.remove(0); // remove()
System.out.println("Updated: " + v);
}
}
Output:
Size: 2
Element at 0: 10
Updated: [20]
6. Package in Java
A package is a namespace for organizing classes/interfaces. Prevents naming conflicts.
Types:
- Built-in: Java-provided (e.g., java.util).
- User-defined: Custom (e.g., mypack).
Create: Use package mypack; at file top. Compile with -d ..
Access: Use import mypack.*; or fully qualified name.
Example: See question 7 from previous set for code.
7. Wrapper Classes in Java
Wrapper Classes convert primitives to objects (e.g., int to Integer). Significance: Use in collections, generics; provide utility methods.
Example: Integer Wrapper:
public class WrapperDemo {
public static void main(String[] args) {
int primitive = 10;
Integer wrapper = Integer.valueOf(primitive); // Wrap
System.out.println("Value: " + wrapper.intValue()); // Unwrap
System.out.println("Parse: " + Integer.parseInt("20")); // Utility
}
}
Output:
Value: 10
Parse: 20
8. Exception Handling in Java
Exception Handling manages runtime errors using try-catch-finally. Prevents abrupt termination.
Program for ArithmeticException:
public class ArithmeticExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup");
}
}
}
Output:
Error: / by zero
Cleanup
9. Creating Threads in Java
Ways:
- Extend
Threadclass, overriderun(). - Implement
Runnableinterface, pass toThread.
isAlive(): Checks if thread is alive.
join(): Waits for thread to finish.
Program:
class MyThread extends Thread {
public void run() { System.out.println("Thread running"); }
}
public class ThreadCreateDemo {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
System.out.println("Alive before start: " + t.isAlive()); // false
t.start();
System.out.println("Alive after start: " + t.isAlive()); // true
t.join(); // Wait
System.out.println("Alive after join: " + t.isAlive()); // false
}
}
Output:
Alive before start: false
Alive after start: true
Thread running
Alive after join: false
10. Synchronization in Threads
Synchronization ensures only one thread accesses shared resources at a time, preventing data inconsistency. Use synchronized keyword.
Program:
class Counter {
int count = 0;
synchronized void increment() { count++; }
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("Count: " + c.count); // 2000 (consistent)
}
}
Output: Count: 2000
11. Multitasking vs Multithreading
Multitasking: OS runs multiple processes concurrently.
Multithreading: Single process runs multiple threads concurrently, sharing resources.
Thread Lifecycle: New → Runnable → Running → Blocked/Waiting → Terminated.
Program (Multithreading):
class MultiThread implements Runnable {
public void run() { System.out.println("Thread: " + Thread.currentThread().getName()); }
}
public class MultiDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MultiThread(), "T1");
Thread t2 = new Thread(new MultiThread(), "T2");
t1.start(); t2.start();
}
}
Output (varies):
Thread: T1
Thread: T2
12. Multithreading Applications, sleep() and suspend()
i) Multithreading Applications: Real-life: Web servers (handle multiple requests), games (AI, rendering), media players (playback, UI).
ii) sleep(): Pauses thread for milliseconds (static, throws InterruptedException).
suspend(): Deprecated; pauses thread (unsafe, can cause deadlocks).
Example: Thread.sleep(1000); // Pause 1s
13. Palindrome String Program
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string: ");
String s = sc.nextLine();
String rev = new StringBuilder(s).reverse().toString();
if (s.equals(rev)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
Sample Output (input: “radar”): Palindrome
14. String Methods: valueOf() and toString()
valueOf(): Converts primitives/objects to String (static).
toString(): Returns string representation of object.
See question 15 from previous set for code example.
15. Calendar Class Program
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2025, Calendar.SEPTEMBER, 20); // Current: Sep 20, 2025
System.out.println("Current: " + cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 15); // +15 days
System.out.println("+15 days: " + cal.getTime());
cal.set(2025, Calendar.SEPTEMBER, 20); // Reset
cal.add(Calendar.MONTH, 4); // +4 months
System.out.println("+4 months: " + cal.getTime());
cal.set(2025, Calendar.SEPTEMBER, 20); // Reset
cal.add(Calendar.YEAR, 2); // +2 years
System.out.println("+2 years: " + cal.getTime());
}
}
Output (approximate format):
Current: Sat Sep 20 00:00:00 IST 2025
+15 days: Sun Oct 05 00:00:00 IST 2025
+4 months: Tue Jan 20 00:00:00 IST 2026
+2 years: Mon Sep 20 00:00:00 IST 2027
16. hashCode() in Java
hashCode(): Returns integer hash code for object, used in hashing (e.g., HashMap). Equals objects must have same hashCode.
Program:
class Person {
String name;
Person(String name) { this.name = name; }
@Override
public int hashCode() { return name.hashCode(); }
@Override
public String toString() { return "Person: " + name; }
}
public class HashDemo {
public static void main(String[] args) {
Person p = new Person("Alice");
System.out.println("hashCode: " + p.hashCode());
System.out.println("toString: " + p.toString());
}
}
Output (varies):
hashCode: 63405538
toString: Person: Alice
17. HashSet Class in Java
HashSet is a collection (java.util.HashSet) storing unique elements, no order, based on hash table.
Program:
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate ignored
System.out.println("Elements: " + set);
}
}
Output (order varies): Elements: [Apple, Banana]
18. Iterator Interface
Iterator (java.util.Iterator) traverses collections. Methods:
hasNext(): Returns true if more elements.next(): Returns next element.remove(): Removes last returned element (optional).
Example: Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); }
19. Collection Interface
Collection (java.util.Collection) is root interface for collections. Methods:
add(E e): Adds element.remove(Object o): Removes element.size(): Returns size.iterator(): Returns iterator.contains(Object o): Checks presence.
20. Binary Search in Collections
import java.util.ArrayList;
import java.util.Collections;
public class BinarySearchDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(5); list.add(1); list.add(3);
Collections.sort(list); // Must sort first
int index = Collections.binarySearch(list, 3);
System.out.println("Index of 3: " + index); // 2
}
}
Output: Index of 3: 2
Leave a Reply