0% found this document useful (0 votes)
5 views23 pages

JAVA Sem-5

Java is a high-level, object-oriented programming language known for its platform independence and security features, created by Sun Microsystems in the mid-1990s. Key features include automatic memory management, multithreading, and a robust environment for executing applications through the Java Virtual Machine (JVM). The document also covers Java's syntax, data types, object-oriented principles, exception handling, and the use of interfaces and inheritance.

Uploaded by

haythere0070
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)
5 views23 pages

JAVA Sem-5

Java is a high-level, object-oriented programming language known for its platform independence and security features, created by Sun Microsystems in the mid-1990s. Key features include automatic memory management, multithreading, and a robust environment for executing applications through the Java Virtual Machine (JVM). The document also covers Java's syntax, data types, object-oriented principles, exception handling, and the use of interfaces and inheritance.

Uploaded by

haythere0070
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/ 23

1.

1 Introducing Java

Java is a high-level, object-oriented programming language created by Sun Microsystems (now


part of Oracle) in the mid-1990s. It is known for its platform independence, made possible by the
Java Virtual Machine (JVM), which allows Java programs to run on various devices without
modification. Java follows the principle of "write once, run anywhere" (WORA), making it
versatile for multiple platforms, such as Windows, macOS, and Linux.

1.2 A Short History of Java

Java was initially developed by James Gosling and his team at Sun Microsystems in 1991.
Originally called "Oak," it was later renamed Java. The language gained popularity due to its
simplicity, portability, and security features. In 1995, Java was released to the public, and by
2009, Oracle Corporation acquired Sun Microsystems, gaining control over Java.

1.3 Features of Java

Some key features of Java include:

● Platform Independence: Java code is compiled into bytecode, which can run on any
system with a JVM.
● Object-Oriented: Java uses objects and classes, enabling encapsulation, inheritance,
and polymorphism.
● Robust and Secure: Java has strong memory management, error-handling capabilities,
and built-in security features.
● Multithreading: Java supports concurrent execution, allowing the development of
efficient, high-performance applications.
● Automatic Memory Management: Java has garbage collection to manage memory
automatically.

1.4 Java Environment – Compiler, Interpreter, JVM

● Compiler: Java source code (.java files) is compiled by the Java compiler into bytecode
(.class files).
● Interpreter: The JVM interprets the bytecode into machine code, enabling it to run on
any platform with a compatible JVM.
● JVM (Java Virtual Machine): The JVM provides the runtime environment where Java
applications execute. It is platform-specific but offers uniformity in executing Java
bytecode across platforms.

1.5 Simple Java Program

Here’s a basic "Hello, World!" program in Java:

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

Explanation:

● public class HelloWorld declares a public class named HelloWorld.


● public static void main(String[] args) is the main method where execution
begins.
● System.out.println("Hello, World!"); prints "Hello, World!" to the console.

1.6 Types of Comments

Java has three types of comments:

Single-line comments: Start with // and are used for brief explanations.
java
Copy code
// This is a single-line comment

Multi-line comments: Start with /* and end with */, used for longer explanations.
java
Copy code
/* This is a
multi-line comment */

Documentation comments: Start with /** and are used to generate documentation.
java
Copy code
/**
* This is a documentation comment.
* It describes the code for Javadoc generation.
*/


1.7 Declaring Single and Multi-dimensional Arrays
Single-dimensional array: A list of elements.
java
Copy code
int[] singleArray = {1, 2, 3, 4, 5};

Multi-dimensional array: An array of arrays (e.g., 2D array for matrices).


java
Copy code
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6}
};

1.8 Accepting Input Using Command-Line Arguments

Java can accept input from the command line. Command-line arguments are passed to the
main method as a String array.

Example:

java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Argument received: " + args[0]);
} else {
System.out.println("No arguments received.");
}
}
}

To run: java CommandLineExample Hello

1.9 Accepting Input from Console (Using BufferedReader and Scanner Class)
Using BufferedReader:
java
Copy code
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BufferedReaderExample {


public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Hello, " + name + "!");
}
}

Using Scanner:
java
Copy code
import java.util.Scanner;

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}

Both BufferedReader and Scanner allow the user to input data during program execution,
but Scanner is generally more convenient for simple inputs and primitive data types.

2.1 Defining a Class

In Java, a class is a blueprint for creating objects. It defines the properties (fields) and behaviors
(methods) that the objects created from the class can have.

java
Copy code
public class Person {
// Fields (attributes)
String name;
int age;

// Method (behavior)
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am "
+ age + " years old.");
}
}

2.2 Access Specifiers (public, protected, private, default)

Access specifiers in Java control the visibility of classes, fields, methods, and constructors.

● public: Accessible from any other class.


● protected: Accessible within the same package and subclasses.
● private: Accessible only within the same class.
● default: If no access specifier is specified, it is accessible within the same package
(package-private).

