0% found this document useful (0 votes)
13 views45 pages

Java 39072810 2025 01 23 16 01

The document provides an overview of Java programming, covering key concepts such as method and constructor overloading, inheritance types, method overriding, interfaces, and packages. It explains the principles of object-oriented programming, including polymorphism and access modifiers, and illustrates these concepts with code examples. Additionally, it discusses I/O streams and collections in Java, emphasizing the importance of stream types for handling data input and output.

Uploaded by

reddynanda426
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)
13 views45 pages

Java 39072810 2025 01 23 16 01

The document provides an overview of Java programming, covering key concepts such as method and constructor overloading, inheritance types, method overriding, interfaces, and packages. It explains the principles of object-oriented programming, including polymorphism and access modifiers, and illustrates these concepts with code examples. Additionally, it discusses I/O streams and collections in Java, emphasizing the importance of stream types for handling data input and output.

Uploaded by

reddynanda426
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/ 45

Java Programming

Basics of Java and Overloading

Basics of Java:

• Java Overview:
o Java is an object-oriented programming language designed to be platform-
independent.
o WORA (Write Once, Run Anywhere): Java code is compiled into bytecode,
which can run on any system with a Java Virtual Machine (JVM).

Simple Java Program:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Overloading:

• Method Overloading: Methods in a class with the same name but different
parameters.
• Constructor Overloading: Multiple constructors in a class with different parameter
lists.

Key Points:

1. Same Method Name: All overloaded methods must have the same name.
2. Different Parameters: Overloaded methods must differ in the type or number of
their parameters. It can also be a combination of both.
3. Return Type: The return type can be different, but it alone cannot be used to
distinguish overloaded methods. The parameter list must differ.
4. Constructor Overloading: Constructors can also be overloaded in a similar way to
methods.

Example:

class MathUtils {
// Overloaded method with two int parameters
public int add(int a, int b) {
return a + b;
}
// Overloaded method with three int parameters
public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method with two double parameters


public double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
MathUtils mathUtils = new MathUtils();

System.out.println(mathUtils.add(10, 20)); // Calls add(int, int)


System.out.println(mathUtils.add(10, 20, 30)); // Calls add(int, int, int)
System.out.println(mathUtils.add(10.5, 20.5)); // Calls add(double, double)
}
}

Why Use Overloading?

• Improved Readability: Having methods with the same name but different
parameters improves code readability.
• Simplifies Development: Overloading allows you to define multiple methods that do
similar work with different parameters, simplifying the development process.

Rules to Remember:

• You cannot overload methods that differ only by return type.


• Method overloading is not supported by changing only the return type, the access
specifier, or the static keyword.
Concepts of Inheritance, Overriding, Interfaces, and Packages
Inheritance:

Inheritance is a key principle of object-oriented programming that allows one class


(subclass/child class) to inherit fields and methods from another class (superclass/parent
class).

• Superclass (Parent Class): The class whose features are inherited.


• Subclass (Child Class): The class that inherits the features.

Example:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}
Types of Inheritance:

1. Single Inheritance

In single inheritance, a class inherits from one superclass only. This is the simplest form of
inheritance.

Example:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}

2. Multilevel Inheritance

In multilevel inheritance, a class is derived from another class, which is also derived from
another class. This creates a chain of inheritance.

Example:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks.");
}
}

class Puppy extends Dog {


void weep() {
System.out.println("The puppy weeps.");
}
}

public class Main {


public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep(); // Defined in Puppy
}
}

3. Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit from a single superclass.

Example:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


void meow() {
System.out.println("The cat meows.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog

Cat cat = new Cat();


cat.eat(); // Inherited from Animal
cat.meow(); // Defined in Cat
}
}

4. Multiple Inheritance (through Interfaces)

Java does not support multiple inheritance with classes to avoid complexity and simplify
design, but it does support multiple inheritance through interfaces. A class can implement
multiple interfaces.

Example:

