π₯ VanshRajput Java Quiz Challenge
π You Won βΉ1!
Congratulations on scoring 100%! π
Enter Your UPI ID
β Submission Received!
Reward will be credited in 7 days. For queries: @ig_vanshsingh
Java Basics: Hello World Program
β This is the simplest Java program.
β
Every Java application must have a main method.
πΉ Key Points:
- public β Makes the class accessible from anywhere.
- static β Allows
main()to run without creating an object. - void β Main does not return any value.
- System.out.println() β Prints text to the console.
/*
* Java Program: Hello World
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!"); // Print message
}
}
Java Basics: Variables & Data Types
β Variables store data in memory, and Java has different types of variables.
πΉ Key Points:
- int β Stores integers (whole numbers).
- double β Stores decimal numbers.
- char β Stores single characters.
- String β Stores text.
- boolean β Stores true/false values.
/*
* Java Program: Variables & Data Types
*/
public class VariablesExample {
public static void main(String[] args) {
int myNumber = 25; // Integer variable
double myDecimal = 10.5; // Decimal variable
char myLetter = 'A'; // Character variable
String myText = "Hello Java"; // String variable
boolean myBool = true; // Boolean variable
// Printing variables
System.out.println("Integer: " + myNumber);
System.out.println("Decimal: " + myDecimal);
System.out.println("Character: " + myLetter);
System.out.println("String: " + myText);
System.out.println("Boolean: " + myBool);
}
}
Java Basics: Conditional Statements
β Conditional statements allow decision-making in Java.
πΉ Key Points:
- if β Executes a block of code if a condition is true.
- else β Executes a block of code if the condition is false.
- else if β Checks multiple conditions sequentially.
/*
* Java Program: Conditional Statements (if-else)
*/
public class ConditionalExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
}
}
Java Basics: Loops
β Loops allow executing a block of code multiple times.
πΉ Key Points:
- for β Runs a loop a specific number of times.
- while β Runs a loop as long as the condition is true.
- do-while β Runs at least once, then repeats while the condition is true.
/*
* Java Program: Loops (for, while, do-while)
*/
public class LoopExample {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 5; i++) {
System.out.println("For Loop: " + i);
}
// while loop
int j = 1;
while (j <= 5) {
System.out.println("While Loop: " + j);
j++;
}
// do-while loop
int k = 1;
do {
System.out.println("Do-While Loop: " + k);
k++;
} while (k <= 5);
}
}
Java Basics: Arrays
β An array stores multiple values of the same data type in a single variable.
πΉ Key Points:
- Arrays have a fixed size.
- Indexing starts from 0.
- Can store int, double, char, or objects.
/*
* Java Program: Arrays
*/
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Java Basics: Functions (Methods)
β Methods are blocks of code that perform a specific task.
πΉ Key Points:
- Methods improve code reusability.
- Can take input (parameters) and return a value.
- static methods can be called without an object.
/*
* Java Program: Functions (Methods)
*/
public class MethodExample {
public static void main(String[] args) {
int sum = add(10, 20);
System.out.println("Sum: " + sum);
}
// Method to add two numbers
public static int add(int a, int b) {
return a + b;
}
}
Java Basics: Object-Oriented Programming (OOP)
β OOP allows structuring programs using objects and classes.
πΉ Key Points:
- Class β Blueprint for objects.
- Object β An instance of a class.
- Encapsulation, Inheritance, Polymorphism, and Abstraction are key OOP principles.
/*
* Java Program: OOP - Classes & Objects
*/
class Car {
String brand;
int speed;
// Constructor
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Method
void showDetails() {
System.out.println("Car Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
public class OOPExample {
public static void main(String[] args) {
Car myCar = new Car("Tesla", 200);
myCar.showDetails();
}
}
Java OOP: Inheritance
β Inheritance allows a class (child) to acquire properties and behaviors from another class (parent).
πΉ Key Points:
- extends keyword is used to inherit a class.
- The child class can override parent class methods.
- Supports **code reusability** and **hierarchical design**.
/*
* Java Program: Inheritance
*/
class Animal {
void makeSound() {
System.out.println("Animals make sounds...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks: Woof! Woof!");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Inherited method
myDog.bark();
}
}
Java OOP: Polymorphism
β Polymorphism allows methods to perform different tasks based on input.
πΉ Types of Polymorphism:
- Method Overloading β Same method name, different parameters.
- Method Overriding β Redefining a parent class method in a child class.
/*
* Java Program: Polymorphism (Method Overloading & Overriding)
*/
class MathOperations {
// Method Overloading
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
class Parent {
void showMessage() {
System.out.println("Message from Parent class.");
}
}
class Child extends Parent {
// Method Overriding
void showMessage() {
System.out.println("Message from Child class.");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum (2 numbers): " + math.add(5, 10));
System.out.println("Sum (3 numbers): " + math.add(5, 10, 15));
Parent obj = new Child();
obj.showMessage(); // Overridden method is called
}
}
Java OOP: Abstract Classes & Interfaces
β Abstract classes and interfaces define templates for classes.
πΉ Key Points:
- abstract keyword is used to define an abstract class.
- Interfaces only contain method signatures (no implementation).
- Classes implement interfaces using the implements keyword.
/*
* Java Program: Abstract Classes & Interfaces
*/
abstract class Vehicle {
abstract void start(); // Abstract method (no body)
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with a key.");
}
}
// Interface
interface Animal {
void makeSound(); // Method signature only
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks: Woof! Woof!");
}
}
public class AbstractInterfaceExample {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
Dog myDog = new Dog();
myDog.makeSound();
}
}
Java Basics: Exception Handling
β Exception handling prevents program crashes due to errors.
πΉ Key Points:
- try β Code that may throw an exception.
- catch β Handles exceptions.
- finally β Executes regardless of exception occurrence.
/*
* Java Program: Exception Handling
*/
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero error
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
System.out.println("This will always execute.");
}
}
}
Java Basics: File Handling
β File handling allows reading and writing files.
πΉ Key Points:
- FileWriter β Writes data to a file.
- FileReader β Reads data from a file.
- BufferedReader β Efficient file reading.
/*
* Java Program: File Handling (Read & Write)
*/
import java.io.*;
public class FileHandlingExample {
public static void main(String[] args) {
String filePath = "example.txt";
// Writing to a file
try (FileWriter writer = new FileWriter(filePath)) {
writer.write("Hello, this is a test file.");
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error writing to file.");
}
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("File content: " + line);
}
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}
}
Java Advanced: Multithreading
β Multithreading allows multiple tasks to run concurrently.
πΉ Key Points:
- Thread Class β Create threads by extending Thread.
- Runnable Interface β Implements the run() method.
- Synchronization β Prevents thread interference.
/*
* Java Program: Multithreading
*/
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
Java GUI: Swing Framework
β Java Swing is used to create graphical applications.
πΉ Key Points:
- JFrame β Main application window.
- JButton β Clickable button.
- ActionListener β Handles button clicks.
/*
* Java Program: Simple Swing GUI
*/
import javax.swing.*;
import java.awt.event.*;
public class SwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing GUI Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 50, 120, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Java Database Connectivity (JDBC)
β JDBC allows Java applications to connect to databases.
πΉ Key Points:
- DriverManager β Connects to database.
- Connection β Establishes the database connection.
- Statement β Executes SQL queries.
/*
* Java Program: JDBC Connection
*/
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// Execute a Query
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java Collections Framework
β The Collections Framework provides dynamic data structures.
πΉ Key Points:
- ArrayList β Dynamic arrays.
- HashMap β Key-value pairs.
- LinkedList β Doubly linked list implementation.
/*
* Java Program: ArrayList & HashMap Example
*/
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// Using ArrayList
ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println("Fruits List: " + fruits);
// Using HashMap
HashMap studentMap = new HashMap<>();
studentMap.put(101, "John");
studentMap.put(102, "Alice");
System.out.println("Student ID 101: " + studentMap.get(101));
}
}
Java Functional Programming: Lambda Expressions
β Lambda expressions provide a concise way to implement interfaces.
πΉ Key Points:
- Functional Interface β An interface with one abstract method.
- Lambda Syntax β (parameters) -> { expression }.
- Reduces **boilerplate code**.
/*
* Java Program: Lambda Expressions
*/
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
// Using Lambda for Addition
MathOperation add = (a, b) -> a + b;
System.out.println("Sum: " + add.operate(10, 5));
}
}
Java Streams API
β Java Streams allow functional-style operations on collections.
πΉ Key Points:
- Stream.filter() β Filters elements based on condition.
- Stream.map() β Transforms elements.
- Stream.forEach() β Iterates and performs actions.
/*
* Java Program: Streams API
*/
import java.util.*;
public class StreamsExample {
public static void main(String[] args) {
List numbers = Arrays.asList(10, 20, 30, 40, 50);
// Filtering numbers greater than 25
numbers.stream()
.filter(n -> n > 25)
.forEach(System.out::println);
}
}
JavaFX GUI Framework
β JavaFX is used for creating modern graphical applications.
πΉ Key Points:
- Stage β The primary window.
- Scene β Holds UI components.
- Button β Clickable button element.
/*
* Java Program: JavaFX GUI
*/
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXExample extends Application {
@Override
public void start(Stage primaryStage) {
Button button = new Button("Click Me");
button.setOnAction(e -> System.out.println("Button Clicked!"));
StackPane root = new StackPane(button);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("JavaFX Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Java Servlets for Web Applications
β Servlets are Java programs that handle web requests.
πΉ Key Points:
- doGet() β Handles HTTP GET requests.
- doPost() β Handles HTTP POST requests.
- PrintWriter β Sends responses to the client.
/*
* Java Program: Servlets
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello, Servlet!
");
}
}