Example:

java
Copy code
public class AccessExample {
public int publicField;
protected int protectedField;
int defaultField;
private int privateField;
}

2.3 Array of Objects

You can create an array to store multiple objects of a class.

java
Copy code
public class Student {
String name;

public Student(String name) {


this.name = name;
}

public static void main(String[] args) {


Student[] students = new Student[3];
students[0] = new Student("Alice");
students[1] = new Student("Bob");
students[2] = new Student("Charlie");

for (Student student : students) {


System.out.println(student.name);
}
}
}

2.4 Constructors, Overloading Constructors, and the this Keyword

● A constructor is a special method that initializes an object. It has the same name as the
class and no return type.
● Constructor Overloading allows you to have multiple constructors with different
parameters.
● The this keyword refers to the current instance of the class.

java
Copy code
public class Car {
String model;
int year;

// Default constructor
public Car() {
this("Unknown", 0);
}

// Parameterized constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}

2.5 static Block, static Fields, and static Methods

● static block: Executed when the class is loaded, typically used for initializing static
fields.
● static fields: Shared among all instances of a class.
● static methods: Can be called without creating an instance of the class. They cannot
access instance (non-static) fields or methods.

java
Copy code
public class StaticExample {
static int count = 0;

static {
count = 5;
}

public static void displayCount() {


System.out.println("Count: " + count);
}
}

2.6 Concept of Garbage Collection

Java’s garbage collector automatically removes objects from memory when they are no longer
in use, freeing up memory and preventing memory leaks.

2.7 Predefined Classes

Java provides many predefined classes in its standard library, such as String, Math, and
ArrayList.

2.7.1 Object Class Methods (equals(), toString(), hashCode(), getClass())

The Object class is the parent of all classes in Java. Its key methods include:
● equals(): Checks if two objects are equal based on specific criteria.
● toString(): Returns a string representation of the object.
● hashCode(): Returns a hash code for the object.
● getClass(): Returns the runtime class of the object.

java
Copy code
public class Product {
String name;
double price;

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Product product = (Product) obj;
return Double.compare(product.price, price) == 0 &&
name.equals(product.name);
}

@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}

@Override
public int hashCode() {
return name.hashCode() + (int) price;
}
}

2.8 Creating, Accessing, and Using Packages

A package is a way of grouping related classes in Java. You can create a package using the
package keyword and access classes within the package using the import statement.

java
Copy code
// File: com/example/MyClass.java
package com.example;

public class MyClass {


public void greet() {
System.out.println("Hello from MyClass!");
}
}

// In another file
import com.example.MyClass;

public class Test {


public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.greet();
}
}

2.9 Wrapper Classes

Wrapper classes provide a way to use primitive data types as objects. The main wrapper
classes are Integer, Double, Character, Boolean, etc. Wrapper classes are helpful in
collections and support useful methods.

Example:

java
Copy code
Integer num = Integer.valueOf(5); // Boxing
int n = num.intValue(); // Unboxing

3.1 Inheritance Basics (extends Keyword) and Types of Inheritance

Inheritance is a mechanism that allows a class (subclass) to inherit fields and methods from
another class (superclass), promoting code reuse and enabling hierarchical class relationships.

● extends keyword: Used by a subclass to inherit from a superclass.


● Types of Inheritance:
○ Single Inheritance: A class inherits from only one superclass.
○ Multilevel Inheritance: A class inherits from another class, which in turn inherits
from a third class.
○ Hierarchical Inheritance: Multiple classes inherit from a single superclass.

Java does not support Multiple Inheritance (a class inheriting from more than one class) to
avoid ambiguity, but it can be achieved using interfaces.

Example:

java
Copy code
class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}

3.2 Superclass, Subclass, and Use of super Keyword

● Superclass: The class being inherited from.


● Subclass: The class that inherits from the superclass.
● super keyword: Used to call the superclass’s constructor or to access its methods and
fields from the subclass.

Example:

java
Copy code
class Animal {
String color = "white";

Animal() {
System.out.println("Animal created");
}
}

class Dog extends Animal {


String color = "brown";

Dog() {
super(); // Calls the superclass constructor
System.out.println("Dog created");
}

void displayColor() {
System.out.println("Dog color: " + color);
System.out.println("Animal color: " + super.color); // Access
superclass field
}
}

3.3 Method Overriding and Runtime Polymorphism

● Method Overriding: A subclass can provide its own implementation of a method defined
in its superclass.
○ The method in the subclass must have the same name, return type, and
parameters as the method in the superclass.
● Runtime Polymorphism: Achieved through method overriding, allowing the JVM to
determine which method to invoke at runtime based on the object type.

Example:

java
Copy code
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Bark");
}
}
class Test {
public static void main(String[] args) {
Animal myDog = new Dog(); // Runtime polymorphism
myDog.sound(); // Outputs: Bark
}
}

3.4 Use of final Keyword Related to Method and Class

● final method: Prevents a method from being overridden in subclasses.


● final class: Prevents a class from being subclassed.

Example:

java
Copy code
final class Car {
final void drive() {
System.out.println("Driving...");
}
}

// class SportsCar extends Car {} // Error: Cannot inherit from final


Car

3.5 Use of Abstract Class and Abstract Methods

● Abstract Class: A class that cannot be instantiated and is meant to be subclassed.


Declared with the abstract keyword.
● Abstract Method: A method without a body that must be implemented in subclasses.
Also declared with the abstract keyword.

Example:

java
Copy code
abstract class Shape {
abstract void draw(); // Abstract method
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}

class Test {
public static void main(String[] args) {
Shape s = new Circle();
s.draw(); // Outputs: Drawing Circle
}
}

3.6 Defining and Implementing Interfaces

An interface is a reference type similar to a class that can contain only abstract methods and
constants by default (in modern Java, interfaces can also have default and static methods).

● Defining an interface: Use the interface keyword.


● Implementing an interface: A class implements an interface using the implements
keyword.

Example:

java
Copy code
interface Drawable {
void draw();
}

class Rectangle implements Drawable {


public void draw() {
System.out.println("Drawing Rectangle");
}
}

3.7 Runtime Polymorphism Using Interface

Runtime polymorphism can be achieved with interfaces. A reference variable of an interface


type can hold objects of any class that implements the interface, allowing flexibility in code.
Example:

java
Copy code
interface Animal {
void sound();
}

class Cat implements Animal {


public void sound() {
System.out.println("Meow");
}
}

class Dog implements Animal {


public void sound() {
System.out.println("Bark");
}
}

class Test {
public static void main(String[] args) {
Animal a;
a = new Cat();
a.sound(); // Outputs: Meow

a = new Dog();
a.sound(); // Outputs: Bark
}
}

In this example, a can refer to either a Cat or Dog object, and the appropriate sound() method
is called at runtime.

4.1 Exception Class, Checked and Unchecked Exceptions

● Exception Class: The Exception class in Java is the superclass of all exceptions,
which are events that disrupt the normal flow of a program.
● Checked Exceptions: Checked at compile-time and must be handled with a try-catch
block or declared with throws (e.g., IOException, SQLException).
● Unchecked Exceptions: Also known as runtime exceptions; they are not checked at
compile-time and do not need explicit handling (e.g., NullPointerException,
ArithmeticException).

Example of Checked Exception:

java
Copy code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedExample {


public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e);
}
}
}

4.2 Catching Exceptions, Multiple Catch Block, Nested try Block

● Catching Exceptions: Use a try-catch block to handle exceptions. The code that might
throw an exception is placed in the try block, and the handling code is placed in the
catch block.
● Multiple Catch Block: Multiple exceptions can be handled in different catch blocks.
● Nested try Block: A try block within another try block, allowing handling of different
exceptions at various levels.

Example of Multiple Catch Block:

java
Copy code
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[5] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds: " + e);
} catch (Exception e) {
System.out.println("General Exception: " + e);
}
}
}

4.3 Creating User-Defined Exception

You can create custom exceptions by extending the Exception class.

java
Copy code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomExceptionExample {


static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age not valid for
voting.");
}
}