interface Animal {
void eat();
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


public void eat() {
System.out.println("The dog eats food.");
}

public void play() {


System.out.println("The dog plays.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Implemented from Animal interface
dog.play(); // Implemented from Pet interface
}
}
Overriding:

• Definition: Providing a specific implementation of a method already defined in its


superclass.

Key Points:

1. Same Method Signature: The overridden method in the subclass must have the same
name, return type, and parameters as the method in the superclass.
2. Annotations: The @Override annotation is used to indicate that a method is
intended to override a method in the superclass. This helps catch errors at compile
time.
3. Access Modifiers: The access level of the overriding method cannot be more
restrictive than that of the overridden method.
4. Runtime Polymorphism: Overriding allows for runtime polymorphism, where the
method that gets called is determined at runtime based on the object's actual type

Example: Method Overriding

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

class Dog extends Animal {


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

public class TestOverriding {


public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}

Rules for Method Overriding

1. Same Method Signature: The method in the child class must have the same
signature as the method in the parent class.
2. Covariant Return Type: The return type of the overriding method can be a subtype
of the return type of the overridden method.
3. Access Level: The overriding method cannot have a more restrictive access level than
the overridden method.
4. Checked Exceptions: The overriding method cannot throw new or broader checked
exceptions than those declared by the overridden method.

Example with Covariant Return Type:

class Animal {
Animal getInstance() {
return new Animal();
}
}

class Dog extends Animal {


@Override
Dog getInstance() {
return new Dog();
}
}

Runtime Polymorphism

Method overriding is used to achieve runtime polymorphism. The overridden method is


called based on the actual object type at runtime, not the reference type.

Example:

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

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal;

myAnimal = new Animal();


myAnimal.sound(); // Output: Animal makes a sound

myAnimal = new Dog();


myAnimal.sound(); // Output: Dog barks

myAnimal = new Cat();


myAnimal.sound(); // Output: Cat meows
}
}

In this example, the sound method is overridden in both Dog and Cat classes. The method
that gets called depends on the actual object type assigned to myAnimal at runtime.

Interfaces:

• Definition: An interface is a reference type in Java that can contain only constants,
method signatures, default methods, static methods, and nested types.

Key Points:

1. Abstract Methods: An interface can declare abstract methods, which must be


implemented by any class that implements the interface.
2. Multiple Inheritance: A class can implement multiple interfaces, allowing for
multiple inheritance in Java.
3. Default Methods: Java 8 introduced default methods, which allow interfaces to
provide default implementations for methods.
4. Static Methods: Interfaces can also include static methods with concrete
implementations.
5. Constant Fields: Fields in interfaces are implicitly public, static, and final.

Defining an Interface

An interface is defined using the interface keyword.

Example:

interface Animal {
void sound();
void eat();
}
Implementing an Interface

A class implements an interface using the implements keyword and must provide concrete
implementations for all abstract methods declared in the interface.

Example:

class Dog implements Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}

@Override
public void eat() {
System.out.println("Dog eats");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
dog.eat(); // Output: Dog eats
}
}

Multiple Inheritance with Interfaces

A class can implement multiple interfaces, thereby achieving multiple inheritance.

Example:

interface Animal {
void sound();
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


@Override
public void sound() {
System.out.println("Dog barks");
}

@Override
public void play() {
System.out.println("Dog plays");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
dog.play(); // Output: Dog plays
}
}

Default Methods

Java 8 introduced default methods in interfaces, which allow providing a default


implementation for methods. This helps in maintaining backward compatibility when
interfaces are updated.

Example:

interface Animal {
void sound();

default void sleep() {


System.out.println("This animal sleeps");
}
}

class Dog implements Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
dog.sleep(); // Output: This animal sleeps
}
}

Static Methods

Interfaces can also contain static methods with implementations.

Example:

interface Animal {
void sound();

static void info() {


System.out.println("Animals can have various
sounds.");
}
}

class Dog implements Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
Animal.info(); // Output: Animals can have various
sounds.
}
}

Packages:

• Definition: A namespace for organizing classes and interfaces in a logical manner.

Key Points:

1. Namespace Management: Packages help manage the namespace by grouping related


classes and interfaces.
2. Access Control: Packages help protect classes and interfaces from being accessed by
classes outside the package.
3. Modularity: Packages make the code more modular and easier to maintain.
4. Reusability: Packages allow for code reusability by grouping related functionality.
Defining a Package

A package is defined using the package keyword at the top of the Java source file.

Example:

// File: com/example/Animal.java
package com.example;

public class Animal {


public void sound() {
System.out.println("Animal makes a sound");
}
}

Using a Package

