B.Tech (Fifth Semester) CBCS Winter 2022. (Information Technology)
Subject: Java Programming
Questions:
- Explain the features of Java Programming.
- Write a java program to overload the method sum(), such that
i) sum() returns 0
ii) sum(n) returns n
iii) sum(m,n) return m+n
iv) sum(x,y,z) return x+y+z - Justify, “Java is platform independent”
- Define constructor. Mention rules to define it. Explain the use of constructor with suitable example.
- Create a java program to sort the elements of an array of dimensions 10 using Bubble sort.
- Elaborate Exceptions in Java. Explain how it is handled in java using example.
- What is Package? Why do we need packages in java? Elaborate on user defined package with suitable example.
- Write a program in java: A class “Employee” contains two fields “Name” and “Designation” extends the class to “Person“, it contains “DOB” and “Mobile Number”. An interface named as Company contains one field “name of the company”. Using the above class and interface get the appropriate information and display it.
- What is thread? Explain and Describe the complete lifecycle of Thread.
- Write a program to create two threads one to add numbers and another to print even numbers between 1 to 100, after printing each number thread should stop from 2000m sec.
- Explain in brief inter-thread communication.
- What is Thread Priority? Explain with an example.
- Write the constructors for the i) Date class ii) Calendar class.
- Write a program which reads two strings from the keyboard and then compare them. Also write a code which modify the suing “java” to “tava”.
- What is string class? And explain the methods valued() and toString() with suitable java program.
- Explain the following methods with suitable java code and discuss the output obtained by them: i) toUpper() ii) equalsIgnorecase() iii) compareTo()
- What is a vector? Write a program to create vector with 7 elements, first 2 integers, 2 are strings and remaining are floats, remove the element at 5th location, display the content of updated vector.
- What is nested class in java? Write a code to elaborate the advantage of using inner class in Java.
- Create a Arraylist of String. Add any five names of fruits and sort them in ascending order using Collection’s sort method
- Mention the difference between Comparable and Comparator interlace.
1. Features of Java Programming
Java is a high-level, object-oriented programming language known for its robustness and portability. Key features include:
- Platform Independence: Compiled to bytecode, runs on any JVM.
- Object-Oriented: Supports encapsulation, inheritance, polymorphism, and abstraction.
- Simple and Secure: No pointers, automatic garbage collection, built-in security features.
- Multithreaded: Built-in support for concurrent execution.
- Robust: Strong exception handling and type checking.
- Portable and Interpreted: Write once, run anywhere (WORA).
- Dynamic: Supports runtime modifications via reflection.
2. Method Overloading for sum()
Method overloading allows multiple methods with the same name but different parameters.
public class SumOverload {
int sum() {
return 0;
}
int sum(int n) {
return n;
}
int sum(int m, int n) {
return m + n;
}
int sum(int x, int y, int z) {
return x + y + z;
}
public static void main(String[] args) {
SumOverload obj = new SumOverload();
System.out.println("sum(): " + obj.sum());
System.out.println("sum(5): " + obj.sum(5));
System.out.println("sum(2, 3): " + obj.sum(2, 3));
System.out.println("sum(1, 2, 3): " + obj.sum(1, 2, 3));
}
}
Output:
sum(): 0
sum(5): 5
sum(2, 3): 5
sum(1, 2, 3): 6
3. Java is Platform Independent
Java achieves platform independence through its “Write Once, Run Anywhere” (WORA) principle. Source code (.java) is compiled into bytecode (.class) by the Java compiler (javac). This bytecode is not machine-specific and is executed by the Java Virtual Machine (JVM), which is platform-dependent. The JVM interprets or JIT-compiles bytecode to native machine code at runtime. Thus, the same bytecode runs on any OS (Windows, Linux, macOS) with a compatible JVM, without recompilation.
4. Constructor Definition and Rules
A constructor is a special method invoked automatically when an object is created. It initializes object state and has the same name as the class, no return type.
Rules:
- Name must match class name.
- No explicit return type (not even void).
- Can be overloaded.
- Cannot be abstract, static, final, or synchronized.
- Default constructor provided if none defined.
Example:
class Rectangle {
int length, width;
// Default constructor
Rectangle() {
length = 10;
width = 5;
}
// Parameterized constructor
Rectangle(int l, int w) {
length = l;
width = w;
}
int area() { return length * width; }
}
public class ConstructorDemo {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // Default
Rectangle r2 = new Rectangle(20, 10); // Parameterized
System.out.println("Area1: " + r1.area());
System.out.println("Area2: " + r2.area());
}
}
Output:
Area1: 50
Area2: 200
5. Bubble Sort Program
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps if in wrong order.
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2, 7, 1, 10, 6, 9}; // Array of 10 elements
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
Output: Sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6. Exceptions in Java
Exceptions are runtime errors disrupting normal program flow (e.g., division by zero). Java classifies them as:
- Checked: Compile-time (e.g., IOException) – must be handled.
- Unchecked: Runtime (e.g., NullPointerException) – optional handling.
- Errors: System issues (e.g., OutOfMemoryError) – usually unrecoverable.
Handling: Use try-catch-finally. Try: risky code; Catch: handle exception; Finally: cleanup.
Example:
public class ExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup done");
}
}
}
Output:
Error: / by zero
Cleanup done
7. Packages in Java
A package is a namespace organizing classes and interfaces, preventing naming conflicts.
Need: Code organization, access control, reusability (e.g., modular projects).
User-Defined Package Example:
- Create directory:
mypackage - File:
MyClass.javain mypackage
// mypackage/MyClass.java
package mypackage;
public class MyClass {
public void greet() {
System.out.println("Hello from package!");
}
}
- Main file:
// Main.java
import mypackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.greet();
}
}
Compile: javac mypackage/MyClass.java Main.java
Run: java Main
Output: Hello from package!
8. Employee, Person, and Company Program
class Employee {
String name, designation;
Employee(String name, String designation) {
this.name = name;
this.designation = designation;
}
}
class Person extends Employee {
String dob;
long mobile;
Person(String name, String designation, String dob, long mobile) {
super(name, designation);
this.dob = dob;
this.mobile = mobile;
}
void display() {
System.out.println("Name: " + name + ", Designation: " + designation);
System.out.println("DOB: " + dob + ", Mobile: " + mobile);
}
}
interface Company {
String companyName = "TechCorp"; // Constant
}
public class InfoDisplay implements Company {
public static void main(String[] args) {
Person p = new Person("John", "Developer", "1990-01-01", 1234567890L);
p.display();
System.out.println("Company: " + companyName);
}
}
Output:
Name: John, Designation: Developer
DOB: 1990-01-01, Mobile: 1234567890
Company: TechCorp
9. Thread and Lifecycle
A thread is a lightweight process enabling concurrent execution within a program. Java threads extend Thread or implement Runnable.
Lifecycle:
- New: Created but not started (
new Thread()). - Runnable: Ready to run after
start()(scheduled by JVM). - Running: Executing code in
run(). - Blocked/Waiting: Waiting for resources (e.g., I/O,
wait()). - Timed Waiting: Sleeping (
sleep()) or timed wait. - Terminated: Completed execution or exception.
10. Two Threads Program
class AddNumbers extends Thread {
public void run() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
class PrintEven extends Thread {
public void run() {
for (int i = 2; i <= 100; i += 2) {
System.out.print(i + " ");
try {
Thread.sleep(2000); // 2000 ms pause
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
AddNumbers t1 = new AddNumbers();
PrintEven t2 = new PrintEven();
t1.start();
t2.start();
}
}
Note: Output interleaves; sum prints quickly, evens with 2s delays.
11. Inter-Thread Communication
Inter-thread communication allows threads to coordinate using shared objects and methods like wait(), notify(), notifyAll() from Object class. Used in producer-consumer scenarios to avoid polling. wait() releases lock and waits; notify() wakes one waiting thread.
Example: Producer notifies consumer after producing data (see producer-consumer code for full demo).
12. Thread Priority
Thread Priority determines scheduling preference (1-10; default 5). Higher priority threads get more CPU time, but not guaranteed due to OS scheduler.
Example:
class PriorityThread extends Thread {
public PriorityThread(String name, int priority) {
super(name);
setPriority(priority);
}
public void run() {
System.out.println(getName() + " running with priority " + getPriority());
}
}
public class PriorityDemo {
public static void main(String[] args) {
PriorityThread t1 = new PriorityThread("High", Thread.MAX_PRIORITY);
PriorityThread t2 = new PriorityThread("Low", Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
Output (may vary): High thread often runs first.
13. Constructors for Date and Calendar
i) Date Class (java.util.Date; deprecated for new code):
Date(): Current date/time.Date(long millis): From milliseconds since 1970-01-01.
ii) Calendar Class (java.util.Calendar; abstract, use getInstance()):
- No public constructors; use
Calendar.getInstance()for default. getInstance(TimeZone zone): With specific timezone.getInstance(Locale locale): With locale.
Use modern java.time API instead.
14. String Comparison and Modification
import java.util.Scanner;
public class StringOps {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string1: ");
String s1 = sc.nextLine();
System.out.print("Enter string2: ");
String s2 = sc.nextLine();
if (s1.equals(s2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings differ");
}
String modified = "java".replace('j', 't');
System.out.println("Modified: " + modified);
}
}
Sample Output (input: “hello”, “hello”):
Strings are equal
Modified: tava
15. String Class and Methods
String Class: Immutable sequence of characters (java.lang.String). Thread-safe, stored in string pool.
valueOf(): Converts primitives/objects to String.
toString(): Returns string representation of object.
public class StringMethods {
public static void main(String[] args) {
int num = 123;
String s1 = String.valueOf(num); // "123"
System.out.println("valueOf: " + s1);
Object obj = new Object();
String s2 = obj.toString(); // Object's string rep
System.out.println("toString: " + s2);
}
}
Output:
valueOf: 123
toString: java.lang.Object@<hash>
16. String Methods: toUpperCase(), equalsIgnoreCase(), compareTo()
public class StringCaseDemo {
public static void main(String[] args) {
String s = "hello";
// i) toUpperCase(): Converts to uppercase
System.out.println("toUpperCase: " + s.toUpperCase()); // HELLO
// ii) equalsIgnoreCase(): Case-insensitive equality
System.out.println("equalsIgnoreCase: " + s.equalsIgnoreCase("HELLO")); // true
// iii) compareTo(): Lexicographical comparison (negative if s < other, 0 if equal, positive if s > other)
System.out.println("compareTo: " + s.compareTo("world")); // Negative (h < w)
}
}
Output:
toUpperCase: HELLO
equalsIgnoreCase: true
compareTo: -15
17. Vector in Java
A Vector is a dynamic array (java.util.Vector) that grows automatically, synchronized for thread-safety.
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<Object> v = new Vector<>();
v.add(10); // Integer
v.add(20); // Integer
v.add("Apple"); // String
v.add("Banana"); // String
v.add(3.5f); // Float
v.add(4.5f); // Float
v.add(5.5f); // Float
v.remove(4); // Remove at index 4 (5th element)
System.out.println("Updated Vector: " + v);
}
}
Output: Updated Vector: [10, 20, Apple, Banana, 4.5, 5.5]
18. Nested Class in Java
A nested class is a class defined inside another class. Types: static nested, inner (non-static). Advantages: Logical grouping, encapsulation, access to outer class members.
Example (Inner Class Advantage: Access private members):
class Outer {
private int data = 100;
class Inner {
void display() {
System.out.println("Inner accesses private: " + data); // Advantage
}
}
}
public class NestedDemo {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
Output: Inner accesses private: 100
19. ArrayList Sort Program
import java.util.ArrayList;
import java.util.Collections;
public class FruitSort {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Mango");
fruits.add("Grape");
Collections.sort(fruits); // Ascending sort
System.out.println("Sorted fruits: " + fruits);
}
}
Output: Sorted fruits: [Apple, Banana, Grape, Mango, Orange]
20. Comparable vs Comparator Interface
| Aspect | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Usage | Natural ordering (implement in class) | Custom/external ordering (separate class) |
| Sorting | Collections.sort(list) | Collections.sort(list, comparator) |
| Flexibility | Fixed per class | Multiple per class |
Example: Comparable for default sort; Comparator for reverse/alternate sort.
Leave a Reply