JAVA Sem-5
JAVA Sem-5
1 Introducing 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.
● 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.
● 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.
java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
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};
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.");
}
}
}
1.9 Accepting Input from Console (Using BufferedReader and Scanner Class)
Using BufferedReader:
java
Copy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
Using Scanner:
java
Copy code
import java.util.Scanner;
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.
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.");
}
}
Access specifiers in Java control the visibility of classes, fields, methods, and constructors.
Example:
java
Copy code
public class AccessExample {
public int publicField;
protected int protectedField;
int defaultField;
private int privateField;
}
java
Copy code
public class Student {
String name;
● 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;
}
}
● 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;
}
Java’s garbage collector automatically removes objects from memory when they are no longer
in use, freeing up memory and preventing memory leaks.
Java provides many predefined classes in its standard library, such as String, Math, and
ArrayList.
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;
}
}
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;
// In another file
import com.example.MyClass;
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
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.
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...");
}
}
Example:
java
Copy code
class Animal {
String color = "white";
Animal() {
System.out.println("Animal created");
}
}
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
}
}
● 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");
}
}
Example:
java
Copy code
final class Car {
final void drive() {
System.out.println("Driving...");
}
}
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
}
}
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).
Example:
java
Copy code
interface Drawable {
void draw();
}
java
Copy code
interface Animal {
void sound();
}
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.
● 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).
java
Copy code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
● 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.
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);
}
}
}
java
Copy code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
● 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
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();
}
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();
}
● 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();
}
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();
}
This overview of exception and file handling provides the basics for managing errors and
working with data files in Java.
● 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.
● 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.
● 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);
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);
● 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.
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.");
}
});
● 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.
java
Copy code
JButton button = new JButton("Click Me");
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
});
● 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.
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.