javanotes sppu ty
javanotes sppu ty
javanotes sppu ty
Chapter 1
1. An Introduction to Java
• Java Overview:
• Java is a high-level, class-based, object-oriented programming language.
• It was designed to have as few implementation dependencies as possible.
• Java applications are typically compiled to bytecode that can run on any Java Virtual
Machine (JVM).
• It's widely used for building web, mobile, and desktop applications.
5. Java Environment
• Java Development Kit (JDK):
• Includes tools for developing, debugging, and monitoring Java applications.
• Java Runtime Environment (JRE):
• A subset of the JDK, containing the JVM, core libraries, and other components to run
Java applications.
• Java Virtual Machine (JVM):
• A virtual machine that enables Java bytecode to be executed on any platform.
6. Simple Java Program
• Example:
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): The entry point of the program.
• System.out.println("Hello, World!"): Prints "Hello, World!" to the console.
8. Types of Comments
• Single-line Comment:
• Begins with // and continues to the end of the line.
• Example: // This is a single-line comment
• Multi-line Comment:
• Begins with /* and ends with */.
• Example:
java
Copy code
/*
This is a
multi-line comment
*/
• Documentation Comment:
• Begins with /** and ends with */.
• Used to generate documentation with javadoc.
• Example:
java
Copy code
/**
* This is a documentation comment.
* It describes the class or method below.
*/
9. Data Types
• Primitive Data Types:
• byte: 8-bit integer.
• short: 16-bit integer.
• int: 32-bit integer.
• long: 64-bit integer.
• float: 32-bit floating point.
• double: 64-bit floating point.
• char: 16-bit Unicode character.
• boolean: Represents true or false.
• Non-Primitive Data Types:
• Includes classes, interfaces, arrays, and strings.
• Non-primitive types are reference types.
• BufferedReader:
• Used to read text from an input stream efficiently.
• Requires exception handling (IOException).
• Example:
java
Copy code
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String input = br.readLine();
• Scanner:
• Simplifies input by providing methods to parse various types (int, double, etc.).
• Example:
java
Copy code
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
chapter 2
1. Defining Your Own Classes
• Class Definition:
• A class in Java is a blueprint for creating objects.
• It contains fields (attributes) and methods (functions) that define the behavior of
objects.
• Syntax:
java
Copy code
class ClassName {
// Fields
// Methods
}
• Example:
java
Copy code
class Car {
String model;
int year;
void startEngine() {
System.out.println("Engine started");
}
}
• In this example, Car is a class with two fields (model and year) and one method
(startEngine()).
• Private:
• The class, method, or field is accessible only within the class it is declared.
• Example:
java
Copy code
private String name;
• Protected:
• The field or method is accessible within the same package and by subclasses.
• Example:
java
Copy code
protected double salary;
• Default (Package-Private):
• No keyword is used. The field or method is accessible only within the same package.
• Example:
java
Copy code
String address; // default access
3. Array of Objects
• Array of Objects:
• An array that holds references to objects.
• Useful for storing multiple objects of the same type.
• Syntax:
java
Copy code
ClassName[] arrayName = new ClassName[size];
• Example:
java
Copy code
Car[] cars = new Car[5];
cars[0] = new Car();
• Overloading Constructors:
• Multiple constructors in a class with different parameter lists.
• Allows objects to be initialized in different ways.
• Example:
java
Copy code
public Car(String model) {
this.model = model;
}
• Static Block:
• A block of code that gets executed when the class is loaded.
• Used to initialize static fields.
• Example:
java
Copy code
static {
// static block
}
5. Predefined Classes
Object Class
• Overview:
• The Object class is the parent class of all classes in Java.
• Every class implicitly inherits from Object.
• Methods:
• equals(): Compares two objects for equality.
java
Copy code
public boolean equals(Object obj) {
return (this == obj);
}
• StringBuffer Class:
• Represents mutable sequences of characters.
• Used when frequent modifications to strings are needed.
• Common Methods:
• append(): Adds a string to the end.
java
Copy code
sb.append("text");
• Example:
java
Copy code
package mypackage;
7. Wrapper Classes
• Overview:
• Wrapper classes provide a way to use primitive data types as objects.
• Commonly used in collections like ArrayList where objects are required.
• Examples:
• Integer: Wraps an int.
• Double: Wraps a double.
• Character: Wraps a char.
• Boolean: Wraps a boolean.
• Autoboxing and Unboxing:
• Autoboxing: Automatic conversion of primitive types to corresponding wrapper
class.
java
Copy code
Integer num = 5; // autoboxing
chapter 3
. Inheritance Basics (extends Keyword) and Types of Inheritance
• Inheritance Basics:
• Definition: Inheritance is a mechanism where a new class inherits the properties and
behaviors (fields and methods) of an existing class.
• extends Keyword: Used to create a subclass from a superclass.
• Syntax:
java
Copy code
class Subclass extends Superclass {
// Additional fields and methods
}
• Example:
java
Copy code
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
• Types of Inheritance:
• Single Inheritance: A subclass inherits from one superclass.
java
Copy code
class A { }
class B extends A { }
• Multilevel Inheritance: A class is derived from another derived class.
java
Copy code
class A { }
class B extends A { }
class C extends B { }
• Example:
java
Copy code
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void eat() {
super.eat(); // Calls the superclass method
System.out.println("Dog eats");
}
}
• Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
• Runtime Polymorphism:
• The ability to call overridden methods through the reference of the superclass.
• Example:
java
Copy code
Animal myDog = new Dog();
myDog.sound(); // Outputs: Dog barks
void concreteMethod() {
System.out.println("Concrete method");
}
}
• Abstract Methods:
• Methods declared without implementation.
• Subclasses must provide an implementation for abstract methods.
• Syntax:
java
Copy code
abstract void methodName();
• Implementing Interfaces:
• A class that implements an interface must provide implementations for all of its
methods.
• Syntax:
java
Copy code
class ImplementingClass implements InterfaceName {
@Override
public void method() {
System.out.println("Method implemented");
}
}
• Functional Interface:
• An interface with exactly one abstract method.
• Can have multiple default or static methods.
• Syntax:
java
Copy code
@FunctionalInterface
interface FunctionalInterfaceName {
void singleAbstractMethod();
}
• Example:
java
Copy code
@FunctionalInterface
interface MyFunctionalInterface {
void doSomething();
}
Chapter 4
1. Dealing with Errors, Exception Class, Checked and Unchecked Exception
• Errors:
• Definition: Errors are serious issues that a typical application should not try to
handle. They usually represent problems in the environment in which the application
is running.
• Examples: OutOfMemoryError, StackOverflowError.
• Exceptions:
• Definition: Exceptions are conditions that occur during the execution of a program
that disrupt the normal flow of the program's instructions.
• Exception Class:
• The Exception class is the superclass of all exceptions.
• All exceptions, checked or unchecked, are subclasses of Exception.
• Syntax:
java
Copy code
class MyException extends Exception {
// Custom exception code
}
• Unchecked Exceptions:
• Checked at runtime.
• These exceptions are not checked at compile-time.
• Examples: NullPointerException,
ArrayIndexOutOfBoundsException.
• Syntax:
java
Copy code
void method() {
// code that may throw NullPointerException
}
• Example:
java
Copy code
try {
int division = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
• Example:
java
Copy code
class MyCustomException extends Exception {
MyCustomException(String message) {
super(message);
}
}
• Streams:
• Definition: A stream is a sequence of data.
• In Java, streams are used to perform input and output operations.
• Types of Streams:
• InputStream: Reads data from a source.
• OutputStream: Writes data to a destination.
• Example:
java
Copy code
FileInputStream inputStream = new FileInputStream("input.txt");
int data = inputStream.read();
while (data != -1) {
System.out.print((char) data);
data = inputStream.read();
}
inputStream.close();
5. Input-OutputStream
• FileInputStream/FileOutputStream:
• FileInputStream: Reads raw byte data from a file.
• FileOutputStream: Writes raw byte data to a file.
• Syntax:
java
Copy code
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
• Example:
java
Copy code
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
fis.close();
fos.close();
• BufferedInputStream/BufferedOutputStream:
• BufferedInputStream: Adds buffering to the input stream to increase efficiency.
• BufferedOutputStream: Adds buffering to the output stream for more efficient
writing.
• Syntax:
java
Copy code
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("output.txt"));
• Example:
java
Copy code
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("output.txt"));
int data;
while ((data = bis.read()) != -1) {
bos.write(data);
}
bis.close();
bos.close();
• DataInputStream/DataOutputStream:
• DataInputStream: Allows reading Java primitive data types (int, float, etc.) from an
input stream.
• DataOutputStream: Allows writing Java primitive data types to an output stream.
• Syntax:
java
Copy code
DataInputStream dis = new DataInputStream(new
FileInputStream("data.bin"));
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("data.bin"));
• Example:
java
Copy code
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("data.bin"));
dos.writeInt(123);
dos.writeFloat(3.14f);
dos.writeBoolean(true);
dos.close();
6. Reader-Writer
• FileReader/FileWriter:
• FileReader: Reads character data from a file.
• FileWriter: Writes character data to a file.
• Syntax:
java
Copy code
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");
• Example:
java
Copy code
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");
int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
fr.close();
fw.close();
• BufferedReader/BufferedWriter:
• BufferedReader: Adds buffering to the character input stream for more efficient
reading.
• BufferedWriter: Adds buffering to the character output stream for more efficient
writing.
• Syntax:
java
Copy code
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new
FileWriter("output.txt"));
• Example:
java
Copy code
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new
FileWriter("output.txt"));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
• InputStreamReader/OutputStreamWriter:
• InputStreamReader: Converts byte input stream to character input stream.
• OutputStreamWriter: Converts character output stream to byte output stream.
• Syntax:
java
Copy code
InputStreamReader isr = new InputStreamReader(new
FileInputStream("input.txt"), "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new
FileOutputStream("output.txt"), "UTF-8");
• Example:
java
Copy code
InputStreamReader isr = new InputStreamReader(new
FileInputStream("input.txt"), "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new
FileOutputStream("output.txt"), "UTF-8");
int data;
while ((data = isr.read()) != -1) {
osw.write(data);
}
isr.close();
osw.close();
chapter 5
1. What is AWT? What is Swing? Difference between AWT and Swing
• AWT (Abstract Window Toolkit):
• Definition: AWT is Java's original platform-dependent GUI toolkit. It provides a set
of APIs to create and manage graphical user interface (GUI) components.
• Components: AWT components are heavyweight, meaning they rely on the
underlying native (OS) resources to display the UI elements.
• Example Components: Button, Label, TextField, Frame.
• Swing:
• Definition: Swing is a part of Java's standard library (Java Foundation Classes - JFC)
that provides a more powerful and flexible set of GUI components. It is built on top
of AWT and is platform-independent.
• Components: Swing components are lightweight, meaning they are written entirely
in Java and do not depend on native OS resources.
• Example Components: JButton, JLabel, JTextField, JFrame.
• Difference between AWT and Swing:
• Platform Dependency: AWT is platform-dependent, while Swing is platform-
independent.
• Component Types: AWT components are heavyweight; Swing components are
lightweight.
• Look and Feel: AWT components have a native look and feel, while Swing
components have a consistent look and feel across platforms.
• Performance: AWT is generally faster because it uses native components, but Swing
provides more flexibility and control over the UI.
• Extensibility: Swing provides more advanced and customizable components
compared to AWT.
• Example:
java
Copy code
JFrame frame = new JFrame("Example");
frame.setLayout(new FlowLayout());
frame.setSize(300, 200);
frame.setVisible(true);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
• JFileChooser:
• Definition: A component that allows the user to choose files or directories from the
filesystem.
• Usage:
java
Copy code
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +
selectedFile.getAbsolutePath());
}
• JColorChooser:
• Definition: A component that provides a user interface for selecting a color.
• Usage:
java
Copy code
Color selectedColor = JColorChooser.showDialog(frame, "Choose a
color", Color.RED);
if (selectedColor != null) {
System.out.println("Selected color: " +
selectedColor.toString());
}
• KeyAdapter:
• Provides default implementations for methods in KeyListener.
• Methods:
• keyTyped(KeyEvent e)
• keyPressed(KeyEvent e)
• keyReleased(KeyEvent e)
• Example:
java
Copy code
JTextField textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
• WindowAdapter:
• Provides default implementations for methods in WindowListener.
• Methods:
• windowOpened(WindowEvent e)
• windowClosing(WindowEvent e)
• windowClosed(WindowEvent e)
• windowIconified(WindowEvent e)
• windowDeiconified(WindowEvent e)
• windowActivated(WindowEvent e)
• windowDeactivated(WindowEvent e)
• Example:
java
Copy code
JFrame frame = new JFrame("Window Adapter Example");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
System.exit(0);
}
});
• Examples:
• ActionListener with 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!");
}
});
• Advantages:
• Conciseness: Reduces the need for separate classes and makes the code more
concise.
• Local Scope: The class is used only where it is defined, limiting its scope and
improving readability.
• BorderLayout: Divides the container into five regions (North, South, East, West,
Center) where components can be placed.
• Usage:
java
Copy code
BorderLayout borderLayout = new BorderLayout();
JFrame frame = new JFrame();
frame.setLayout(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);
gbc.gridx = 0; // column
gbc.gridy = 0; // row
panel.add(new JButton("Button 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(new JButton("Button 2"), gbc);
• Swing Layouts:
• Swing layouts are similar to AWT layouts but often provide more features and better
appearance customization.
• Common Components in AWT and Swing:
• JFrame: The main window of a Swing application.
• Usage:
java
Copy code
JFrame frame = new JFrame("Swing Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
• JRadioButton: A radio button that is part of a group where only one button can be
selected at a time.
• Usage:
java
Copy code
JRadioButton radioButton = new JRadioButton("Option 1");
• JList: Displays a list of items from which the user can select one or more.
• Usage:
java
Copy code
String[] items = {"Item 1", "Item 2", "Item 3"};
JList<String> list = new JList<>(items);
• Adapters:
• Definition: Adapter classes provide default implementations of event listener
interfaces, allowing you to override only the methods you need.
• Examples: MouseAdapter, KeyAdapter, WindowAdapter.
• Usage:
java
Copy code
JButton button = new JButton("Click Me");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
});