JAVA
1. Applet Life Cycle
An applet is a Java program that runs in a web browser. The life cycle of an
applet involves the following methods:
- init(): Called when the applet is initialised.
- start(): Called when the applet starts running.
- stop(): Called when the applet is stopped, like when the user leaves the page.
- destroy(): Called when the applet is destroyed to release resources.
public class MyApplet extends Applet {
public void init() { System.out.println("Applet Initialized"); }
public void start() { System.out.println("Applet Started"); }
public void stop() { System.out.println("Applet Stopped"); }
public void destroy() { System.out.println("Applet Destroyed"); }
}
2. Scope of the Variable
Scope defines where a variable can be used.
- Local Scope: Declared inside methods.
- Instance Scope: Declared in a class but outside methods.
- Static Scope: Declared with static, shared across all instances.
class Example {
int instanceVar = 5; // Instance scope
static int staticVar = 10; // Static scope
public void method() {
int localVar = 15; // Local scope
System.out.println(localVar);
}
}
3. Java Program Structure
A Java program follows this structure:
1. Package declaration: Optional, helps organise classes.
2. Import statements: For importing built-in or custom packages.
3. Class declaration: The main logic resides inside classes.
4. Main method: Entry point of the program.
package mypackage;
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
4. Packages
Packages in Java are used to group related classes. They help in
organising code and avoiding name conflicts.
package mypackage; // Declare package
public class MyClass {
public void display() { System.out.println("In MyClass"); }
}
// Use in another file
import mypackage.MyClass; // Import package
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display(); // Output: In MyClass
}
}
5. Constructor
A constructor is a special method that is called when an object is created. It
is used to initialise objects.
class Car {
String model;
public Car(String model) { // Constructor
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Honda");
System.out.println(myCar.model); // Output: Honda
}
}
6. StringBuffer Methods
StringBuffer is used for mutable strings (strings that can change). Key
methods are:
- append(): Adds text to the buffer.
- insert(): Inserts text at a specific position.
- reverse(): Reverses the content.
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Output: "Hello World"
sb.insert(5, ","); // Output: "Hello, World"
sb.reverse(); // Output: "dlroW ,olleH"
System.out.println(sb);
}
}
7. Exception Handling
Java provides a way to handle runtime errors using try-catch blocks. This
prevents the program from crashing.
- try: Block where the error might occur.
- catch: Block to handle the error.
- finally: Block that always executes, even if an error occurs.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // Will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This always runs.");
}
}
}
8. Random Access Files
RandomAccessFile allows you to read and write to any position in a file.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
file.writeUTF("Hello"); // Write to file
file.seek(0); // Move to the start of the file
System.out.println(file.readUTF()); // Output: Hello
file.close();
}
}
9. Tokens
Tokens are the smallest units in a Java program, like keywords, identifiers,
literals, operators, and separators. For example:
int number = 10;
- `int`: Keyword
- `number`: Identifier
- `=`, `+`, `-`: Operators
- `10`: Literal
10. Streams in Java
Streams are used to handle input/output operations in Java.
- InputStream: For reading data.
- OutputStream: For writing data.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream("input.txt");
int data;
while((data = input.read()) != -1) {
System.out.print((char) data); // Reads file content
}
input.close();
}
}
11. Life Cycle of a Thread
A thread in Java has five states:
1. New: Thread created but not started.
2. Runnable: Ready to run.
3. Blocked: Waiting for resources.
4. Waiting: Waiting for another thread’s action.
5. Terminated: Finished execution.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}
12. Decision Making and Looping
- Decision Making:
Using `if-else` and `switch`.
- Looping:
Using `for`, `while`, and `do-while` loops.
int age = 18;
// Decision making
if (age >= 18) {
System.out.println("You are an adult");
} else {
System.out.println("You are a minor");
}
// Looping
for (int i = 0; i < 5; i++) {
System.out.println(i); // Output: 0 to 4
}
13. Method Overloading and Overriding
- Overloading:
Methods with the same name but different parameters.
- Overriding:
Subclass provides a specific implementation of a method that is already
defined in its parent class.
Method Overloading Example:
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
Method Overriding Example:
class Animal {
public void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}