<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Java]]></title><description><![CDATA[Everything related to java]]></description><link>https://block-chain.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 02 Nov 2026 22:13:55 GMT</lastBuildDate><atom:link href="https://block-chain.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[JDBC]]></title><description><![CDATA[What's JDBC ?? JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to databases, execute SQL queries, and retrieve or…]]></description><link>https://block-chain.hashnode.dev/jdbc</link><guid isPermaLink="true">https://block-chain.hashnode.dev/jdbc</guid><dc:creator><![CDATA[Rajesh Gurajala]]></dc:creator><pubDate>Sun, 25 Oct 2026 08:18:51 GMT</pubDate><content:encoded><![CDATA[<p><em><strong>What's JDBC ??</strong></em></p>
<p>JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to databases, execute SQL queries, and retrieve or modify data. JDBC driver implements the database-specific communication.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/ef03d552-8667-46e6-a561-9c6ed00120a8.png" alt="" style="display:block;margin:0 auto" />

<p>For example, suppose you're building a Java backend for an movie Ticket-booking application. You need to store users, movies, and tickets in PostgreSQL. JDBC lets your Java code communicate with that database.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/a4ab7070-d913-4f57-98cd-ce51460b8d7b.png" alt="" style="display:block;margin:0 auto" />

<p>Q1. We have different db's like MySQL, PostgreSQL, Oracle DB.. so do we need seperate code, methods for each kind to DB to interact with them ??</p>
<p>A. No, Java created <strong>interfaces</strong> and <strong>abstract classes</strong>, (which have only method initialization but no definition) so that create an object with interface reference type and u can simply use similar methods. So <strong>java.sql.*</strong> has all method definitions and DB vendors had overridden their own version of functionality. DB vendors made their group of .class files (all method bodies) into JAR.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/683fe6d2-e4d5-427c-aad9-456d44b426f9.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[Core Java 2 (OOPS)]]></title><description><![CDATA[Q: What if u want to have a same variable for all objects of Mobile class ?? A: use static keyword. Suppose u create a static field origin, then all…]]></description><link>https://block-chain.hashnode.dev/core-java-2-oops</link><guid isPermaLink="true">https://block-chain.hashnode.dev/core-java-2-oops</guid><dc:creator><![CDATA[Rajesh Gurajala]]></dc:creator><pubDate>Sat, 17 Oct 2026 11:18:01 GMT</pubDate><content:encoded><![CDATA[<h3><strong>1. Static Variables</strong></h3>
<pre><code class="language-java">
class Mobile{
    String brand, model;
    int price;

    public void getInfo(){
        System.out.printf("I'm %s %s \n", brand, model);
    }
}

class Main{
    public static void main(String args[]){

        Mobile m1 = new Mobile();
        m1.brand = "samsung";
        m1.model = "galaxy s25";
        m1.price = 100;

        Mobile m2 = new Mobile();
        m2.brand = "apple";
        m2.model = "20";
        m2.price = 130;

        m1.getInfo();    // I'm samsung galaxy s25 
        m2.getInfo();    // I'm apple 20 

    }
}
</code></pre>
<p>Q: What if u want to have a same variable for all objects of Mobile class ??</p>
<p>A: use static keyword. Suppose u create a static field <strong>origin,</strong> then all objects can use this variable as <strong>origin</strong> in methods. But in main function, u have to call it by <strong>Mobile.origin</strong> but not <strong>m1.origin, m2.origin ...</strong></p>
<p>Simply static variable is a <strong>class</strong> Member not <strong>object</strong> member.</p>
<pre><code class="language-java">
class Mobile{
    static String origin;
    String brand;

    public void getInfo(){
        System.out.printf("I'm %s from %s \n", brand, origin);
    }
}

class Main{
    public static void main(String args[]){
        Mobile m1 = new Mobile();
        m1.brand = "samsung";
        Mobile m2 = new Mobile();
        m2.brand = "apple";

        Mobile.origin = "china";
        m1.getInfo();    // I'm samsung from china
        m2.getInfo();    // I'm apple from china
    }
}
</code></pre>
<p>A better practice to instansiate static variables once at beginning is by using the static block, instead of initialising at the constructor.</p>
<pre><code class="language-java">
class Mobile{
    static String origin;
    String brand; int price;

    static{
        brand = "china";
    }

    public Mobile(){
        brand = ""; price = 0;
    }

    public void getInfo(){
        System.out.printf("I'm %s from %s \n", brand, origin);
    }
}
</code></pre>
<h3><strong>2. Static Methods</strong></h3>
<pre><code class="language-java">
class Mobile{
    static String origin;
    String brand; int price;

    static{
        origin = "china";
    }

    public Mobile(){
        brand = ""; price = 0;
    }

    public void getInfo(){
        System.out.printf("I'm %s from %s \n", brand, origin);
    }

    public static void Info(){
        // actually used for static variables
        System.out.printf("We're from %s \n", origin);
    }

    public static void personalInfo(Mobile m){
        // but possible to use attributes as well, like this
        System.out.println(m.price);
    }
}

