0% found this document useful (0 votes)
12 views7 pages

Java Programming Examples and Tasks

The document contains multiple Java programming examples demonstrating various concepts such as JDBC for database operations, synchronization with threads, custom exceptions, HashMap operations, and finding middle elements in arrays. It also covers object-oriented programming principles like abstract classes, encapsulation, composition, multiple inheritance using interfaces, and the use of static and non-static variables in a counter class. Each example includes code snippets and explanations of the functionality implemented.

Uploaded by

likhitha0324
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)
12 views7 pages

Java Programming Examples and Tasks

The document contains multiple Java programming examples demonstrating various concepts such as JDBC for database operations, synchronization with threads, custom exceptions, HashMap operations, and finding middle elements in arrays. It also covers object-oriented programming principles like abstract classes, encapsulation, composition, multiple inheritance using interfaces, and the use of static and non-static variables in a counter class. Each example includes code snippets and explanations of the functionality implemented.

Uploaded by

likhitha0324
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

A1 + A2 Java

1. JDBC Program to Create and Fetch Data

import [Link].*;

public class JDBCExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";

try (Connection conn = [Link](url, user,


password)) {
Statement stmt = [Link]();
[Link]("CREATE TABLE IF NOT EXISTS Employee (id INT, name
VARCHAR(50), salary DOUBLE)");

[Link]("INSERT INTO Employee VALUES (1, 'Alice', 50000), (2,


'Bob', 60000), " +

"(3, 'Charlie', 70000), (4, 'David', 80000), (5, 'Eve', 90000)");

ResultSet rs = [Link]("SELECT * FROM Employee");


while ([Link]()) {
[Link]([Link]("id") + " " + [Link]("name")
+ " " + [Link]("salary"));
}
} catch (SQLException e) {
[Link]();
}
}
}

2. Program to Demonstrate synchronized Keyword

class SharedResource {
public synchronized void printNumbers() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}

1
}
}
}

public class SynchronizedExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

Thread t1 = new Thread(() -> [Link](), "Thread-1");


Thread t2 = new Thread(() -> [Link](), "Thread-2");

[Link]();
[Link]();
}
}

3. Custom Exception for Insufficient Balance

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {
super(message);
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
double balance = 5000;
double withdrawAmount = 6000;

try {
if (withdrawAmount > balance) {
throw new
InsufficientBalanceException("Insufficient balance for withdrawal.");
}
balance -= withdrawAmount;
[Link]("Withdrawal successful. Remaining balance: " +
balance);
} catch (InsufficientBalanceException e) {
[Link]([Link]());
}
}
}

2
4. HashMap Operations

import [Link];

public class HashMapOperations {


public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();

// Adding elements
[Link](1, "Alice");
[Link](2, "Bob");
[Link](3, "Charlie");

// Displaying elements
[Link]("Initial HashMap: " + map);

// Removing an element
[Link](2);
[Link]("After removal: " + map);

// Updating an element
[Link](3, "David");
[Link]("After update: " + map);
}
}

5. Finding the Middle Element in an Array

public class MiddleElement {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int middle = [Link] / 2;

if ([Link] % 2 == 0) {
[Link]("Middle elements: " + arr[middle - 1] + ", " +
arr[middle]);
} else {
[Link]("Middle element: " + arr[middle]);
}
}
}

3
A3 + A4 Java

1. Abstract Class Example

abstract class Animal {


String name;

public Animal(String name) {


[Link] = name;
}

abstract void makeSound();


}

class Dog extends Animal {


public Dog(String name) {
super(name);
}

@Override
void makeSound() {
[Link](name + ": Bow Bow");
}
}

class Cat extends Animal {


public Cat(String name) {
super(name);
}

@Override
void makeSound() {
[Link](name + ": Meowww...");
}
}

public class AbstractExample {


public static void main(String[] args) {
Animal dog = new Dog("Bobby");
Animal cat = new Cat("Tommy");

[Link]();
[Link]();
}
}

4
2. Encapsulation with Student Class

class Student {
private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


[Link] = age;
}
}

public class EncapsulationExample {


public static void main(String[] args) {
Student student = new Student();
[Link]("Alice");
[Link](20);

[Link]("Name: " + [Link]());


[Link]("Age: " + [Link]());
}
}

3. Composition and Aggregation Example

class Engine {
public void start() {
[Link]("Engine started...");
}
}

class Car {
private Engine engine;

public Car() {

5
engine = new Engine();
}

public void drive() {


[Link]();
[Link]("Car is driving...");
}
}

public class CompositionExample {


public static void main(String[] args) {
Car car = new Car();
[Link]();
}
}

