Learn coding with amol
Hello my name is amol sharma or vineet and this is my 8th part of learn coding with amol and in this part we are going to learn javascript full.
js(javascript) PART-8
Complete Java Guide — Definitions + Copy‑Code
Introduction
Java is a high‑level, class‑based, object‑oriented language designed for portability ("write once, run anywhere"). Programs compile to bytecode that runs on the JVM (Java Virtual Machine).
// HelloWorld.java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, Java!"); } } Syntax, Types, Variables, Operators
Primitive types: byte, short, int, long, float, double, char, boolean. Reference types: arrays, classes, interfaces, enums.
Variables & Literals
int age = 18; // decimal literal
long big = 1_000_000L; // underscores for readability double pi = 3.14159; // double precision char letter = 'A'; boolean ok = true; String name = "Amol"; // reference type (immutable) var auto = 42; // local variable type inference (Java 10+) Operators
int a = 5, b = 2; int sum = a + b; // arithmetic: + - * / % boolean cmp = a > b; // comparison: > < >= <= == != boolean both = (a > 0) && (b > 0); // logical: && || ! a += 3; // compound assignment int x = a++;// post-incr int y = ++b;// pre-incr Control Flow
if / else, switch (with expressions)
int score = 82;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
String day = "MON"; String type = switch (day) { // switch expression (Java 14+) case "SAT", "SUN" -> "weekend"; default -> "weekday"; }; Loops
for (int i = 0; i < 3; i++) { System.out.println(i); }
int[] nums = {1,2,3}; for (int n : nums) { // enhanced for System.out.println(n); }
int i = 0; while (i < 3) i++; Methods
A method is a function defined inside a class. Java supports overloading (same name, different parameters) and varargs.
class MathUtil {
static int add(int a, int b){ return a + b; }
static int add(int a, int b, int c){ return a + b + c; } // overload
static int sumAll(int... xs){ // varargs
int s = 0; for (int x: xs) s += x; return s;
}
} Classes & Objects
A class defines state (fields) and behavior (methods). Constructor initializes new objects. static members belong to the class, not instances.
public class Person {
private final String name;
private int age;
public static int population = 0;
public Person(String name, int age){
this.name = name; this.age = age; population++;
}
public String getName(){ return name; }
public int getAge(){ return age; }
public void haveBirthday(){ this.age++; }
} Inheritance & Polymorphism
class Animal { void speak(){ System.out.println("..."); } }
class Dog extends Animal { @Override void speak(){ System.out.println("Woof"); } } class Cat extends Animal { @Override void speak(){ System.out.println("Meow"); } }
Animal a = new Dog(); // polymorphism a.speak(); // prints "Woof" Interfaces, Abstract, Records
Interfaces & default methods
interface Greeter {
void greet(String name);
default void hi(){ System.out.println("Hi"); }
} class ConsoleGreeter implements Greeter { public void greet(String name){ System.out.println("Hello, " + name); } } Abstract classes
abstract class Shape { abstract double area(); } class Circle extends Shape { private final double r; Circle(double r){ this.r = r; } double area(){ return Math.PI * r * r; } } Records (immutable data carriers)
public record Point(int x, int y) {} Point p = new Point(3,4); System.out.println(p.x()); // 3 Enums, Packages, Access Modifiers
package com.example.model;
public enum Grade { A, B, C, D, F }
// Access modifiers: public, protected, (package-private), private Exceptions
Checked exceptions must be declared or handled; unchecked (RuntimeException) need not. Use try-with-resources for auto-close.
import java.io.*;
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } Generics
class Box<T> {
private T value;
public Box(T value){ this.value = value; }
public T get(){ return value; }
}
Box b = new Box<>("hi"); // Wildcards void printAll(java.util.List xs){ xs.forEach(System.out::println); } Collections Framework
import java.util.*;
List list = new ArrayList<>(); list.add("a"); list.add("b"); Set set = new HashSet<>(list); Map map = new HashMap<>(); map.put("a",1); map.put("b",2);
for (Map.Entry e : map.entrySet()) { System.out.println(e.getKey()+"="+e.getValue()); } Lambdas & Streams
import java.util.*;
import java.util.stream.*;
List nums = Arrays.asList(1,2,3,4,5); int sumSquares = nums.stream() .filter(n -> n % 2 == 1) .map(n -> n * n) .reduce(0, Integer::sum); System.out.println(sumSquares); File I/O & NIO
import java.nio.file.*;
import java.io.IOException;
try { Path p = Path.of("notes.txt"); Files.writeString(p, "Hello file\n"); String s = Files.readString(p); System.out.println(s); } catch (IOException e) { e.printStackTrace(); } Concurrency Basics
import java.util.concurrent.*;
ExecutorService pool = Executors.newFixedThreadPool(2); Future f = pool.submit(() -> 21 * 2); try { System.out.println(f.get()); } catch (Exception e) { e.printStackTrace(); } pool.shutdown(); Annotations
@interface Range {
int min(); int max();
}
class Demo { @Deprecated(since = "1.0") void old(){ } } JDBC (Database Access)
import java.sql.*;
String url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"; try (Connection c = DriverManager.getConnection(url); Statement st = c.createStatement()) { st.executeUpdate("CREATE TABLE users(id INT, name VARCHAR(50))"); st.executeUpdate("INSERT INTO users VALUES(1,'Amol')"); try (ResultSet rs = st.executeQuery("SELECT * FROM users")) { while (rs.next()) System.out.println(rs.getInt(1)+": "+rs.getString(2)); } } Unit Testing (JUnit 5)
// build.gradle (Groovy DSL)
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0' }
test { useJUnitPlatform() }
// Example test import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test;
class MathUtilTest { @Test void adds(){ assertEquals(5, MathUtil.add(2,3)); } } Build Tools
Maven (pom.xml)
<project xmlns="http://maven.apache.org/POM/4.0.0">
4.0.0 com.example demo 1.0.0 21 21 Gradle (build.gradle.kts)
plugins { java } java { toolchain { languageVersion.set(JavaLanguageVersion.of(21)) } } repositories { mavenCentral() } dependencies { testImplementation("org.junit.jupiter:junit-jupiter:5.10.0") } tasks.test { useJUnitPlatform() } Modern Java Features
- Java 8: Lambdas, Streams, Optional, Date/Time API.
- Java 9–11: Modules, var for locals, HTTP client.
- Java 14–17: switch expressions, text blocks, records, sealed classes.
- Java 21 (LTS): virtual threads (Project Loom), pattern matching improvements.
// Text block (Java 15+)
String json = """ { "hello": "world" } """;
// Pattern matching for instanceof (Java 16+) Object o = "hi"; if (o instanceof String s) { System.out.println(s.toUpperCase()); } Mini Project: CLI Todo App
A tiny end‑to‑end program using collections, I/O, and try‑with‑resources.
import java.nio.file.*;
import java.io.; import java.util.;
public class Todo { static final Path FILE = Path.of("todo.txt"); public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("add | list | done "); return; } Files.writeIfAbsent(FILE, new byte[0]); // helper extension not in JDK; replace below if needed } } Note: For portability, replace helper calls with standard JDK writes/reads as shown in the I/O section.
Cheatsheet
// Compile & run
javac Main.java java Main
// Common packages java.lang, java.util, java.io, java.nio, java.time, java.net, java.sql, java.math
// Access modifiers public / protected / (package-private) / private
// Common annotations @Override @Deprecated @SuppressWarnings @FunctionalInterface 
Comments
Post a Comment