class Main{
    public static void main(String args[]){
        // create 2 oblects m1 and m2
        m1.getInfo();
        Mobile.Info();
        Mobile.personalInfo(m2);
    }
}
</code></pre>
<h3><strong>3. Encapsulation</strong></h3>
<pre><code class="language-java">
class Person{
    private String name;
    private int age;
}
</code></pre>
<p>We made instance variables private, means no one outside class (other classes and main function can't access these variables). But, methods of Person class can access them. (getter, setter methods)</p>
<pre><code class="language-java">
public void getInfo(){
        System.out.printf("I'm %s, my age is %d \n", name, age);
    }

public void setInfo(String n, int a){
        name = n; age = a;
    }

// setInfo can also be written as:

public void setInfo(String name, int age){
        this.name = name; this.age = age;
    }
</code></pre>
<h3><strong>4. Inheritance</strong></h3>
<p>Inheriting properties from parents.</p>
<p><strong>step 1: [modularity, within a folder !!]</strong></p>
<p>if u want to make a calculator app, write functionality in <a href="http://calculator.java">calculator.java</a> and <a href="http://main.java">main.java</a> has main function using calcultor objects (without any imports, like JS or python). But both files should be in same directory.</p>
<p><strong>step 2:</strong></p>
<pre><code class="language-java">// Remember, class names always start with Capital letter.

// Calc.java
public class Calc{
    public int add(int a, int b){
        return a + b;
    }
    public int sub(int a, int b){
        return a - b;
    }
}

// Main.java
public class Main{
    public static void main(String args[]){
        int a = 10, b = 3;
        Calc c = new Calc();

        int addValue = c.add(a, b);
        int subValue = c.sub(a, b);

        System.out.printf("%d + %d = %d, %d - %d = %d", a, b, addValue, a,b, subValue);
    }
}
</code></pre>
<p>Now, make a advanced calc, with more features but both basic and advanced should exist, then do so by inheriting properties from base to advanced class.</p>
<pre><code class="language-java">
public class Adv extends Calc{
    public int mul(int a, int b){
        return a * b;
    }
}

// Main.java
class Main{
    public static void main(String args[]){
        Adv a = new Adv();
        int x = a.add(1,2);
        int y = a.mul(3,4);
    }
}
</code></pre>
<p><strong>TIP:</strong></p>
<p>U now have Main.java, Calc.java, <a href="http://Adv.java">Adv.java</a> and 3 .class files.Now, to run main program u just need only Main.java, Calc.class, Adv.class.</p>
<p>=&gt; In java, <strong>extends</strong> key word is used for inheritance. Adv is a calc !!</p>
<p>=&gt; In java, we can make multi level inheritance. But, multiple inheritance is not valid. Because if multiple parents have a function f() defined for them, and child calls obj.f(), it is ambigious for compiler for what f() to implement.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/c162d668-d9d3-4b5a-a1ea-18e22d32ea2b.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Method over riding</strong></p>
<p>Suppose parent class has add function where add(a,b) returns a+b. In child class u want to over ride parent add function and want add(a,b) to return a+b+5. Simply define similar function with modified functionality.</p>
<pre><code class="language-java">
class A{
    public int add(int x, int y){
        return x + y;
    }
}

class B extends A{
    public int add(int x, int y){
        return x + y + 5;
    }
}

class Main{
    public static void main(String args[]){
        B obj = new B();
        System.out.println(obj.add(2,3));
    }
}
</code></pre>
<h3><strong>Packages</strong></h3>
<p><strong>(modulariy, folder having multiple folders)</strong></p>
<p>Suppose the application structure is :</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/c9d5fb8e-2a04-41ea-b144-bacd9d920f0a.png" alt="" style="display:block;margin:0 auto" />

<p>As both <strong>AdvClass.java</strong> and <strong>Class.java</strong> are present in <strong>arithmetic</strong> folder, they have first line as <strong>package arithmetic;</strong></p>
<p>Now, every file is simply a class and utilising their methods require to create their objects, import the required classes from package and use em.</p>
<pre><code class="language-java">
import arithmetic.Calc;
import arithmetic.AdvCalc;

class Main{
    public static void main(String args[]){
        Calc c = new Calc();
        AdvCalc a = new AdvCalc();

        System.out.println(c.add(2,3));
        System.out.println(a.mul(5,6));
    }
}
</code></pre>
<p>Now, same method is used to import built-in packages for their classes.</p>
<pre><code class="language-java">
import java.util.ArrayList;

class Main{
    public static void main(String args[]){
        ArrayList a = new ArrayList();
    }
}
</code></pre>
<p><em><strong>So, What's the structure behind java.util.ArrayList ??</strong></em></p>
<p><em><strong>ArrayList class</strong></em> is present in <em><strong>util folder</strong></em>. And <em><strong>util folder</strong></em> is present in <em><strong>java folder.</strong></em></p>
<p><em><strong>Then, why aren't we importing System for println() ??</strong></em></p>
<p><em><strong>System.java</strong></em> file has the 1st line <em><strong>package java.lang;</strong></em></p>
<p>But every java file has <em><strong>import java.lang.*</strong></em> by default.</p>
<p><strong>OBSERVATION:</strong></p>
<p>In above <em><strong>Main.java</strong></em>, u can simply write <em><strong>import arithmetic.*;</strong></em></p>
<p><strong>ACCESS MODIFIERS:</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/4e94ec26-6679-4254-8c99-f7da53153945.png" alt="" style="display:block;margin:0 auto" />

<p>The pattern is:</p>
<p>Make <strong>class</strong> as <strong>public</strong> (Every file should have only 1 public class !!)</p>
<p>Most <strong>methods</strong> are <strong>public</strong>. when it comes to <strong>variables:</strong></p>
<p><strong>protected</strong> allows child class to use them, <strong>default</strong> allows only within package classes, but <strong>private</strong> allows only (methods, variables, ..) of same class only.</p>
<p><strong>Note:</strong></p>
<p>Ensure, everything should be either <strong>public / protected / private</strong> mostly.</p>
<p><strong>Default</strong> is not encouraged at all.</p>
<h3><strong>Polymorphism</strong></h3>
<p><strong>( behaving in many ways )</strong></p>
<p>Java has 2 types of polymorphism:</p>
<ol>
<li><p>Compile time polymorphism / Method over loading</p>
</li>
<li><p>Run time polymorphism / Method over riding</p>
</li>
</ol>
<p>In compile time, we can expect what method will execute at compile time. where as in run time, we can decide at run time only.</p>
<p>When talking about run time:</p>
<p><strong>CASE 1:</strong> we're already familiar with this !!</p>
<pre><code class="language-java">
class A{
    void show(){
        System.out.println("In A show");
    }
}

class B extends A{
}

class Main{
    public static void main(String args[]){
        B obj = new B();
        obj.show();

        // op = A show, reason = inheritance
    }
}
</code></pre>
<p>Now,</p>
<pre><code class="language-java">
class A{
    void show(){
        System.out.println("In A show");
    }
}

class B extends A{
    void show(){
        System.out.println("In B show");
    }
}

class Main{
    public static void main(String args[]){
        B obj = new B();
        obj.show();

        // op = B show, reason = over-riding
    }
}
</code></pre>
<p><strong>CASE 2:</strong> Storing another type of object in variable of type A</p>
<p>Also known as <strong>Dynamic method dispatch</strong></p>
<pre><code class="language-java">
class A{
    void show(){
        System.out.println("In A show");
    }
}

class B extends A{
    void show(){
        System.out.println("In B show");
    }
}

class C extends A{
    void show(){
        System.out.println("In C show");
    }
}

class Main{
    public static void main(String args[]){

        A obj = new A();
        obj.show(); // A show

        obj = new B();
        obj.show(); // B show

        obj = new C();
        obj.show(); // C show

    }
}
</code></pre>
<p>Even though obj variable is of type A, child methods will only work.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/44117871-1220-40a4-b05c-c46bac8452ff.png" alt="" style="display:block;margin:0 auto" />

<pre><code class="language-java">class A{
    void show(){
        System.out.println("In A show");
    }
}

class B{
    void show(){
        System.out.println("In B show");
    }
}

class Main{
    public static void main(String args[]){

        A obj = new B(); // Compile time error !!
        obj.show(); 
    }
}
</code></pre>
<p>Forget about run time, this is a compile time error now, because B is not a child of A. So, A obj can't allow other types to store.</p>
<p><strong>UP CASTING AND DOWN CASTING:</strong></p>
<pre><code class="language-java">
class A{
    public final void show1(){
        System.out.println("Hello from A");
    }
}
class B extends A{
    public void show2(){ 
        System.out.println("Hello from B");
    }
}
class Main{
    public static void main(String args[]){
        A obj = new B();
        obj.show1();    // Hello from A
        obj.show2();    // compile error !!
    }
}
</code></pre>
<p>For obj, object type is B but reference type is A. So, compiler checks for show1() from class A and executes. As show2() not present in A, the compiler will throw error.</p>
<p>But storing obj in B type variable gives error as A is not child of B.</p>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        A obj = new B();
        B obj1 = obj;
    }
}
</code></pre>
<p><strong>SOLUTION:</strong> DOWN CASTING.</p>
<p>( converting parent reference to child reference. )</p>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        A obj = new B();
        B obj1 = (B) obj;
        obj1.show2();   
    }
}
</code></pre>
<p>and UP CASTING (child reference to parent, already seen in dynamic dispatch)</p>
<pre><code class="language-java">A obj = new B();
</code></pre>
<h3><strong>final keyword:</strong></h3>
<p>final keyword can be used for a variable, method, class.</p>
<ol>
<li>final variable:</li>
</ol>
<p>In c++, Js to make constant variables, we use const keyword. Similarly in java, to make a constant variable, we use final keyword.</p>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        int a = 5;
        a = 10;     // valid

        final int b = 20;
        b = 30;     // error !!
    }
}
</code></pre>
<ol>
<li>final class:</li>
</ol>
<p>When u make a class final, no one can inherit it.</p>
<pre><code class="language-java">
final class A{
    
}
class B extends A{    // error !!

}
</code></pre>
<ol>
<li>final method:</li>
</ol>
<p>When u make a method final, no one can override it.</p>
<pre><code class="language-java">
class A{
    public final void show(){
        System.out.println("Hello from A");
    }
}