To use a class or interface from a package, you need to import it using the import keyword.

Example:

// File: Main.java
import com.example.Animal;

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();
}
}

Types of Packages

1. Built-in Packages: Java provides a rich set of built-in packages, such as


java.lang, java.util, java.io, etc.
2. User-defined Packages: You can create your own packages to organize your classes
and interfaces.

Creating a Package

To create a package, follow these steps:

1. Create a directory structure that matches the package name.


2. Place the Java source files in the appropriate directory.
3. Use the package statement to specify the package name.

Example:

// Directory structure: com/example/


package com.example;

public class Dog {


public void bark() {
System.out.println("Dog barks");
}
}

// Directory structure: com/example/


package com.example;

public class Cat {


public void meow() {
System.out.println("Cat meows");
}
}

Importing Packages

You can import classes and interfaces from other packages using the import statement.

Example:

import com.example.Dog;
import com.example.Cat;

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();

Cat cat = new Cat();


cat.meow();
}
}

You can also use the wildcard * to import all classes and interfaces from a package.
Example:

import com.example.*;

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();

Cat cat = new Cat();


cat.meow();
}
}

Access Modifiers and Packages

Access modifiers control the accessibility of classes, interfaces, and their members. The four
access levels are:

1. Default (Package-Private): Accessible only within the same package.


2. Public: Accessible from any other class.
3. Protected: Accessible within the same package and by subclasses.
4. Private: Accessible only within the same class.

Example:

// File: com/example/Animal.java
package com.example;

public class Animal {


void defaultMethod() {
System.out.println("Default method");
}

public void publicMethod() {


System.out.println("Public method");
}

protected void protectedMethod() {


System.out.println("Protected method");
}

private void privateMethod() {


System.out.println("Private method");
}
}

// File: com/example/Main.java
package com.example;

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.defaultMethod(); // Accessible
animal.publicMethod(); // Accessible
animal.protectedMethod(); // Accessible
// animal.privateMethod(); // Not accessible
}
}

I/O Streams and Collections

I/O Streams in Java

I/O (Input/Output) Streams in Java are used to read from and write to data sources such as
files, network connections, or other external systems. The java.io package provides a
wide range of classes for handling input and output.

Key Concepts:

1. Stream: A sequence of data. Input streams are used to read data, and output streams
are used to write data.
2. Byte Streams: Handle raw binary data. Classes include InputStream and
OutputStream.
3. Character Streams: Handle character data (text). Classes include Reader and
Writer.

Byte Streams

Byte streams are used for reading and writing binary data. The main classes are
InputStream and OutputStream.