4. Multiple Inheritance Using Interfaces

interface A {
void methodA();
}

interface B {
void methodB();
}

class C implements A, B {
@Override
public void methodA() {
[Link]("Method A");
}

@Override
public void methodB() {
[Link]("Method B");
}
}

public class InterfaceExample {


public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}

6
5. Counter Class with Static and Non-Static Variables

class Counter {
private static int count = 0;
private int instanceNumber;

public Counter() {
count++;
instanceNumber = count;
}

public void print() {


[Link]("Instance Number: " + instanceNumber + ", Count: " +
count);
}
}

public class CounterExample {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

[Link]();
[Link]();
[Link]();
}
}

Common questions

Powered by AI

Encapsulation is essential in object-oriented programming because it restricts unauthorized access to an object's data and ensures internal representation is hidden from the outside. The 'Student' class demonstrates this by using private fields for 'name' and 'age', exposing them only through public getter and setter methods. This control allows validation or modification logic within the setters and getters, ensuring data integrity and maintaining the object's invariants .

The Counter class illustrates differences between static and non-static variables, where static variables are shared across all instances, and non-static variables are instance-specific. The 'count' variable is static, incremented every time a new 'Counter' is created, reflecting the total number of 'Counter' instances. In contrast, 'instanceNumber' is non-static, preserving its unique number per instance, determined by the static 'count' at instantiation, demonstrating how static fields provide class-wide properties while non-static preserve individual state .

Using synchronized methods in Java ensures that only one thread can execute a method at any moment, effectively preventing race conditions and ensuring data consistency. In the 'SynchronizedExample' given, the shared resource 'printNumbers' method is synchronized, meaning when one thread enters, the other is blocked until the first thread finishes executing. This guarantees that the numbers are printed sequentially without interleaving from different threads .

Interfaces resolve the diamond problem by allowing a class to implement multiple interfaces without the ambiguity issues related to method inheritance seen with classes. In the example, class 'C' implements interfaces 'A' and 'B', each defining different methods. Because interfaces only provide method signatures without implementation, 'C' provides its specific implementations, eliminating method conflicts typical in class-based multiple inheritance, ensuring clear and consistent behavior .

Abstract classes and inheritance in Java improve code reusability by allowing a superclass to define general behaviors for its subclasses, which can override these behaviors as needed. In the provided example, the 'Animal' class is abstract with a method 'makeSound()'. Subclasses 'Dog' and 'Cat' inherit properties from 'Animal' and provide specific sound implementations. This allows for flexibility and reuse of the 'Animal' class structure, reducing code duplication and improving maintainability .

Data structures like HashMap are important in Java for efficient data access and manipulation, increasing performance by providing constant-time complexity for basic operations such as insertions, deletions, and lookups. The HashMap example demonstrates managing key-value pairs, where users can quickly add, remove, or update entries. Its use in storing and retrieving data mapped by keys showcases the efficiency and speed improvements in handling large data sets compared to more basic structures like lists or arrays .

Exceptions in Java help maintain robust applications by providing a mechanism to handle errors gracefully. In the example, the custom exception 'InsufficientBalanceException' extends the Exception class to signal errors related to insufficient funds during a withdrawal operation. By throwing and catching this exception, the program avoids undefined behaviors or crashes and provides clear feedback ('Insufficient balance for withdrawal') to the user, enhancing user experience and system reliability .

Handling checked exceptions in Java is crucial because they enforce error handling at compile time, ensuring potential errors are addressed. In the custom exception example, 'InsufficientBalanceException' is a checked exception, meaning its occurrence must be declared or caught by the method with 'throws'. This mechanism compels developers to provide explicit error handling for predictable conditions, improving robustness and reliability by preventing certain runtime errors from manifesting unchecked .

Composition in Java involves building classes using references to other objects, allowing more flexible and maintainable designs compared to inheritance. In the example, a 'Car' class contains a reference to an 'Engine' object, which it uses to perform actions like 'drive'. Unlike inheritance, where a subclass is a type of its parent class, composition allows a class to utilize different features by combining them, promoting code reuse and reducing the fragility often introduced by deep inheritance chains .

JDBC (Java Database Connectivity) allows Java applications to interact with databases by using a set of APIs to execute SQL queries. In the 'JDBCExample', a connection to a MySQL database 'testdb' is established using DriverManager.getConnection(). SQL queries are executed using a Statement object, which creates a table and inserts data if the table does not exist. Queries are also used to fetch data, iterating over the ResultSet to process the retrieved information, demonstrating how JDBC manages database interactions through a consistent interface .

You might also like