class B extends A{
    public void show(){ // error !!
        System.out.println("Hello from B");
    }
}
</code></pre>
<h3><strong>abstract keyword:</strong></h3>
<p>U can declare a method without defining it. Cause, different children may define it differently.</p>
<pre><code class="language-java">class A{
    public void show();
}
</code></pre>
<p>But above syntax throws error. To fix, make class A abstract and ur desired method show abstract.</p>
<pre><code class="language-java">
abstract class A{
    public abstract void show();
}

class B extends A{
    public void show(){
        System.out.println("Showing B");
    }
}

class C extends A{
    public void show(){
        System.out.println("Showing C");
    }
}
</code></pre>
<p><strong>Rules for abstract:</strong></p>
<ol>
<li><p>If parent class is abstract (has a abstract method), every child should ovverride it.</p>
</li>
<li><p>U cannot create an object of abstract class, u can only create child type objects, but referencing variable can be parent type.</p>
</li>
</ol>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        A obj1 = new A(); // in valid
        B obj2 = new B(); // valid
        A obj3 = new C(); // valid
    }
}
</code></pre>
<ol>
<li>A class can be abstract with only normal methods and zero abstract methods, literally can have any type of methods.</li>
</ol>
<h3><strong>Inner Class</strong></h3>
<p><strong>Suppose u have a class inside another class, how to access methods and variables of inner class ??</strong></p>
<pre><code class="language-java">
class A{
    public void show(){
        System.out.println("show from A");
    }

    class B{
        public void config(){
            System.out.println("config from B");
        }
    }
}