Example (FileInputStream and FileOutputStream):

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream in = new
FileInputStream("input.txt");
FileOutputStream out = new
FileOutputStream("output.txt")) {
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Character Streams

Character streams are used for reading and writing text data. The main classes are Reader
and Writer.

Example (FileReader and FileWriter):

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample {


public static void main(String[] args) {
try (FileReader in = new FileReader("input.txt");
FileWriter out = new FileWriter("output.txt")) {
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Buffered Streams

Buffered streams use an internal buffer to reduce the number of I/O operations, improving
performance. Classes include BufferedInputStream, BufferedOutputStream,
BufferedReader, and BufferedWriter.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedStreamExample {


public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new
FileReader("input.txt"));
BufferedWriter out = new BufferedWriter(new
FileWriter("output.txt"))) {
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Collections:

The java.util package provides the Collections Framework, which includes a set of
interfaces and classes to handle groups of objects in a standard way.

Key Interfaces:

1. Collection: The root interface for the Collections Framework.


2. List: An ordered collection (sequence) that allows duplicates. Examples include
ArrayList and LinkedList.
3. Set: A collection that does not allow duplicates. Examples include HashSet and
TreeSet.
4. Map: A collection of key-value pairs. Examples include HashMap and TreeMap.
List Interface

A List is an ordered collection that allows duplicate elements.

Example (ArrayList):

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

public class ListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

for (String fruit : list) {


System.out.println(fruit);
}
}
}

Set Interface

A Set is a collection that does not allow duplicate elements.

Example (HashSet):

import java.util.HashSet;
import java.util.Set;

public class SetExample {


public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate element

for (String fruit : set) {


System.out.println(fruit);
}
}
}
Map Interface

A Map is a collection that maps keys to values, with no duplicate keys allowed.

Example (HashMap):

import java.util.HashMap;
import java.util.Map;

public class MapExample {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

for (Map.Entry<String, Integer> entry :


map.entrySet()) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}

Exception Handling and Multithreaded Programming


Exception Handling:

Exception handling in Java is a mechanism to handle runtime errors, ensuring the normal
flow of the application. Java provides a robust and flexible exception handling framework
through its try, catch, finally, throw, and throws keywords.

Key Concepts:

1. Exception: An unwanted or unexpected event that disrupts the normal flow of a


program.
2. Checked Exceptions: Exceptions that are checked at compile-time.
3. Unchecked Exceptions: Exceptions that occur during runtime.
4. Error: A serious problem that a reasonable application should not try to catch.
Exception Hierarchy

Java exceptions are represented by the Throwable class, which has two main subclasses:
Error and Exception.

• Error: Represents serious issues that a typical application should not catch. Examples
include OutOfMemoryError, StackOverflowError.
• Exception: Represents conditions that a typical application might want to catch.
There are two main types:
o Checked Exceptions: Must be either caught or declared in the method
signature. Examples include IOException, SQLException.
o Unchecked Exceptions (RuntimeExceptions): Do not need to be declared or
caught. Examples include NullPointerException,
ArithmeticException.

Basic Syntax for Exception Handling

1. Try-Catch Block

A try block is used to wrap code that might throw an exception, and a catch block is used
to handle the exception.

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

Example:

public class ExceptionExample {


public static void main(String[] args) {
try {
int data = 10 / 0; // This will throw
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: "
+ e.getMessage());
}
}
}
2. Multiple Catch Blocks

You can catch multiple exceptions by using multiple catch blocks.

try {
// Code that might throw multiple exceptions
} catch (IOException e) {
// Handle IOException
} catch (SQLException e) {
// Handle SQLException
}

Example:

import java.io.*;

public class MultipleCatchExample {


public static void main(String[] args) {
try {
FileInputStream file = new
FileInputStream("test.txt");
int data = 10 / 0;
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught:
" + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: "
+ e.getMessage());
}
}
}

3. Finally Block

A finally block contains code that is always executed, regardless of whether an exception
is thrown or not. It's typically used for cleanup activities like closing resources.

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always be executed
}
Example:

import java.io.*;

public class FinallyExample {


public static void main(String[] args) {
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught:
" + e.getMessage());
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
System.out.println("IOException caught: " +
e.getMessage());
}
}
}
}

4. Throw Keyword

The throw keyword is used to explicitly throw an exception.

throw new ExceptionType("Error message");

Example:

public class ThrowExample {


public static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to
vote");
} else {
System.out.println("Eligible to vote");
}
}

public static void main(String[] args) {


validateAge(16);
}
}

5. Throws Keyword

The throws keyword is used in method signatures to declare that a method might throw one
or more exceptions.

void methodName() throws ExceptionType1, ExceptionType2 {


// Method code
}

Example:

import java.io.*;

public class ThrowsExample {


public static void readFile() throws IOException {
FileInputStream file = new
FileInputStream("test.txt");
file.close();
}

public static void main(String[] args) {


try {
readFile();
} catch (IOException e) {
System.out.println("IOException caught: " +
e.getMessage());
}
}
}

Custom Exceptions

You can create your own exception classes by extending the Exception class or
RuntimeException class.

Example:

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void validateAge(int age) throws
CustomException {
if (age < 18) {
throw new CustomException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}

public static void main(String[] args) {


try {
validateAge(16);
} catch (CustomException e) {
System.out.println("CustomException caught: " +
e.getMessage());
}
}
}

Multithreaded Programming:

Multithreading in Java allows concurrent execution of two or more threads to maximize the
utilization of CPU. Each thread runs in parallel to perform its task independently, enabling
more efficient execution of complex and time-consuming tasks.

Key Concepts:

1. Thread: A lightweight process. Multiple threads share the same process memory
space.
2. Multithreading: A process of executing multiple threads simultaneously.
3. Concurrency: The ability to run multiple threads or tasks in parallel.
4. Synchronization: A mechanism to control the access of multiple threads to shared
resources.

Creating Threads