public static void main(String[] args) {


try {
validate(16);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
4.4 String Class (Basic Methods), StringBuffer Class

● String Class: Immutable class for handling text in Java. Key methods include:
○ length(): Returns the length of the string.
○ charAt(int index): Returns the character at a specific index.
○ substring(int beginIndex, int endIndex): Returns a substring.
○ toUpperCase(), toLowerCase(): Converts the string to uppercase or
lowercase.

java
Copy code
String str = "Hello";
System.out.println(str.length()); // Outputs: 5
System.out.println(str.toUpperCase()); // Outputs: HELLO

● StringBuffer Class: Mutable class used for creating and manipulating strings when
modifications are needed. Key methods include append(), insert(), delete(), and
reverse().

java
Copy code
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Outputs: Hello World

4.5 Introduction to Files and Streams (FileInputStream, FileOutputStream,


DataInputStream, DataOutputStream)

● FileInputStream and FileOutputStream: Used for reading and writing


byte-oriented data, like images or binary files.

java
Copy code
// Writing to a file
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write("Hello World".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// Reading from a file
try (FileInputStream fis = new FileInputStream("output.txt")) {
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}

● DataInputStream and DataOutputStream: Used for reading and writing primitive


data types in a portable way.

java
Copy code
// Writing data
try (DataOutputStream dos = new DataOutputStream(new
FileOutputStream("data.bin"))) {
dos.writeInt(100);
dos.writeDouble(12.5);
} catch (IOException e) {
e.printStackTrace();
}

// Reading data
try (DataInputStream dis = new DataInputStream(new
FileInputStream("data.bin"))) {
int i = dis.readInt();
double d = dis.readDouble();
System.out.println("Int: " + i + ", Double: " + d);
} catch (IOException e) {
e.printStackTrace();
}

4.6 Reader-Writer: FileReader, FileWriter, BufferedReader, BufferedWriter

● FileReader and FileWriter: Used for reading and writing character data.

java
Copy code
// Writing characters to a file
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello World");
} catch (IOException e) {
e.printStackTrace();
}

// Reading characters from a file


try (FileReader fr = new FileReader("output.txt")) {
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}

● BufferedReader and BufferedWriter: Provide efficient reading and writing of text


data, as they buffer characters to optimize performance.

java
Copy code
// Writing using BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("buffered_output.txt"))) {
bw.write("Hello Buffered World");
} catch (IOException e) {
e.printStackTrace();
}

// Reading using BufferedReader


try (BufferedReader br = new BufferedReader(new
FileReader("buffered_output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

This overview of exception and file handling provides the basics for managing errors and
working with data files in Java.

5.1 What is Swing?

● Swing is a part of Java’s Standard Library (Java Foundation Classes, or JFC) for
building graphical user interface (GUI) applications. It provides a set of lightweight,
platform-independent components, such as buttons, labels, and text fields, that can be
used to build rich desktop applications.
● Swing components are more flexible and provide more features than the older AWT
components.

5.2 The MVC Architecture

● Swing uses the Model-View-Controller (MVC) architecture, which separates the data
(model), the user interface (view), and the control logic (controller). This makes it easier
to manage and update the UI.
○ Model: Holds the data of the application.
○ View: Responsible for the presentation of the data.
○ Controller: Manages user input and interactions, updating the model as needed.

5.3 Layout Manager and Layouts

● Layout Managers in Swing control the size, position, and arrangement of components
within a container. Some commonly used layout managers are:
○ FlowLayout: Places components in a row, centering them by default.
○ BorderLayout: Divides the container into five regions (North, South, East, West,
Center).
○ GridLayout: Organizes components in a grid of equally sized cells.
○ BoxLayout: Places components either vertically or horizontally.

Example of BorderLayout:

java
Copy code
JFrame frame = new JFrame("BorderLayout Example");
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);

5.4 Components – JLabel, JButton, JText, JTextArea, JCheckBox, JRadioButton, JList,


JComboBox

● JLabel: Displays a short string or image icon.


● JButton: A button that can trigger actions when clicked.
● JTextField: Allows single-line text input.
● JTextArea: Allows multi-line text input.
● JCheckBox: A checkable box representing a true/false value.
● JRadioButton: Allows selection of one option from a group.
● JList: A list of items from which the user can select.
● JComboBox: A dropdown menu for selecting items.

Example using JLabel and JButton:

java
Copy code
JFrame frame = new JFrame("JLabel and JButton Example");
JLabel label = new JLabel("Hello, Swing!");
JButton button = new JButton("Click Me");
button.addActionListener(e -> label.setText("Button Clicked!"));
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
frame.setSize(200, 100);
frame.setVisible(true);

5.5 Event Handling: Event Sources, Listeners – ActionListener, ItemListener

● Event Handling in Swing is based on the delegation event model. Components (like
buttons) generate events, and listeners (like ActionListener) handle them.
○ Event Sources: Components that generate events.
○ Listeners: Interfaces that contain methods to handle events, like
actionPerformed() for ActionListener.

Example using ActionListener:


java
Copy code
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});

5.6 Mouse and Keyboard Event Handling

● Mouse Events: Detected using MouseListener and MouseMotionListener for


interactions like clicks, movements, and drags.
● Keyboard Events: Detected using KeyListener for interactions like key presses and
releases.

Example of Mouse Event Handling:

java
Copy code
JButton button = new JButton("Click Me");
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked on button.");
}
});

5.7 Adapters – MouseAdapter, KeyAdapter

● Adapters: Abstract classes that implement listener interfaces. They allow handling
specific events without implementing all the methods in a listener interface.
○ MouseAdapter: Used to handle mouse events.
○ KeyAdapter: Used to handle keyboard events.

Example using MouseAdapter:

java
Copy code
JButton button = new JButton("Click Me");
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
});

5.8 Anonymous Inner Class

● An Anonymous Inner Class is an unnamed inner class that is defined and instantiated
in a single expression. It’s commonly used in event handling to implement listener
interfaces.

Example using Anonymous Inner Class:

java
Copy code
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

Swing enables Java applications to have GUI interfaces with sophisticated layouts and event
handling, making it essential for creating desktop applications.

You might also like