class Main{
    public static void main(String args[]){
        A obj1 = new A();
        A.B obj2 = obj1.new B();
        obj2.config();
    }
}
</code></pre>
<p><strong>step 1:</strong> Create obj of type A.</p>
<p><strong>step 2:</strong> Create obj of type B by:</p>
<p>Reference type: directly can't write B, so mention path A.B</p>
<p>Object type: Methods / variables / inner classes of A can only be accessed by object of A. so A. new B();</p>
<p><strong>What if class B is static ??</strong> ( no need to create B object )</p>
<pre><code class="language-java">A.B.config();
</code></pre>
<h3><strong>Anonymous Inner Class</strong></h3>
<p>An anonymous inner class in Java is a class without a name that you declare and instantiate in a single statement.</p>
<p>It is useful when you want to override a method or provide an implementation for a class or interface without creating a separate named class.</p>
<pre><code class="language-java">
class A {
    public void show() {
        System.out.println("show from A");
    }
}

// Now, if you want to override show(), you create another class:

class B extends A {
    public void show() {
        System.out.println("show from B");
    }
}

// This works, but you created a separate named class B.
</code></pre>
<p>Instead:</p>
<pre><code class="language-java">
class A{
    public void show(){
        System.out.println("show from A");
    }
}

class Main{
    public static void main(String args[]){
        A obj1 = new A(){
            public void show(){
                System.out.println("From anonymous class");
            }
        };
        
        A obj2 = new A();
        A obj3 = new A();

        obj1.show();    // from anonymous
        obj2.show();    // from A
        obj3.show();    // from A   
    }
}
</code></pre>
<h3><strong>Logical thing for u !!</strong></h3>
<pre><code class="language-java">
abstract class A{
    public abstract void show();
}

class B extends A{
    public void show(){
        System.out.println("show from B");
    }
}

class Main{
    public static void main(String args[]){
        A obj1 = new B();
        obj1.show();  
    }
}
</code></pre>
<p>can also be written as:</p>
<pre><code class="language-java">abstract class A{
    public abstract void show();
    public abstract void config();
}

class Main{
    public static void main(String args[]){
        A obj1 = new A(){
            public void show(){
                System.out.println("show from B");
            }
            public void config(){
                System.out.println("config from B");
            }
        };
        obj1.show();  
    }
}
</code></pre>
<h3><strong>Interface:</strong></h3>
<p>Suppose u made a class with only abstract methods and zero normal methods. Instead, we can make a interface.</p>
<pre><code class="language-java">abstract class A{
    public abstract void show();
    public abstract void config();
}
</code></pre>
<p><em><strong>Interface vs abstract class</strong></em></p>
<ol>
<li><p>Interface is not a class.</p>
</li>
<li><p>By default, every method in interface is <strong>public abstract.</strong></p>
</li>
<li><p>Similar to abstract class, we can't create object of interface, but we can use interface as reference type.</p>
</li>
<li><p>abstract class : extends :: interface : implements [ class - interface ]</p>
</li>
<li><p>By default, variables in interface are static and final, so initialise when decalring them.</p>
</li>
<li><p>Unlike abstract class, u can implement multiple interfaces.</p>
</li>
<li><p>Class B implements interface P, Q, ....... But interface X extends interface Y (inheritance in interface). So child interface gets abstract methods of parent interface, and object of child interface should implement all methods of parent interface.</p>
</li>
</ol>
<pre><code class="language-java">
interface A{
    int version = 6.2;
    String model = "java";
    void show();
    void config();
}

class B implements A{
    public void show(){
        System.out.println("Showing in B");
    }

    public void config(){
        System.out.println("config in B");
    }
}

class Main{
    public static void main(String args[]){
        A obj = new B();
        obj.show();
        obj.config();
    }
}
</code></pre>
<pre><code class="language-java">
interface A{
    void run();
}

interface B{
    void fly();
}

class C implements A, B{
    public void run(){
        System.out.println("running in C");
    }

    public void fly(){
        System.out.println("flying in C");
    }
}

interface D extends B{
    void swim();
}
</code></pre>
<ol>
<li>Suppose there exists interface A and class B and B implements A. U create <strong>A obj = new B();</strong> <em>Then, obj can only implement methods of A but not B (seen in downcasting)</em></li>
</ol>
<pre><code class="language-java">
interface A{
    void show();
    void config();
}

interface X{
    void run();
}

class B implements A, X{
    public void show(){
        System.out.println("Showing in B");
    }

    public void config(){
        System.out.println("config in B");
    }

    public void run(){
        System.out.println("running in B");
    }
}

class Main{
    public static void main(String args[]){
        A obj = new B();
        obj.show();
        obj.config();
        obj.run();        // invalid, can only implement A methods

        X obj1 = new B();
        obj1.run();       // valid
    }
}
</code></pre>
<ol>
<li><p><em><strong>WHAT'S THE NEED OF INTERFACE ??</strong></em></p>
</li>
<li><p>Suppose u are a sde in a company, got laptop for coding.</p>
</li>
</ol>
<pre><code class="language-java">
class Laptop{
    void code(){
        System.out.println("coding in laptop");
    }
}

class Sde{
    void devApp(Laptop l){
        l.code();
    }
}

class Main{
    public static void main(String args[]){
        Sde raj = new Sde();
        Laptop l = new Laptop();
        raj.devApp(l);
    }
}
</code></pre>
<ol>
<li>Suppose laptop got extinct, and u were given desktop to code, but devApp() of Sde can only take Laptop as input ?? <em><strong>Solution: abstract class</strong></em></li>
</ol>
<pre><code class="language-java">
abstract class Computer{
    abstract void code();
}

class Laptop extends Computer{
    void code(){
        System.out.println("coding in laptop");
    }
}

class Desktop extends Computer{
    void code(){
        System.out.println("coding in desktop");
    }
}