There are two primary ways to create a thread in Java:

1. Extending the Thread Class


2. Implementing the Runnable Interface
1. Extending the Thread Class

To create a thread by extending the Thread class, you need to override the run method and
create an instance of the class.

Example:

class MyThread extends Thread {


@Override
public void run() {
System.out.println("Thread is running...");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}

2. Implementing the Runnable Interface

To create a thread by implementing the Runnable interface, you need to implement the
run method and pass an instance of the class to a Thread object.

Example:

class MyRunnable implements Runnable {


@Override
public void run() {
System.out.println("Thread is running...");
}
}

public class RunnableExample {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the thread
}
}
Thread Lifecycle

A thread in Java goes through various stages during its lifecycle:

1. New: A thread that has been created but not yet started.
2. Runnable: A thread that is ready to run and waiting for CPU time.
3. Running: A thread that is currently executing.
4. Blocked/Waiting: A thread that is blocked or waiting for some condition or resource.
5. Terminated: A thread that has completed its execution or has been terminated.

Thread Methods

1. start(): Starts the thread.


2. run(): Contains the code that defines the thread's behavior.
3. sleep(long millis): Causes the thread to sleep for a specified duration.
4. join(): Waits for the thread to die.
5. yield(): Causes the currently executing thread to pause and allow other threads to
execute.
6. interrupt(): Interrupts the thread.
Example of sleep and join:

