Java was developed by James Gosling at Sun Microsystems. Originally designed for embedded systems, Java became widely popular due to its platform independence and security features, making it ideal for web applications.
Java is a pure object-oriented language where everything revolves around objects and classes. Key OOP principles include:
Java has two types of data types:
Literals are fixed values that appear directly in the code:
Variables store values with a defined type:
Java supports two types of type conversions:
In expressions, Java promotes smaller data types automatically:
Strings are objects that represent sequences of characters.
Java supports single and multi-dimensional arrays.
Java supports several types of operators:
Operator precedence determines the order in which operators are evaluated in expressions. For example, multiplication and division have higher precedence than addition and subtraction.
Order (from highest to lowest):
In Java, a class is a blueprint for creating objects. It can contain fields (variables) and methods to define behavior.
class TonyStark { int power = 100; void showPower() { System.out.println("Power level: " + power); } }
Objects are instances of a class. Here's how to declare and use them:
public class Main { public static void main(String[] args) { TonyStark ironMan = new TonyStark(); // Object declaration ironMan.showPower(); } }
Constructors are special methods used to initialize objects.
class TonyStark { int suitNumber; TonyStark(int n) { suitNumber = n; } void showSuit() { System.out.println("Mark " + suitNumber); } }
You can define multiple methods with the same name but different parameters.
class Jarvis { void greet() { System.out.println("Hello, Tony!"); } void greet(String name) { System.out.println("Hello, " + name + "!"); } }
class Reactor { int level; Reactor(int l) { level = l; } Reactor boost(Reactor r) { return new Reactor(this.level + r.level); } }
A method can call itself. This is called recursion.
class Demo { int factorial(int n) { if (n == 1) return 1; return n * factorial(n - 1); } }
class Lab { private int secret = 42; // Access control static int techCount = 5; // Static final int ID = 101; // Constant }
Classes can be defined within another class.
class Avengers { class Suit { void show() { System.out.println("Nano Suit Ready"); } } }
public class Demo { public static void main(String[] args) { String hero = "IronMan"; System.out.println(hero.toUpperCase()); // IRONMAN } }
public class CommandDemo { public static void main(String[] args) { System.out.println("Hello, " + args[0]); } } // Run: java CommandDemo Tony // Output: Hello, Tony
Inheritance allows one class to acquire properties of another.
class Hero { void display() { System.out.println("I’m a Hero"); } } class IronMan extends Hero { void show() { System.out.println("I’m IronMan"); } }
class Avenger { String name = "Unknown"; } class Stark extends Avenger { Stark() { super.name = "Tony Stark"; } }
class AI { void respond() { System.out.println("Generic AI"); } } class Jarvis extends AI { void respond() { System.out.println("Yes, Mr. Stark."); } } public class Main { public static void main(String[] args) { AI system = new Jarvis(); system.respond(); // Output: Yes, Mr. Stark. } }
abstract class Armor { abstract void activate(); } class NanoSuit extends Armor { void activate() { System.out.println("Suit Activated!"); } }
final class Shield {} class IronShield extends Shield { // Error! Cannot inherit final class // ... }
Every class in Java inherits from Object
. Common methods include:
toString()
equals()
hashCode()
class ArcReactor { public String toString() { return "Clean Energy Source"; } }
package tech.stark; public class Reactor { public void activate() { System.out.println("Arc Reactor Online"); } }
import tech.stark.Reactor; public class Lab { public static void main(String[] args) { Reactor r = new Reactor(); r.activate(); } }
interface Suit { void activate(); } class NanoSuit implements Suit { public void activate() { System.out.println("NanoSuit Deployed"); } }
public class Arc { public static void main(String[] args) { try { int div = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } } }
public class TryDemo { public static void main(String[] args) { try { try { int a = 30 / 0; } catch (ArithmeticException e) { System.out.println("Inner catch: " + e); } int[] arr = new int[2]; arr[5] = 100; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Outer catch: " + e); } } }
public class Jarvis { static void greet(int id) throws Exception { if (id != 101) throw new Exception("Unauthorized"); } public static void main(String[] args) { try { greet(100); } catch (Exception e) { System.out.println(e); } finally { System.out.println("Access Attempted"); } } }
class PowerOverloadException extends Exception { PowerOverloadException(String msg) { super(msg); } } class Reactor { void boost(int level) throws PowerOverloadException { if (level > 100) throw new PowerOverloadException("Too much power!"); } }
public class MainThread { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } }
class AI extends Thread { public void run() { System.out.println("AI System Activated"); } } public class Lab { public static void main(String[] args) { AI jarvis = new AI(); jarvis.start(); } }
class Bot extends Thread { public void run() { for (int i = 0; i < 3; i++) { System.out.println(getName() + " running..."); } } } public class Demo { public static void main(String[] args) { new Bot().start(); new Bot().start(); } }
class StarkAI extends Thread { public void run() { System.out.println("Running..."); } } public class Main { public static void main(String[] args) throws InterruptedException { StarkAI s = new StarkAI(); s.start(); System.out.println(s.isAlive()); s.join(); System.out.println("Finished"); } }
class PriorityTest extends Thread { public void run() { System.out.println("Thread priority: " + getPriority()); } } public class Main { public static void main(String[] args) { PriorityTest t = new PriorityTest(); t.setPriority(Thread.MAX_PRIORITY); t.start(); } }
class Shared { synchronized void print(String msg) { System.out.println("[" + msg); try { Thread.sleep(500); } catch (Exception e) {} System.out.println("]"); } }
class Resource { synchronized void waitForIt() throws InterruptedException { wait(); } synchronized void signalIt() { notify(); } }
Note: Methods like suspend(), resume(), and stop() are deprecated. Use flags instead.
class Worker extends Thread { private boolean running = true; public void run() { while (running) { System.out.println("Working..."); try { Thread.sleep(1000); } catch (Exception e) {} } } public void stopWorking() { running = false; } }
In Java, Input and Output operations are essential for interacting with the user and external files. Here are the basics of reading console input and writing console output:
// Reading console input import java.util.Scanner; Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); // Writing console output System.out.println("Hello, " + name + "!");
The PrintWriter
class provides convenient methods for writing formatted text to files or the
console:
import java.io.PrintWriter; try { PrintWriter writer = new PrintWriter("output.txt"); writer.println("This is a line of text."); writer.close(); } catch (Exception e) { System.out.println("Error writing to file."); }
Reading from and writing to files can be done using classes like FileReader
and
FileWriter
.
import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; // Reading from file try { FileReader fr = new FileReader("input.txt"); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } catch (Exception e) { System.out.println("Error reading file."); } // Writing to file try { FileWriter fw = new FileWriter("output.txt"); fw.write("This is a new line in the file."); fw.close(); } catch (Exception e) { System.out.println("Error writing to file."); }
An applet is a small Java program that can be embedded in a web page and run inside a browser. The basic
architecture of an applet consists of the init()
, start()
, and
paint()
methods:
import java.applet.Applet; import java.awt.Graphics; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello, Java Applet!", 50, 50); } }
To force an applet to repaint itself, use the repaint()
method:
public void paint(Graphics g) { g.clearRect(0, 0, 300, 300); // Clear the area before drawing g.drawString("Repainting the applet", 50, 50); } // Request repaint repaint();
The <applet>
HTML tag is used to embed an applet in a web page. The applet is
specified by its class file:
You can pass parameters to applets using the <param>
tag in HTML:
The AudioClip
interface allows applets to play sound:
import java.applet.Applet; import java.applet.AudioClip; import java.net.URL; public class PlaySoundApplet extends Applet { AudioClip clip; public void init() { try { URL sound = new URL(getCodeBase(), "sound.wav"); clip = getAudioClip(sound); } catch (Exception e) { System.out.println("Error loading sound."); } } public void start() { clip.play(); } }
Event handling in Java uses a delegation model. Different event types trigger methods in the event listener interfaces:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button clicked!"); } }
Event listener interfaces capture specific events. Common examples include:
Adapter classes provide default implementations for event listener interfaces, allowing you to override only the methods you need:
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class MouseClickListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked at " + e.getX() + ", " + e.getY()); } }
The Abstract Window Toolkit (AWT) is the foundation for building graphical user interfaces (GUIs) in Java. It contains classes for creating windows, handling events, and drawing graphics.
import java.awt.*; public class AWTExample { public static void main(String[] args) { Frame frame = new Frame("AWT Window"); frame.setSize(400, 400); frame.setVisible(true); } }
In AWT, a window is represented by the Frame
class. Here’s how to create a simple window:
import java.awt.*; public class SimpleWindow { public static void main(String[] args) { Frame frame = new Frame("Simple Window"); frame.setSize(300, 200); frame.setVisible(true); } }
Frames are the top-level containers for GUI elements. Here's how you can work with frames:
import java.awt.*; public class FrameWindow { public static void main(String[] args) { Frame frame = new Frame("Frame Example"); Button button = new Button("Click Me"); frame.add(button); frame.setSize(400, 300); frame.setLayout(new FlowLayout()); frame.setVisible(true); } }
AWT provides basic graphics capabilities. You can use the Graphics
class to draw shapes,
lines, and text.
import java.awt.*; public class GraphicsExample extends Frame { public void paint(Graphics g) { g.setColor(Color.RED); g.drawLine(50, 50, 150, 150); // Draw line g.drawRect(200, 200, 100, 100); // Draw rectangle g.setColor(Color.BLUE); g.drawString("AWT Graphics Example", 100, 100); // Draw string } public static void main(String[] args) { GraphicsExample obj = new GraphicsExample(); obj.setSize(400, 400); obj.setVisible(true); } }
AWT provides several controls that can be added to frames. These include labels, buttons, checkboxes, text fields, and more.
Controls are the basic components used for interacting with users. Below is an example of adding controls to a frame:
import java.awt.*; public class ControlExample { public static void main(String[] args) { Frame frame = new Frame("Control Example"); Label label = new Label("Enter your name:"); TextField textField = new TextField(); Button button = new Button("Submit"); frame.add(label); frame.add(textField); frame.add(button); frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.setVisible(true); } }
Buttons are commonly used for triggering actions in a GUI. Here’s how to use a button in AWT:
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, 200); frame.setVisible(true); } }
Checkboxes allow users to select multiple options. Here’s an example:
import java.awt.*; import java.awt.event.*; public class CheckboxExample { public static void main(String[] args) { Frame frame = new Frame("Checkbox Example"); Checkbox checkbox1 = new Checkbox("Option 1"); Checkbox checkbox2 = new Checkbox("Option 2"); frame.add(checkbox1); frame.add(checkbox2); frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.setVisible(true); } }
Check box groups allow grouping of checkboxes for mutual exclusivity. Below is an example:
import java.awt.*; public class CheckboxGroupExample { public static void main(String[] args) { Frame frame = new Frame("Checkbox Group Example"); CheckboxGroup group = new CheckboxGroup(); Checkbox checkbox1 = new Checkbox("Option 1", group, false); Checkbox checkbox2 = new Checkbox("Option 2", group, false); frame.add(checkbox1); frame.add(checkbox2); frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.setVisible(true); } }
Choice controls allow users to select from a list of options. Here's an example:
import java.awt.*; public class ChoiceExample { public static void main(String[] args) { Frame frame = new Frame("Choice Example"); Choice choice = new Choice(); choice.add("Option 1"); choice.add("Option 2"); choice.add("Option 3"); frame.add(choice); frame.setSize(300, 200); frame.setVisible(true); } }
Text fields allow users to enter a single line of text. Here's how to use it:
import java.awt.*; public class TextFieldExample { public static void main(String[] args) { Frame frame = new Frame("TextField Example"); TextField textField = new TextField("Default text"); frame.add(textField); frame.setSize(300, 200); frame.setVisible(true); } }
Text areas allow users to enter multiple lines of text. Here's an example:
import java.awt.*; public class TextAreaExample { public static void main(String[] args) { Frame frame = new Frame("Text Area Example"); TextArea textArea = new TextArea("This is a text area."); frame.add(textArea); frame.setSize(400, 300); frame.setVisible(true); } }
Layout managers control the positioning of components. The FlowLayout
manager arranges
components sequentially from left to right:
import java.awt.*; public class FlowLayoutExample { public static void main(String[] args) { Frame frame = new Frame("FlowLayout Example"); Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); Button button3 = new Button("Button 3"); frame.setLayout(new FlowLayout()); frame.add(button1); frame.add(button2); frame.add(button3); frame.setSize(300, 200); frame.setVisible(true); } }
AWT also provides support for creating menu bars and menus. Here’s how to create a simple menu:
import java.awt.*; import java.awt.event.*; public class MenuExample { public static void main(String[] args) { Frame frame = new Frame("Menu Example"); MenuBar menuBar = new MenuBar(); Menu menu = new Menu("File"); MenuItem menuItem1 = new MenuItem("Open"); MenuItem menuItem2 = new MenuItem("Exit"); menu.add(menuItem1); menu.add(menuItem2); menuBar.add(menu); frame.setMenuBar(menuBar); frame.setSize(300, 200); frame.setVisible(true); } }