class Sde{
    void devApp(Computer c){
        c.code();
    }
}

class Main{
    public static void main(String args[]){
        Sde raj = new Sde();
        Laptop l = new Laptop();
        Desktop d = new Desktop();

        raj.devApp(l);
        raj.devApp(d);
    }
}
</code></pre>
<ol>
<li>Now, a cleaner implementation is interface. So, interface helps in abstracting the working logic of different components but helps to use different methods under same reference type (here Computer).</li>
</ol>
<h3><strong>Enums</strong></h3>
<p>In Java, an <code>enum</code> (enumeration) is a special class used to define a fixed set of named constants. It improves type safety and readability by restricting a variable to one of the predefined values.</p>
<pre><code class="language-java">
enum Status{
    Working, Failed, Blocked
}

public class Main{
    public static void main(String args[]){
        Status s = Status.Blocked;
        System.out.println(s);  // Blocked
        System.out.println(s.ordinal());    // 2 (index)

        Status[] a = Status.values();
        for(Status st : a){
            System.out.print(st + " " + st.ordinal() + "\n");
        }
    }
}
</code></pre>
<p><strong>Enums in If else block:</strong></p>
<pre><code class="language-java">enum Status{
    Working, Failed, Blocked
}

public class Main{
    public static void main(String args[]){
        Status s = Status.Blocked;
        System.out.println(s); 

        if(s == Status.Working) System.out.println("Alive");
        else if(s == Status.Failed) System.out.println("Dead");
        else System.out.println("Fix");
    }
}
</code></pre>
<p><strong>Enums in switch case:</strong></p>
<pre><code class="language-java">enum Status{
    Working, Failed, Blocked
}

public class Main{
    public static void main(String args[]){
        Status s = Status.Blocked;
        System.out.println(s); 

        int points = 0;
        switch(s){
            case Working: points += 5; break;
            case Failed: points = 0; break;
            case Blocked: points -= 2; break;
            default: System.out.println("invalid"); 
        }
        System.out.println(points);
    }
}
</code></pre>
<ol>
<li><p>Enum can't extend a class, and a class extend a enum. But enum can have fields, constructors and methods similar to a class. Enum can implement multiple interfaces.</p>
</li>
<li><p><strong>enum</strong> extends <strong>java.lang.Enum</strong></p>
</li>
</ol>
<pre><code class="language-java">enum Laptop{
    macbook(1000), thinkpad(2000), pavilion(3000);
    private int price;
    private Laptop(){price = 500;}
    private Laptop(int p){price = p;}
    public int getPrice(){return price;}
}

class Main{
    public static void main(String args[]){
        Laptop l = Laptop.pavilion;
        System.out.println(l.getPrice());   // 3000
        for(Laptop p : Laptop.values()){
            System.out.print(p + " " + p.getPrice() + "\n");
        }
    }
}
</code></pre>
<h3><strong>Functional Interface</strong></h3>
<p>A functional interface in Java is an interface that contains exactly one abstract method. It can have multiple <code>default</code> and <code>static</code> methods.</p>
<p>It is also called a SAM (Single Abstract Method) interface.</p>
<pre><code class="language-java">@FunctionalInterface
interface Computer {
    void code();
}

class Main {
    public static void main(String[] args) {
        Computer c = new Computer() {
            public void code() {
                System.out.println("Coding...");
            }
        };

        c.code();    // Coding
    }
}
</code></pre>
<p><strong>LAMBDA EXPRESSIONS (A syntactic sugar)</strong></p>
<pre><code class="language-java">
@FunctionalInterface
interface Computer {
    void code();
}

class Main {
    public static void main(String[] args) {
        Computer c = () -&gt; System.out.println("Coding...");

        c.code();
    }
}
</code></pre>
<p><strong>Lambda Expressions with parameters and return value</strong></p>
<pre><code class="language-java">@FunctionalInterface
interface Calculator {
    int operate(int a, int b);
}

class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -&gt; a + b;
        Calculator multiply = (a, b) -&gt; a * b;

        System.out.println(add.operate(10, 20));
        System.out.println(multiply.operate(10, 20));
    }
}
</code></pre>
<p><em><strong>Notice something important:</strong></em> the same interface can have different implementations through different lambda expressions.</p>
]]></content:encoded></item><item><title><![CDATA[Core Java ]]></title><description><![CDATA["Suppose ur application had a 1000 files, but only 1 file gets executed. That file might depend on all other files. That file should have a main function."]]></description><link>https://block-chain.hashnode.dev/core-java</link><guid isPermaLink="true">https://block-chain.hashnode.dev/core-java</guid><dc:creator><![CDATA[Rajesh Gurajala]]></dc:creator><pubDate>Wed, 14 Oct 2026 07:12:39 GMT</pubDate><content:encoded><![CDATA[<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/18e7ea80-06fc-4edd-9568-8162afa4a123.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/ffcef499-1c13-4910-bf90-fc0f62d44762.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>BASIC JAVA PROGRAM:</strong></h3>
<p>"Suppose ur application had a 1000 files, but only 1 file gets executed. That file might depend on all other files. That file should have a main function."</p>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){
        int a = 5, b = 3;
        System.out.println(a+b);
    }
}
</code></pre>
<h3><strong>DATA TYPES:</strong></h3>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){
        int a = 5, b = 3;          // 4 bytes
        long l = 123456l;          // 8 bytes
        float f = 1.2345f;         // 4 bytes
        double d = 1.2345678;      // 8 bytes, default

        char c = 'h';              // 2 bytes
        boolean eligible = true;
    }
}
</code></pre>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){
        int a = 0b101;     // binary
        int b = 0x7E;      // hexa decimal
        int c = 1_00_000;  // readable big numbers
        System.out.printf("%d %d %d \n",a,b,c);    // 5 126 100000

        float  f = 1.2367f;
        double d = 12e5;
        System.out.printf("%.3f %f \n", f, d); //1.237 1200000.00

        char x = 'a';
        x+=2; x--;
        System.out.printf("%c \n", x); // b
    }
}
</code></pre>
<h3><strong>TYPE CONVERSION AND CASTING:</strong></h3>
<p>implicit conversion means storing small value in big container</p>
<p>Explicit conversion is also known as type casting.</p>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){

        // implicit conversion
        byte b = 127;
        int c = b;      
   
        // explicit conversion
        int d  = 57;
        byte e = (byte) d;  // 57
        byte p = (byte) 300; // 300 % 256
        // byte e = d, f = 300;   lossy conversion error

        float f = 5.7f;
        int g = (int) f;    // 5
    }
}
</code></pre>
<h3><strong>CONDITIONAL STATEMENTS</strong></h3>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){
        int marks = 86;
        char grade = '-';

        if(marks &gt;= 90) grade = 'A';
        else if(marks &gt;= 70) grade = 'B';
        else grade = 'C';

        System.out.println(grade);

        // TERNARY OPERATORS
        int salary = 34000;
        int bonus = (salary &gt; 20000) ? 6000 : 2000;

        // SWITCH STATEMENT
        
        int month = 15;
        switch(month){
            case 1:
                System.out.println("Republic Day");
                break;
            case 8:
                System.out.println("Independence Day");
                break;
            case 10:
                System.out.println("Gandhi Jayanti");
                break;
            default:
                System.out.println("No holiday");
        }
    }
}
</code></pre>
<h3><strong>LOOPS</strong></h3>
<pre><code class="language-java">
class Hello{
    public static void main(String args[]){

        // WHILE LOOP
        int i = 0;
        while(i&lt;10){
            System.out.printf("Iteration %d \n", i);
            i++;
        }

        // FOR LOOP
        int total = 0;
        for(int j=0; j&lt;5; j++) total += 10;

        // DO-WHILE LOOP
        int k = 0;
        do{
            System.out.printf("Iteration %d \n", k);
            k++;
        }while(k&lt;8);
    }
}
</code></pre>
<h3><strong>CLASSES AND OBJECTS</strong></h3>
<pre><code class="language-java">
class Calculator{
    int id; String country;

    public Calculator(){
        id = 1;
        country = "";
    }

    public Calculator(string c){
        country = c;
    }

    public String greet(){
        return "Hello, user !!";
    }

    public int add(int a, int b){
        return a + b;
    }
}

class Hello{
    public static void main(String args[]){
        int x = 56, y = 19;
        Calculator c = new Calculator();

        String msg = c.greet();
        System.out.println(msg);

        int result = c.add(x, y);
        System.out.println(result);

        System.out.println(c.id);
    }
}
</code></pre>
<ol>
<li><strong>METHOD OVER LOADING:</strong></li>
</ol>
<pre><code class="language-java">
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;
    }
    public double add(double a, double b, double c){
        return a + b + c;
    }
}
</code></pre>
<h3><strong>ARRAYS</strong></h3>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        // u should some how mention array size initially.

        // 1d array
        int arr1[] = {11,28,36,40};
        int arr2[] = new int[5];

        for(int i=0; i&lt;5; i++) arr2[i] = 4 * i;
        System.out.println(arr2[3]);
        for(int x: arr2) System.out.println(x);

        // multi dimensional array
        int nums1[][] = new int[2][3];
        int nums2[][] = {{0,1,2}, {1,2,3}};

        System.out.println(nums2[1][2]);
        for(int temp[]: nums2){
            for(int x: temp) System.out.println(x);
        }

        // jagged array =&gt; variable column size
        int nums[][] = new int[3][];
        nums[0] = new int[2];
        nums[1] = new int[8];
        nums[2] = new int[5];

        for(int i=0; i&lt;nums.length; i++){
            for(int j=0; j&lt;nums[i].length; j++){
                nums[i][j] = i + j;
            }
        }

    }
}
</code></pre>
<pre><code class="language-java">
class Student{
    String name;
    int id, marks;
}

class Hello{
    public static void main(String args[]){
        Student s1 = new Student();
        s1.name = "Alex";
        s1.id = 1;
        s1.marks = 99;

        Student s2 = new Student();
        s2.name = "Boris";
        s2.id = 2;
        s2.marks = 53;

        Student s3 = new Student();
        s3.name = "Charles";
        s3.id = 3;
        s3.marks = 77;

        Student students[] = new Student[3];
        students[0] = s1;
        students[1] = s2;
        students[2] = s3;

        for(Student s: students) System.out.printf("%d ", s.marks);
    }
}
</code></pre>
<h3><strong>STRINGS</strong></h3>
<p>String is not a primitive data type in java unlike others like int, float, char, bool ..</p>
<p>String is a class, so s in String is a capital letter.</p>
<p>String s = "java"; is equivalent to String s = new String("java");</p>
<pre><code class="language-java">class Main{
    public static void main(String args[]){
        String s = "hello";
        s = s.concat(" user");
        System.out.println(s);  // hello user
    }
}
</code></pre>
<p><em><strong>How strings objects are created in heap memory ??</strong></em></p>
<p>Suppose the code is :</p>
<pre><code class="language-java">class Main{
    public static void main(String args[]){
        String name = "navin";
        s1 = "Navin";
        s2 = "Navin";
    }
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/cc1dc33f-d1c3-4b65-a66f-fd1c9aa4db68.png" alt="" style="display:block;margin:0 auto" />

<p>Strings are immutable (cannot be changed) by default. which means for suppose u do <em><strong>name = name + "reddy":</strong></em></p>
<p>The string <em><strong>"navin"</strong></em> stays as it is at address 101, a new string <em><strong>"navin reddy"</strong></em> created at new address and name points to new address.</p>
<p>Now, the old string <em><strong>"navin"</strong></em> becomes eligible for garbage collection.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/59fd63a7-d89f-4683-947c-bd782915bd3c.png" alt="" style="display:block;margin:0 auto" />

<p>There are 2 ways to make mutable strings: StringBuilder and StringBuffer.</p>
<h3><strong>STRING BUILDER</strong></h3>
<pre><code class="language-java">
class Main{
    public static void main(String args[]){
        StringBuffer sbf = new StringBuffer("Alexo cocoa");
        sbf.append(" fields");  // "Alexo cocoa fields"
        sbf.delete(5, 11);      // "Alexo fields"
        sbf.insert(0, "Java ");  // "Java Alexo fields"
        System.out.println(sbf.substring(0, 6)); // "Java A"

        String s = sbf.toString();

    }
}
</code></pre>
<p><strong>Q:</strong> StringBuffer vs StringBuilder ??</p>
<p><strong>A:</strong> StringBuffer is thread safe but StringBuilder isn't. Rest of pre defined methods are same for both.</p>
<p><em><strong><mark>Complete java oops from</mark></strong></em> <a href="https://block-chain.hashnode.dev/core-java-2-oops"><em><strong><mark>https://block-chain.hashnode.dev/core-java-2-oops</mark></strong></em></a> <em><strong><mark>for better understanding of further topics.</mark></strong></em></p>
<h3><strong>EXCEPTIONS</strong></h3>
<p>There are 3 types of errors. Compile time, run time, logical (seen in testing).</p>
<p>Run time errors are exceptions. And we shouldn't stop at a run time error, and do exception handling.</p>
<p><strong>try catch block</strong></p>
<pre><code class="language-java">
class Main {
    public static void main(String[] args) {
        int i = 2;
        int result = 0;

        try{
            // critical section of code
            result = 10 / i;
        }catch(Exception e){
            System.out.println("Something went wrong..");
            System.out.println(e);
        }

        System.out.println(result);
    }
}
</code></pre>
<p><strong>Note:</strong></p>
<ol>
<li>catch will only implement only if exception occurs, rest will be implemented in all cases.</li>
<li>If i=0 output: Something went wrong 0, else it simply prints result.</li>
</ol>
<pre><code class="language-java">
class Main {
    public static void main(String[] args) {
        int i = 2;
        int result = 0;
        int nums[] = new int[5];

        try{
            // critical section of code
            result = 10 / i;
            result += nums[5];

        }catch(ArithmeticException e){
            System.out.println("can't divide by zero");
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Array index out of bounds");
        }catch(Exception e){
            System.out.println("Unknown error occured");
        }

        System.out.println(result);
    }
}
</code></pre>
<p><strong>throw keyword</strong></p>
<p><em><strong>Q: Suppose if result becomes zero, generate me a exception and reset the value to 10.</strong></em></p>
<pre><code class="language-java">
class Main {
    public static void main(String[] args) {
        int i = 0;
        int result = 0;

        try{
            result = 10 / i;
            if(result == 0) throw new ArithmeticException("result became zero");
        }catch(ArithmeticException e){
            result = 10;
            System.out.println(e);    // result became zero
        }
        System.out.println(result);
    }
}
</code></pre>
<p><strong>make a custom Exception class</strong></p>
<pre><code class="language-java">
class JohnException extends Exception{
    public JohnException(String s){
        super(s);
    }
}

public class Main {
    public static void main(String[] args) {
        int i = 20;
        int result = 0;

        try{
            result = 10 / i;
            if(result == 0) throw new JohnException("result became zero");
        }catch(JohnException e){
            result = 10;
            System.out.println(e);
        }
        System.out.println(result);
    }
}
</code></pre>
<h3><strong>HOW TO TAKE INPUT FROM USER ??</strong></h3>
<p>Older approach:</p>
<pre><code class="language-java">
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException{
        // InputStreamReader object needs InputStream object as parameter
        // Instead let's pass System.in 
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(in);

        System.out.println("Enter a number");
        int num = Integer.parseInt(bf.readLine());
        System.out.println(num);

    }
}
</code></pre>
<p>Current approach:</p>
<pre><code class="language-java">
import java.util.Scanner;

public class Main {
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int num = sc.nextInt();
        System.out.println(num);

    }
}
</code></pre>
<p><strong>finally keyword</strong></p>
<p>Consider this scenario**:**</p>
<pre><code class="language-java">
public class Main {
    public static void main(String[] args){
        int i = 0, result = 0;
        try{
            result = 18 / i;
            System.out.println("Bye");
        }catch(Exception e){
            System.out.println("Cannot divide by zero");
        }
    }
}
</code></pre>
<p>Here, calculating result is critical step. So at the result calculation, if an Exception is thrown (if i == 0), rest of code under result line will never be executed and catch block or below code will be executed.</p>
<p><strong>Solution:</strong></p>
<pre><code class="language-java">
public class Main {
    public static void main(String[] args){
        int i = 0, result = 0;
        try{
            result = 18 / i;
        }catch(Exception e){
            System.out.println("Cannot divide by zero");
        }finally{
            System.out.println("Bye");
        }
    }
}
</code></pre>
<p>Now Bye line will be executed, irrespective of exception.</p>
<h3><strong>THREADS</strong></h3>
<p>A thread is the smallest unit of CPU execution within a process. It represents a sequence of instructions that the CPU can execute.</p>
<p><strong>In sight:</strong></p>
<p>Every process (a single program) is divided into threads. And irrespective of how many threads u have, cpu scheduler allows 1 thread of application A at a time to execute, and then 1 thread of application B to execute.</p>
<p>Nowadays, we got multi core CPU's which can implement multiple threads at same time.</p>
<p><strong>Consider this program:</strong></p>
<pre><code class="language-java">
class A{
    void show(){
        for(int i=0; i&lt;100; i++) System.out.println("Hi");
    }
}

class B{
    void show(){
        for(int i=0; i&lt;100; i++) System.out.println("Hello");
    }
}

public class Main {
    public static void main(String[] args){
        A obj1 = new A();
        B obj2 = new B();
        obj1.show();
        obj2.show();
    }
}
</code></pre>
<p>Hi will be printed 100 times. Only then, Hello will be printed 100 times. What if we want parallel execution of <em><strong>obj1.show()</strong></em> and <em><strong>obj2.show() ??</strong></em></p>
<p><em><strong>Approach:</strong></em></p>
<pre><code class="language-java">
class A extends Thread{
    public void run(){
        for(int i=0; i&lt;100; i++){
            System.out.println("Hi");
        }
    }
}

class B extends Thread{
    public void run(){
        for(int i=0; i&lt;100; i++){
            System.out.println("Hello");
        }
    }
}

public class Main {
    public static void main(String[] args){
        A obj1 = new A();
        B obj2 = new B();
        obj1.start();
        obj2.start();
    }
}
</code></pre>
<ol>
<li>Extend thread class to class A and class B to utilise benefits of threads for those methods.</li>
<li>After extending, the object should call start(), and that start() will implement run() function of that class with threads.</li>
</ol>
<p><em><strong>Another Approach to utilise threads:</strong></em></p>
<p>Runnable is parent class of Thread. So extend Runnable class, create the objects of A, B and pass them as parameters to Thread objects.</p>
<pre><code class="language-java">
class A implements Runnable{
    public void run(){
        for(int i=0; i&lt;100; i++){
            System.out.println("Hi");
        }
    }
}

class B implements Runnable{
    public void run(){
        for(int i=0; i&lt;100; i++){
            System.out.println("Hello");
        }
    }
}

public class Main {
    public static void main(String[] args){
        Runnable obj1 = new A();
        Runnable obj2 = new B();

        Thread t1 = new Thread(obj1);
        Thread t2 = new Thread(obj2);

        t1.start();
        t2.start();
    }
}
</code></pre>
<h3><strong>COLLECTIONS</strong></h3>
<p>In this topic, we have 3 topics. Collection (Interface), Collections (Class), Collection API.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68496e2b746e5e01f89ed801/e3dd4384-e5e5-4c17-9edf-eff1b4916285.png" alt="" style="display:block;margin:0 auto" />

<pre><code class="language-java">import java.util.Collection;
import java.util.ArrayList;
public class Main{
    public static void main(String args[]){
        Collection&lt;Integer&gt; nums = new ArrayList&lt;Integer&gt;();
        nums.add(6);
        nums.add(10);
        System.out.println(nums);    // [6, 10]
    }
}
</code></pre>
<p><strong>Collection</strong> doesn't support Indexing. So, let us use <strong>List.</strong></p>
<pre><code class="language-java">import java.util.List;
import java.util.ArrayList;
public class Main{
    public static void main(String args[]){
        List&lt;Integer&gt; nums = new ArrayList&lt;Integer&gt;();
        nums.add(6);
        nums.add(10);
        System.out.println(nums.get(1));    // 10
    }
}
</code></pre>
<p>Let us store <strong>Set</strong> to store unique values.</p>
<pre><code class="language-java">import java.util.Set;
import java.util.HashSet;
public class Main{
    public static void main(String args[]){
        Set&lt;Integer&gt; nums = new HashSet&lt;Integer&gt;();
        nums.add(66);
        nums.add(10);
        System.out.println(nums);        // [66, 10]
    }
}
</code></pre>
<p>Let us use <strong>Map</strong> for storing key, value pairs.</p>
<pre><code class="language-java">
import java.util.Map;
import java.util.HashMap;

public class Main{
    public static void main(String args[]){
        Map&lt;String, Integer&gt; m = new HashMap&lt;String, Integer&gt;();
        m.put("raj", 100);
        m.put("alex", 45);
        m.put("david", 39);

        System.out.println(m);  // {entire map}
        System.out.println(m.get("david"));
        m.put("alex", 76);  // update

        System.out.println(m.keySet()); // {set of all keys}
        for(String key: m.keySet()){
            System.out.println(key + " " + m.get(key));
        }
    }
}
</code></pre>
<p><strong>Sorting</strong></p>
<ol>
<li>Ascending sorting of list</li>
</ol>
<pre><code class="language-java">import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Main{
    public static void main(String args[]){
        List&lt;Integer&gt; l = new ArrayList&lt;Integer&gt;();
        l.add(34);
        l.add(76);
        l.add(23);
        l.add(12);
        l.add(100);

        System.out.println(l);  // [34, 76, 23, 12, 100]
        Collections.sort(l);
        System.out.println(l);  // asc sorted list
    }
}
</code></pre>
<ol start="2">
<li>Custom sorting logic with comaparator</li>
</ol>
<pre><code class="language-java">import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main{
    public static void main(String args[]){

        Comparator&lt;Integer&gt; com = new Comparator&lt;Integer&gt;(){
            public int compare(Integer i, Integer j){
                int result = (i % 10 &gt; j % 10) ? 1 : -1;    // yes / no
                return result;
            }
        };

        List&lt;Integer&gt; arr = new ArrayList&lt;Integer&gt;(List.of(23, 67, 100, 89));
        Collections.sort(arr, com);
        System.out.println(arr);


    }
}
</code></pre>
]]></content:encoded></item></channel></rss>