class MyRunnable implements Runnable {


@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000); // Sleep for 1 second
System.out.println("Thread is running: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadMethodsExample {


public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();

try {
thread.join(); // Wait for the thread to finish
System.out.println("Thread has finished
execution");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Synchronization

Synchronization is used to control access to shared resources by multiple threads to prevent


data inconsistency and ensure thread safety.

Synchronized Method

A method can be declared synchronized to make it thread-safe.

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

class MyRunnable implements Runnable {


private Counter counter;

public MyRunnable(Counter counter) {


this.counter = counter;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

public class SynchronizedMethodExample {


public static void main(String[] args) throws
InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(new MyRunnable(counter));
Thread t2 = new Thread(new MyRunnable(counter));

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Final count: " +


counter.getCount());
}
}
Synchronized Block

A synchronized block can be used to synchronize a specific block of code instead of the
whole method.

class Counter {
private int count = 0;

public void increment() {


synchronized (this) {
count++;
}
}

public int getCount() {


return count;
}
}

Inter-Thread Communication

Inter-thread communication in Java can be achieved using the wait(), notify(), and
notifyAll() methods, which are part of the Object class.

Example:

class SharedResource {
private int count = 0;
private boolean available = false;

public synchronized void produce() throws


InterruptedException {
while (available) {
wait();
}
count++;
System.out.println("Produced: " + count);
available = true;
notify();
}

public synchronized void consume() throws


InterruptedException {
while (!available) {
wait();
}
System.out.println("Consumed: " + count);
available = false;
notify();
}
}

class Producer implements Runnable {


private SharedResource resource;

public Producer(SharedResource resource) {


this.resource = resource;
}

@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
resource.produce();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class Consumer implements Runnable {


private SharedResource resource;

public Consumer(SharedResource resource) {


this.resource = resource;
}

@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
resource.consume();
Thread.sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class InterThreadCommunicationExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(new Producer(resource));
Thread consumer = new Thread(new Consumer(resource));

producer.start();
consumer.start();
}
}

Applets, AWT, and Event Handling


Applets:
Java applets were small Java programs that could be embedded in web pages and run within a
web browser. They provided interactive features to enhance the functionality of web pages.
However, applets have largely fallen out of favor due to security concerns and limitations
compared to other web technologies like HTML5, CSS3, JavaScript, and more recently,
WebAssembly. Despite this, understanding Java applets can provide insights into the history
and evolution of web technologies.

Key Concepts:

1. Applet Lifecycle: Similar to applications, applets have distinct stages: initialization,


start, stop, and destroy.
2. Applet Tags: HTML tags (<applet> and <object>) were used to embed and run
applets in web pages.
3. Applet Security: Due to security concerns, modern browsers have deprecated support
for Java applets.
4. Alternatives: Web technologies like HTML5, JavaScript, and WebAssembly have
largely replaced Java applets for web-based applications.

Creating a Simple Applet

To create a basic Java applet, you typically extend the java.applet.Applet class and
override methods such as init(), start(), stop(), and destroy(). Here’s an
example of a simple applet:

import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
@Override
public void init() {
// Initialization code
}

@Override
public void start() {
// Start code (e.g., start animation or timer)
}

@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}

@Override
public void stop() {
// Stop code (e.g., stop animation or timer)
}

@Override
public void destroy() {
// Cleanup code (e.g., release resources)
}
}

Embedding Applets in HTML

To embed a Java applet in an HTML page, you use the <applet> or <object> tag.
Here’s an example using the <applet> tag:

<!DOCTYPE html>
<html>
<head>
<title>Java Applet Example</title>
</head>
<body>
<applet code="SimpleApplet.class" width="300"
height="200">
Your browser does not support Java applets.
</applet>
</body>
</html>

Applet Lifecycle Methods

• init(): Initializes the applet. Called once when the applet is first loaded.
• start(): Starts the applet. Called each time the applet is revisited or resumed.
• paint(Graphics g): Called whenever the applet needs to redraw itself. Typically
overridden to draw graphics or text.
• stop(): Stops the applet. Called when the applet is no longer visible or needs to stop
processing.
• destroy(): Cleans up resources used by the applet. Called when the applet is about to
be unloaded.

Applet Security

Java applets ran with certain security restrictions imposed by the Java Runtime Environment
(JRE). These restrictions included limitations on accessing the local file system, network
connections, and other system resources. Despite these restrictions, vulnerabilities were
discovered over time, leading to security concerns and the eventual deprecation of Java
applets in modern browsers.

Deprecated Status

As of Java 9, the java.applet package and the Applet API have been deprecated. Modern
browsers have also dropped support for Java applets due to security issues and the availability
of more secure and versatile web technologies.

Alternatives

Instead of Java applets, web developers now use technologies such as:

• HTML5: For multimedia and interactive content.


• JavaScript: For client-side scripting and dynamic web content.
• CSS3: For styling and animations.
• WebAssembly: For running high-performance applications in browsers.

AWT (Abstract Window Toolkit):

AWT (Abstract Window Toolkit) is a set of classes and methods provided by Java for
creating and managing graphical user interface (GUI) elements such as windows, buttons,
menus, and dialogs. AWT is part of the Java Foundation Classes (JFC) and is the original
GUI framework for Java.
Key Concepts:

1. Components: GUI elements such as buttons, labels, text fields, etc.


2. Containers: Components that can contain other components, such as windows
(Frame), panels (Panel), etc.
3. Layout Managers: Control the positioning and sizing of components within
containers.
4. Events: User actions (clicks, keystrokes) that trigger actions in the GUI.

AWT Components

AWT provides a set of GUI components that can be used to create user interfaces. Some of
the commonly used components include:

• Window: Represents a top-level window with a title bar and border. Example:
Frame.
• Panel: A container for holding other components. Example: Panel.
• Button: A clickable button. Example: Button.
• Label: Displays a text or image. Example: Label.
• TextField: Allows users to input single-line text. Example: TextField.
• TextArea: Allows users to input multiple lines of text. Example: TextArea.
• Checkbox: A checkable option. Example: Checkbox.
• Choice: A drop-down list of choices. Example: Choice.

AWT Containers

Containers are components that can contain other components. Some common containers in
AWT include:

• Frame: A top-level window with a title bar and border.


• Panel: A generic container that can hold other components.
• Applet: A container specifically designed for running within a web browser.

AWT Layout Managers

Layout managers control how components are arranged within containers. AWT provides
several layout managers, including:

• FlowLayout: Arranges components in a row, wrapping to the next line if necessary.


• BorderLayout: Divides the container into five regions (North, South, East, West,
Center).
• GridLayout: Arranges components in a grid of rows and columns.
• GridBagLayout: Provides more flexible grid arrangement with adjustable cell sizes.
Example of Using AWT Components

Here's a simple example demonstrating how to create a basic GUI using AWT:

import java.awt.*;

public class AwtExample {


public static void main(String[] args) {
// Create a frame (window)
Frame frame = new Frame("AWT Example");

// Create components
Label label = new Label("Enter your name:");
TextField textField = new TextField(20);
Button button = new Button("Submit");

// Add components to the frame


frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(textField);
frame.add(button);

// Set frame properties


frame.setSize(300, 150);
frame.setVisible(true);
}
}

AWT Event Handling

AWT uses the event-delegation model for event handling. Events are generated by user
actions (e.g., mouse clicks, keystrokes) and are handled by event listeners registered with
components. Some common event listener interfaces in AWT include ActionListener,
MouseListener, KeyListener, etc.

Example of Event Handling:

import java.awt.*;
import java.awt.event.*;

public class ButtonExample {


public static void main(String[] args) {
Frame frame = new Frame("Button Example");
Button button = new Button("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setSize(200, 100);
frame.setVisible(true);
}
}

AWT vs. Swing

Swing, introduced later in Java's development, is built on top of AWT but provides a more
powerful and flexible set of components and features. Swing components are lightweight and
offer a more consistent look and feel across different platforms compared to AWT, which
uses native platform components.

Event Handling:

Key Concepts in Event Handling

1. Event: An occurrence triggered by user interaction or system operation. Examples


include mouse clicks, keystrokes, window resizing, etc.
2. Event Source: The component or object that generates an event. For example, a
button (JButton) is an event source when clicked.
3. Event Listener: An object that registers to receive and handle events from a specific
event source. It implements a corresponding listener interface and provides methods
to handle events.

Event Handling Mechanism

Steps Involved in Event Handling:

1. Event Source Registration: Components register themselves with event listeners.


This is typically done using methods like addActionListener() for buttons or
addMouseListener() for mouse events.
2. Event Listener Implementation: Event listeners implement interfaces corresponding
to the type of events they want to handle. Common listener interfaces include
ActionListener, MouseListener, KeyListener, etc.
3. Event Dispatching: When an event occurs (e.g., a button click), the event source
notifies all registered listeners by calling their event handling methods.
Example of Event Handling

Here’s a basic example of handling a button click event using Java Swing:

import javax.swing.*;
import java.awt.event.*;

public class EventHandlingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
JButton button = new JButton("Click Me");

// Register ActionListener to handle button click


events
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button
clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example:

• JButton is the event source.


• addActionListener() registers an ActionListener (an anonymous class
here) to handle button click events.
• When the button is clicked, actionPerformed() method of the
ActionListener is called, showing a message dialog.

Common Event Listener Interfaces

1. ActionListener: Handles action events, like button clicks.

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle button click
}
});
2. MouseListener: Handles mouse events, like clicks, enters, exits.

component.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
// Handle mouse click
}
// Other mouse event methods
});

3. KeyListener: Handles keyboard events, like key presses.

component.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// Handle key press
}
// Other key event methods
});

Event Handling in JavaFX

In JavaFX, which is the successor to Swing for GUI applications, event handling is similar
but uses its own set of classes and interfaces. JavaFX provides more modern and flexible
ways to handle events, leveraging features like event filters, event handlers, and properties
binding.
IMPORTANT MCQS
1) What is the primary purpose of the Java Virtual Machine (JVM)?

• a) To compile Java code


• b) To interpret bytecode
• c) To manage memory
• d) To provide an interface for operating system services

2) Which of the following is not a Java primitive data type?

• a) int
• b) float
• c) double
• d) String

3) Which method is the entry point for any Java program?

• a) start()
• b) main()
• c) init()
• d) run()

4) What does the 'static' keyword mean when applied to a method?

• a) The method belongs to an instance of the class.


• b) The method cannot be overridden.
• c) The method belongs to the class, not any particular object.
• d) The method is abstract.

5) What is method overloading in Java?

• a) Defining multiple methods with the same name but different parameters.
• b) Defining a method in a subclass that has the same signature as a method in the
superclass.
• c) Changing the return type of a method.
• d) Using the same method name in different classes.

6) In Java, which keyword is used to inherit a class?

• a) implements
• b) extends
• c) inherits
• d) super

7) Which of the following concepts allows you to define methods in an interface without
implementation?

• a) Polymorphism
• b) Abstraction
• c) Encapsulation
• d) Inheritance

8) Which interface must be implemented by a class to enable it to be run as a thread?

• a) Runnable
• b) Threadable
• c) Executable
• d) ActionListener

9) What is the default value of a boolean variable in Java?

• a) true
• b) false
• c) null
• d) 0

10) Which of the following is true about the finalize() method?

• a) It is called automatically when an object is created.


• b) It is called automatically before an object is garbage collected.
• c) It must be manually called to release resources.
• d) It is used to initialize an object.

11) What is the use of the 'this' keyword in Java?

• a) To refer to the current class


• b) To refer to the superclass
• c) To refer to the current object
• d) To refer to a local variable

12) Which collection class allows you to access its elements by associating a key with an
element's value, and allows you to retrieve elements in the order in which they were
inserted?

• a) HashSet
• b) TreeSet
• c) LinkedHashMap
• d) TreeMap

13) What is the purpose of the 'final' keyword in a method declaration?

• a) The method cannot be overloaded.


• b) The method cannot be overridden.
• c) The method cannot be called.
• d) The method cannot be inherited.

14) Which of these statements is true about the 'File' class in Java?
• a) It is an abstract class.
• b) It can be used to create files and directories.
• c) It can read from and write to files.
• d) It is part of the java.util package.

15) Which exception is thrown when a program attempts to divide by zero?

• a) NullPointerException
• b) ArithmeticException
• c) ArrayIndexOutOfBoundsException
• d) NumberFormatException

16) Which keyword is used to declare a class that cannot be inherited?

• a) final
• b) static
• c) abstract
• d) sealed

17) Which of the following methods is used to start a thread execution?

• a) run()
• b) start()
• c) init()
• d) execute()

18) In which package is the 'Scanner' class defined?

• a) java.io
• b) java.lang
• c) java.util
• d) java.net

19) Which method is used to read a line of text from the console in Java?

• a) readLine()
• b) read()
• c) nextLine()
• d) getLine()

20) What is the return type of the 'hashCode()' method in Java?

• a) Object
• b) int
• c) long
• d) boolean

21) What is the output of the following code?

String str = "Hello";


str.concat(" World");
System.out.println(str);

• a) Hello World
• b) Hello
• c) Hello WorldHello
• d) World

22) Which of the following can be used to create an abstract class in Java?

• a) The abstract keyword


• b) The interface keyword
• c) The extends keyword
• d) The implements keyword

23) Which of the following is not a valid Java keyword?

• a) transient
• b) volatile
• c) static
• d) unsigned

24) What is the output of the following code?

int a = 10;
int b = 20;
int c = 30;
a = b = c;
System.out.println(a);

• a) 10
• b) 20
• c) 30
• d) Compilation Error

25) Which method is used to wait for a thread to die in Java?

• a) sleep()
• b) wait()
• c) join()
• d) yield()

26) What is the correct syntax for creating a new instance of the File class?

• a) File file = new File("filename");


• b) File file = File("filename");
• c) File file = File.create("filename");
• d) File file = new File.create("filename");

27) Which of the following is true about the 'ArrayList' class in Java?
• a) It is synchronized.
• b) It can grow dynamically.
• c) It is part of java.lang package.
• d) It is an abstract class.

28) Which of the following is not a method of the 'Thread' class?

• a) sleep()
• b) wait()
• c) run()
• d) yield()

29) Which of these data types can be used for a switch statement expression in Java?

• a) int
• b) float
• c) boolean
• d) long

30) Which of these statements about the 'Vector' class is true?

• a) Vector is synchronized.
• b) Vector cannot grow dynamically.
• c) Vector is part of java.lang package.
• d) Vector does not allow duplicate elements.
KEY
1) b) To interpret bytecode
2) d) String
3) b) main()
4) c) The method belongs to the class, not any particular object.
5) a) Defining multiple methods with the same name but different parameters.
6) b) extends
7) b) Abstraction
8) a) Runnable
9) b) false
10) b) It is called automatically before an object is garbage collected.
11) c) To refer to the current object
12) c) LinkedHashMap
13) b) The method cannot be overridden.
14) b) It can be used to create files and directories.
15) b) ArithmeticException
16) a) final
17) b) start()
18) c) java.util
19) c) nextLine()
20) b) int
21) b) Hello
22) a) The abstract keyword
23) d) unsigned
24) c) 30
25) c) join()
26) a) File file = new File("filename");
27) b) It can grow dynamically.
28) b) wait()
29) a) int
30) a) Vector is synchronized.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy