Reading view

There are new articles available, click to refresh the page.

Git Reset – A tool to correct your (commited) mistakes.

Terminologies

  1. Work Tree: Your working tree are the files that you are currently working on. Your local folder.
  2. Git Index/Staging Area: The git “index” is where you place files you want commit to the git repository. The index is also known as cache, directory cache, current directory cache, staging area, staged files. Before you “commit” (checking) files to the git repository, you need to first place the files in the git “index”.

The index is not the working directory, you can type a command such as git status, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename command).

In simple words, git reset is to correct your mistakes. Consider a scenario, where you have mistakenly did some wrong code and commited it too. Everything started to fall apart. Now you want to go back to the previous stable state (or previous commit). This is the scenario, where git reset helps you. In this blog post you will understand the usage of git reset in 3 different ways.

Visualization of Working Folder, Staging, Local Repository

Git Reset

In general, git reset’s function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. Git reset helps you in two broad categories.

  1. To remove changes from staging area.
  2. To undo commits at repository level.

Scenario #1 : To remove changes from staging area

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: sample.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add sample.txt

Checking the stage area

Now the file is been added to the staging area (but not commited). But now you realize that you have a wrong content inside it. So inorder to remove it from the staging area, you just need to execute git reset <filename>.

Now you can see that the file is been moved from the staging area to working directory. and the contents inside the file is preserved.

Some of the possible scenarios,

  1. If there are many files in the staged area, then you can simply use git reset.
  2. There is also another command to unstage files, git restore. git restore --staged .

Scenario #2 – To Undo commits at repository level

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: file.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add file1.txt
  6. Create a text file (eg: file2.txt)
  7. Add some content inside it.
  8. Add the file to the staging area. git add file2.txt
  9. Create a text file (eg: file3.txt)
  10. Add some content inside it.
  11. Add the file to the staging area. git add file3.txt
image.png

There are 3 modes to reset a commit from the local reposity.

Once any file or folder is committed, we won’t have the concept of resetting the file. It will be resetting the commits only.

All these 3 modes, will move the HEAD to a specified commit, and all the remaining recent commits will be removed. The mode will decide whether these changes are going to remove from staging area and working directory or not.

Mixed Method (Default)

Command: git reset --mixed <commit-id>

Functionality: It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status.

Use this when you realize you made some bad commits, but you want to keep all the work you’ve done so you can fix it up and recommit. In order to commit, you’ll have to add files to the index again (git add …).

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --mixed 002aa06

Now we can see the HEAD moved to the commit which we specified. And the file3.txt is removed from the local repository and staging.

But the contents inside the file is preserved in the working directory. We can check using the git status to see the file under Untracked files.

Soft Method

Command: git reset --soft <commit-id>

Functionality: All your files are intact as with –mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you’ve made some bad commits, but the work’s all good all you need to do is recommit it differently.

The index is untouched, so you can commit immediately if you want the resulting commit will have all the same content as where you were before you reset.

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --soft f8d7c74

Now we can see the HEAD moved to the commit which we specified. And the file2.txt is removed from the commit, but staging.

The contents in the file are preserved and its already present in the staging. We can check this using the git status to see the file under Added files.

Hard Method

Command: git reset --hard <commit-id>

Functionality: This is the easiest to understand, probably. All of your local changes get clobbered.

One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don’t change the branch but get rid of all local changes.

The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

Hands On: Our working directory will look like this,

We can add one more commit (so that we will have some commits to test).

so now we have 2 files in commit, and one file in working directory (untracked file – file3.txt). We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --hard f8d7c74

Now we can see the HEAD moved to the commit which we specified. Also the file2.txt is been removed from the local repository, staging and the working directory.

It removed the files that were present in the commit. This is the one that can really make you lose work, because it modifies your work tree.

The Strange Notation

When you are searching for the working for git reset, you might noticed people using HEAD^ and HEAD~1. These are just the shorthand or specifying commits, without having to use a hash name like f8d7c74.

It’s fully documented in the “specifying revisions” section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things

  • HEAD~ is short for HEAD~1 and means the commit’s first parent. HEAD~2 means the commit’s first parent’s first parent. Think of HEAD~n as “n commits before HEAD” or “the nth generation ancestor of HEAD”.

  • HEAD^ (or HEAD^1) also means the commit’s first parent. HEAD^2 means the commit’s second parent. Remember, a normal merge commit has two parents – the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).

  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

In this blog post we understood the working of different ways to reset a commit. I am having one question for you. When we are resetting to a different commit, (i.e) pointing the head to a different commit, what will happen to the removed commits ? Is there any way to go back to it ?

Java Methods

Method is block of code or collections(group) of statement that perform a specific task.All method in java belong to a class.method similar to function and expose the behavior of objects.which only runs when it is called.

method must have return type weather void or return data like int , string...etc

Syntax

AccessModifer returntype methodName(Parameter List)
{
// method body 
}

Access Modifiers:-

=> public, private, protected, default – controls method access

Method overloading:

Same class same method name , different parameters
(compile-time polymorphism)

Method Overriding:-

Different class (extend(is an-relationship) )parent and child relationship and Redefining-parent method in child class( same method name and parameters)

Types of methods:

  • Static method
  • Instance method
  • Construtor(special method)

Why use methods?
To reuse code: define the code once , and use it many times

without method

public class Test_Withoutmethod {

    public static void main(String[] args) {

        int a =5 , b=3;
        int sum = a+b;
        System.out.println("Sum: "+ sum);

        int x=10, y=2;
        int result =x*y;
        System.out.println("Sum: "+result);
    }

}

with method:


public class Test_withMethod {


    static  void  add(int a , int b)
    {
        int sum =a+b;
        System.out.println("Sum: "+ sum);
    }
public static int minFunction(int n1, int n2)
{
    int min;
//  System.out.println("Min value is : "+min); you can not initialize local variable  ,when printing came compile time error.

    if (n1>n2)
    {
        min =n2;
    System.out.println("Min:n2 is : "+min);
    return min;
    }
            else
            {   
    min=n1;
    System.out.println("Min:n1 is : "+min);
    return min;
            }
    }


    public static void main(String[] args) {

   add(5,3);// callmethod 
   add(10,2); // reuse method 
   minFunction(1,2);
    }

}

Method Defining and Calling with return types and void :-


// method  defining and  calling
public class Method_Example1 {

    public static void main(String[] args) {
  int total= add(210,210);
  System.out.println(" Return value example => Total: 210+210 = "+total);
  twlethMark(550);
    }

    //  method using to void example 
    public static void twlethMark(int mark)
    {
        if(mark>580)
        {
            System.out.println("Rank:A1");
        }
        else if (mark >=550)
        {
            System.out.println("Rank:A2");

        }
        else
        {
            System.out.println("Rank:A3");
        }

    }

    public static int add (int n1,int n2)
    {
        int total = n1+n2;

        return total;


    }

}


swapping values inside method:-

public class Method_SwappingValue {

public static void main(String[] args) {

    int a =30;
    int b =45;
    System.out.println("Before swapping, a =" +a+ " and b ="+b);
    swapValueinFunction(a,b);
    System.out.println("\n Now ,Before and After swapping values will be same here");
    System.out.println("After swapping, a = "+a + ", b = "+b);
}

public static void swapValueinFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = "+a + ", b = "+b);

int c =a;  // a(30) value moved to c (),now a (empty) is  empty
a= b;  // b(45) value moved  a, because a is empty, now a is 45
b=c;  // c(30)  value   moved  to b(empty) , now b is 30
System.out.println("After swapping(Inside), a = "+a + ", b = "+b);



}

}

Method&Calling_Passing_Parameters

public class Method_Passing_Parameters {

    static String letter = " open the letter\n \n"
            + "To Smantatha,\n"
            + "\n"
            + "You are my heartbeat 💓\n"
            + "My heart is not beeping... because you're not near to hear it.\n"
            + "Come close and make it beep again.\n"
            + "Make my heart lovable with your presence. ❤️\n"
            + "\n"
            + "Forever yours,\n"
            + "Prasanth 💌";

    public static void main(String[] args) {
     sendLetter("prasanth","Java Developer"); //passing string parameter
    }

 static void readLetter(String reader,String career,int age) {
        System.out.println(reader+" read the letter from prasanth:");
        System.out.println(reader + letter);
    }

static void sendLetter(String sender,String career) {

System.out.println(sender+" sent a letter to samantha");    
//System.out.println("Message: "+letter);
System.out.println();
readLetter("samantha","Actress",35);

    }

}

Example: method using to return value and void

public class JavaReturnandVoid{

    public static void main(String[] args) {
        int Balance =myAccountBalance(100);
System.out.println("Balance: "+Balance);
System.out.println("\n");
samInfo(25,55);
char [] data=samInfo(25,55,5.9);
System.out.println(data);


    }

static void samInfo(int i, int j) {

    System.out.println("Age: "+i);
    System.out.println("Weight: "+j);


    }
// differen  paremeter if you have ,  how to return  ?
static char[] samInfo(int i, int j, double d) {
    System.out.println("differen  paremeter if you have ?  how to return ");
    String data = "Age:" +i+", weight"+j+", Height:"+d;
    return data.toCharArray(); //convert to char[]

}

static int myAccountBalance(int AccountBalnce ) {

    int myPurse = 1;
    int Balance =myPurse+AccountBalnce;
        return Balance;
    }


}

<u>How to different way return the value:-</u>

public class MethodReturnExample {

public static void main(String[] args) {
    // 1. calling void method 
     greet();
     // 2. calling int return method
       int sum=add(210,210);
       System.out.println("sum: "+ sum);
       //3.calling  String return method
       String message=getMessage("Prasanth");
       System.out.println(message);
       //4. calling method that returns both and string
          Object[] data=getUserinfo();
          System.out.println("Id "+ data[0]);
          System.out.println("Name "+ data[1]);


}

// 1.void method - just print
static void greet() {
System.out.println("Hello ,Welcome to java ");
}
//2. return int

static int add(int num1,int num2)
{
int sum= num1+num2;

return sum;

}
//3. return string

static String getMessage(String name)
{
return "Hi My name is " + name +" i am Javadeveloper";
}

//4. return int and string using object[] or Array
static Object[] getUserinfo()
{
int id =101;
String name ="Hellow";

return new Object[] {id,name};

}

}



<u> Important Return Type Scenarios</u>

int return 5 + 3; Return a number
String return "Hello"; Return a message or text
boolean return a > b; Return true/false
char[] return name.toCharArray(); Return letters from a string
Array return new int[]{1,2,3}; Return multiple numbers
Object return new Person(...); Return class object
void System.out.println("Hi"); Just perform action, no return


// method ovlerloading and overriding we will see Java Oops concept


<u>Method&Block Scope:-</u>

public class MethodandBlock_Scope_Example {

public static void main(String[] args) {

//System.out.println(x);
int a =100;
System.out.println(a);

    //method Scope: x is visible any where inside main method
    //Anywhere in the method
    int x =100;
    System.out.println("x in method:"+x);

    if(x>50)
    {
        //Block Scope: y is only visible inside this if block
        //only inside the block
        int y =200;
        System.out.println("Y in if block: "+y);

    }
    // try to access y outside the block
//  System.out.println("y is outside if block: "+y); //error not visible out of block


}

}



<u>Java Recursion:-</u>



package java_Method;

// Factorial Using Recursion
public class Recursion_Example {

int fact(int n)
{
    int result;

    if (n==1)

        return 1;
        result =fact(n-1) * n;

        /*fact(3-1) *3 -> fact (2) * 3  becomes -> (fact(1) *2)*3)
         * fact(4-1) *4 -> fact (3) * 3  
         * 
         * 
         * 
         * 
         */
        return result ;


}


public static void main(String[] args) {

    Recursion_Example obj1 = new Recursion_Example();
    System.out.println("Factorial of 3 is "+ obj1.fact(3));
    System.out.println("Factorial of 4 is "+ obj1.fact(4));
    System.out.println("Factorial of 5 is "+ obj1.fact(5));

/*

  • fact(5) = 5 x 4 x 3 x 2 x 1 =120
  • fact(1) = 1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 = 24
  • fact(5) =24*5 =120
  • ------------------
  • fact(4) = 4 × 3 × 2 × 1 = 24
  • fact(1) =1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 =24
  • fact(4) =24
  • ------------------
  • fact(3) = 3 × 2 × 1 = 6
  • fact(1) =1
  • fact(2) =1*2 =2
  • fact(3) =2*3 =6
  • ------------
  • */

    }

}


package java_Method;

// Sum of Natural Numbers Using Recursion
public class RecursionExample1 {

public static void main(String[] args) {


    int result = sum(10);
    System.out.println(result);


}

public static int sum(int k)
{
    if(k>0)
    {
        return k+ sum(k-1);
    }

    else
    {
        return 0;
    }
}

}








Let’s Build a Bank Account Simulation

Problem Statement

🧩 Overview

Build a bank system to create and manage user accounts, simulate deposits, withdrawals, interest accrual, and overdraft penalties.

🎯 Goals

  • Support multiple account types with different rules
  • Simulate real-world banking logic like minimum balance and interest
  • Track user actions securely

🏗 Suggested Classes

  • BankAccount: account_number, owner, balance, deposit(), withdraw()
  • SavingsAccount(BankAccount): interest_rate, apply_interest()
  • CheckingAccount(BankAccount): minimum_balance, penalty
  • User: name, password, accounts[]

📦 Features

  • Create new accounts (checking/savings)
  • Deposit money to account
  • Withdraw money (with rules):
    • Checking: maintain minimum balance or pay penalty
    • Savings: limit to 3 withdrawals/month
  • Apply interest monthly for savings
  • Show account summary

🔧 OOP Concepts

  • Inheritance: SavingsAccount and CheckingAccount from BankAccount
  • Encapsulation: Balance, account actions hidden inside methods
  • Polymorphism: Overridden withdraw() method in each subclass

🔌 Optional Extensions

  • Password protection (simple CLI input masking)
  • Transaction history with timestamp
  • Monthly bank statement generation

Let’s Build a Library Management System With OOPS

Problem Statement

🧩 Overview

Design a command-line-based Library Management System that simulates the basic operations of a library for both users and administrators. It should manage books, user accounts, borrowing/returning of books, and enforce library rules like book limits per member.

🎯 Goals

  • Allow members to search, borrow, and return books.
  • Allow admins to manage the library’s inventory.
  • Track book availability.
  • Prevent double borrowing of a book.

👤 Actors

  • Admin
  • Member

🏗 Suggested Classes

  • Book: ID, title, author, genre, is_available
  • User: username, role, user_id
  • Member(User): borrowed_books (max 3 at a time)
  • Admin(User): can add/remove books
  • Library: manages collections of books and users

📦 Features

  • Admin:
    • Add a book with metadata
    • Remove a book by ID or title
    • List all books
  • Member:
    • Register or login
    • View available books
    • Borrow a book (limit 3)
    • Return a book
  • Library:
    • Handles storage, availability, and user-book mappings

🔧 OOP Concepts

  • Inheritance: Admin and Member inherit from User
  • Encapsulation: Book’s availability status and member’s borrow list
  • Polymorphism: Different view_dashboard() method for Admin vs Member

🔌 Optional Extensions

  • Track borrowing history (borrow date, return date)
  • Due dates and overdue penalties
  • Persistent data storage (JSON or SQLite)

📊 Learn PostgreSQL in Tamil: From Zero to 5★ on HackerRank in Just 10 Days

 

PostgreSQL is one of the most powerful, stable, and open-source relational database systems trusted by global giants like Apple, Instagram, and Spotify. Whether you’re building a web application, managing enterprise data, or diving into analytics, understanding PostgreSQL is a skill that sets you apart.

But what if you could master it in just 10 days, in Tamil, with hands-on learning and a guaranteed 5★ rating on HackerRank as your goal?

Sounds exciting? Let’s dive in.

🎯 Why This Bootcamp?

This 10-day PostgreSQL Bootcamp in Tamil is designed to take you from absolute beginner to confident practitioner, with a curriculum built around real-world use cases, performance optimization, and daily challenge-driven learning.

Whether you’re a

  • Student trying to get into backend development
  • Developer wanting to upskill and crack interviews
  • Data analyst exploring SQL performance
  • Tech enthusiast curious about databases

…this bootcamp gives you the structured path you need.

🧠 What You’ll Learn

Over 10 days, we’ll cover

  • ✅ PostgreSQL installation & setup
  • ✅ PostgreSQL architecture and internals
  • ✅ Writing efficient SQL queries with proper formatting
  • ✅ Joins, CTEs, subqueries, and advanced querying
  • ✅ Indexing, query plans, and performance tuning
  • ✅ Transactions, isolation levels, and locking mechanisms
  • ✅ Schema design for real-world applications
  • ✅ Debugging techniques, tips, and best practices
  • ✅ Daily HackerRank challenges to track your progress
  • ✅ Solve 40+ HackerRank SQL challenges

🧪 Bootcamp Highlights

  • 🗣 Language of instruction: Tamil
  • 💻 Format: Online, live and interactive
  • 🎥 Daily live sessions with Q&A
  • 📊 Practice-oriented learning using HackerRank
  • 📚 Notes, cheat sheets, and shared resources
  • 🧑‍🤝‍🧑 Access to community support and mentorship
  • 🧠 Learn through real-world datasets and scenarios

Check our previous Postgres session

📅 Details at a Glance

  • Duration: 10 Days
  • Language: Tamil
  • Format: Online, hands-on
  • Book Your Slot: https://topmate.io/parottasalna/1558376
  • Goal: Earn 5★ in PostgreSQL on HackerRank
  • Suitable for: Students, developers, DBAs, and tech enthusiasts

🔥 Why You Shouldn’t Miss This

  • Learn one of the most in-demand database systems in your native language
  • Structured learning path with practical tasks and daily targets
  • Build confidence to work on real projects and solve SQL challenges
  • Lifetime value from one affordable investment.

Will meet you in session !!!

Constructor

What is constructor?

  • A constructor is a special type of method it used to initialize objects.

  • It has same name as the class and does not have a return type.(why do not return type because constructor is initialize the object .not to return value).

  • Called automatically when an object is created using new keyword.

Constructor:-

  • Java constructor is special type of method that are used to initialize object when it is created
  • It has the same name as its class and is syntactically similar to a method ,however constructors have no explicit return type include void .
  • You will use a constructor to give initial values to the instance variables defined by the class or to perform any other star-up procedures required to create a fully formed object.

  • All classes have constructor , whether you define one or not because java automatically provides a default constructor that initializes all member variables to zero.once you define your constructor , the default constructor is no longer used.

  • Constructors in Java are called automatically when you create an object to initialize objects attributes(instance variable 0r data).

  • Constructors in Java are used only to initialize instance variables, not static variables(just try to static variable for initialize ,no came error but not recommend ). Each object get its own copy of the variables,they are stored in different memory locations.you can have only one constructor with the same parameter list(signature)
    ,you can create many objects using that constructor.

Why Constructors Can’t Be Inherited?

Constructors are not inherited: Sub-classes don't get super class constructors by default. or You cannot inherit (or override) a constructor from a parent class in a child class.But you can call the constructor of the parent class using super().

What does “inherited” really mean?
when a child class gets access to the parent class's and variables automatically-without writing again in the child class

Note: just they are inherited , does not automatically called (You get access automatically, but you use them manually), you still need call them like any normal method or variables.

when a child class extends a parent class ,it inherits method and variables , but not constructors.
The child class must to explicitly call the parts's constructor using super();

Example:-

public class Parent_Child {

    String var="Parent_variable";
Parent_Child
{
        System.out.println("Parent Constructor");
}

    void show()
    {
        System.out.println("Parent_instacemethod");
    }

}


public class Child_parent  extends Parent_Child{

Child_parent {
        super(); //  You must call it, not inherited
        System.out.println("Child Constructor");
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //    // Child class doesn't define 'var' or 'show()' but it gets them from Parent  
        Child_parent obj1 = new Child_parent();
        obj1.show(); // You’re calling the inherited method
        System.out.println(obj1.var); // You’re accessing the inherited variable.


    }

}

Constructor cannot be overridden

Overriding means redefining a method in a child class with the same signature.
But constructor are not inherited , so you can not override them.Also constructor are not normal methods, so overriding does not apply.
finally constructor can not to be inherited and overriding .

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    // This is not overriding
    Child() {
        System.out.println("Child Constructor");
    }
}

Rules for creating java Constructor:-

  • The name of the constructor must be the same as the class name.
  • Java constructors do not have a return type include void.
  • In a class can be multiple constructors in the same class ,this concept is known as constructor overloading.
  • You can use the access modifier in the constructor ,if you want to change the visibility/accessibility of constructors.
  • Java provides a default constructor that is invoked during the time of object creation . if you create any type of constructor, the default constructor (provide by java) is not invoked(called).

Cannot be called like normal methods (c.Parent() calls the method, not constructor)

do not define two constructor with same parameter type even if parameter names are different ,java can not accept.

Example:

class Student {
Student() {
System.out.println("Constructor called!");
}
}

public class Test {
public static void main(String[] args) {
Student s = new Student(); // Constructor is called automatically here
}
}

output:-
Constructor called!

You do not call the constructor like a method (s.Student()).
You just create the object, and Java will automatically call the constructor.

Creating constructor:-

Syntax

Class ClassName{



Classname()
{
}
}

Types of Java Constructors:-

  • Default constructor(implicit Default constructor) => No parameters and invisible.
  • No-args Constructor.(explicit Default constructor) => No parameters
  • Parameterized Constructor => with parameters multiple constructor with different parameters.Used to initialize object with specific values.

Default constructor

If you do not create any constructor in the class, java provides a default constructor that initializes the variables to default values like 0,null,false.

public class DefaultConstructor {
    String name ;
    int age;
    String jobRole;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DefaultConstructor obj1 = new DefaultConstructor();
        obj1.name="R.prasanth";
        obj1.age=25;
        obj1.jobRole="JavaDeveloper";
        System.out.println("Name: "+obj1.name+", Age: "+obj1.age+", JobRole: "+obj1.jobRole);

    }
}

Example:2

public class DefaultConstructor1 {
    int id;
    String name;
    public static void main(String[] args) {

        DefaultConstructor1 s1 =new DefaultConstructor1();
        System.out.println("ID: "+s1.id);
        System.out.println("Name: "+s1.name);

    }
}

No-args Constructor.

The No-Argument constructor does not accept any argument,By using the no-args constructor you can initialize the class data members(fields or global variable) and perform various activities that you want on object creation.

Example:-


public class SimpleConstructor {
    //Explicitly you created constructor now ,no more invoked java provide default constructor
    SimpleConstructor()
    {
        System.out.println("Vankam da mapla Thiruttani irunthu");
    }
    public static void main(String[] args) {
        System.out.println("The main() method ");
        //creating a class's object, that will invoke the constructor.
        SimpleConstructor obj1 = new  SimpleConstructor();

    }
}


Example;1

public class NoArgsConstructor {
    int id;
    String name;

    NoArgsConstructor()
    {
        id =101;
        name ="Jhon";

    }

    void show ()
    {
        System.out.println("ID: "+id+", Name: "+name);
    }
    public static void main(String[] args) {
        System.out.println("NoArgs-constructor");

        NoArgsConstructor s1 = new NoArgsConstructor();
        s1.show();
    }
}

3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized constructor.
use when you need to initialize different objects with different data.
Use with this keyword to avoid confusion between parameter and instance variable

Example:1

public  class Parmet_Constructor {

    String name,jobStatus,jobFinding;
    static int age;

    Parmet_Constructor (String name,int age,String jobStatus,String jobFinding)
    { //this.varName → refers to current object's variable.
     this.name=name;
     this.age=age;
     this.jobStatus=jobStatus;
     this.jobFinding=jobFinding;
    }
    public void  studentDetails()
    {
        System.out.println("name: "+ name+", age: "+age+",jobStatus: "+jobStatus+",jobfinding: "+jobFinding);
    }

    public static void main(String[] args) {
        Parmet_Constructor  obj1 = new Parmet_Constructor ("Prasanth",25,"Job_seeker","Java_Developer");
        obj1.studentDetails();
    }
}


Example:2

public class ParameterizedConstructor {
   int experience ; 
   int salary;
   String jobVacancy, name;
   // Parameterized constructor
   ParameterizedConstructor(String name, String jobVacancy, int salary,int experience) {
       this.name = name;
       this.jobVacancy = jobVacancy;
       this.salary = salary;
       this.experience= experience;
   }
   void candidateInfo() {
       System.out.println("Candidate Name: " + name);
       System.out.println("Job Vacancy: " + jobVacancy);
       System.out.println("Salary: " + salary);
       System.out.println("Experience: " + experience);
       System.out.println("-------------------------------");
   }
   public static void main(String[] args) {
       ParameterizedConstructor candidate1 = new ParameterizedConstructor("Prasanth", "Java Developer", 25000,1);
       ParameterizedConstructor candidate2 = new ParameterizedConstructor("Vignesh", "Frontend Developer", 26000,1);
       candidate1.candidateInfo();
       candidate2.candidateInfo();
   }
}

Constructor Overloading:-

Constructor overloading means multiple constructors in a class.when you have multiple constructor with different parameters listed, then it will be known as constructor overloading.

Example:

/constructor overloading
public class StudentData_ConstructorOverloading {
    //fields or globalvariable
   String name, gender, class_section, DOB, BloodGroup;
   float height;
   int id;
   // Constructor 1
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String BloodGroup) {
//this used to refer to current object's variable:
       this.id = id; //local variable opposite side global variable
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.BloodGroup = BloodGroup;
   }
   // Constructor 2
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section, String DOB, float height) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
       this.DOB = DOB;
       this.height = height;
   }
   // Constructor 3
   StudentData_ConstructorOverloading(int id, String name, String gender, String class_section) {
       this.id = id;
       this.name = name;
       this.gender = gender;
       this.class_section = class_section;
   }
   void studentData() {
       System.out.println("ID: " + id);
       System.out.println("Name: " + name);
       System.out.println("Gender: " + gender);
       System.out.println("Class Section: " + class_section);
       System.out.println("DOB: " + DOB);
       System.out.println("Blood Group: " + BloodGroup);
       System.out.println("Height: " + height);
       System.out.println("-----------------------------");
   }
   public static void main(String[] args) {
       StudentData_ConstructorOverloading student1 = new StudentData_ConstructorOverloading(1, "Mukesh", "Male", "A", "B+");
       StudentData_ConstructorOverloading student2 = new StudentData_ConstructorOverloading(2, "Prasanth", "Male", "C", "03/06/2000", 5.10f);
       StudentData_ConstructorOverloading student3 = new StudentData_ConstructorOverloading(3, "Shivan", "Male", "B");
       student1.studentData();
       student2.studentData();
       student3.studentData();
   }
}
// global/field(static/non-static)  if do not initialize variable value it will provide default value.
/*
* int byte shrot long-> 0
* float double -. 0.0
* String  null
* boolean  default value is false
* 
*
*
*/


Example:-

public class Student_Constructor_DoandDonot {

    int id;
    String name,department;
    char gender;

    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    // do not define  two constructor with  same  parameter type even if parameter names are different ,java can not accept
    /*
    Student_Constructor_DoandDonot(int id, String name,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
*/
    /*
    Student_Constructor_DoandDonot(int Id, String Name,String Department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
    }
    */
    Student_Constructor_DoandDonot(int id, String name,char gender,String department)
    {
        this.id=id;
        this.name=name;
        this.department=department;
        this.gender=gender;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    //do's
        Student_Constructor_DoandDonot student1 =new Student_Constructor_DoandDonot(101,"Prasanth","ComputerScience");
        Student_Constructor_DoandDonot student2 =new Student_Constructor_DoandDonot(102,"shivan","History");
        Student_Constructor_DoandDonot student3 =new Student_Constructor_DoandDonot(103,"Parvathi",'F',"History");
        student1.infoStudent();
        student2.infoStudent();
        student3.infoStudent3();

    }
    public void infoStudent() {
   System.out.println("id: "+id+", Name: "+name+", Department:" +department);       
    }
    public void infoStudent3() {
        System.out.println("id: "+id+", Name: "+name+", Gender:"+gender+", Department:" +department);       
        }
}

  • Constructors cannot be inherited, but you can call superclass constructor using super().
  • You cannot inherit (or override) a constructor from a parent class in a child class.
  • Constructors can use this keyword to refer to the current object.

=>this()

  • This refers current class object
  • This used to call another constructor in same class
  • this() Only use to inside constructor not any others
  • Must be the first line in the constructor.
  • not allowed in normal methods.
  • Does not work with static methods or variables.
  • can not be used with super() in same constructor. helps when may constructor share common values.
  • To access current class instance variable (to avoid confusion with parameter name)
  • To call instance method of same class

What this does not do:

  • Not for inheritance
  • Not for typecasting
  • Not used for calling parent constructor (use super() for that

=>super()

  • Used to call parent class constructor.
  • you can use super() inside the first line of the
    child class constructor to call parent constructor.
    (when you create a child object, the parent part must to initialized first.)
    why? to initialize parent class fields. (or)
    Used to initialize parent class properties.
    In child classes to call parent constructor (especially if the parent class has a parameterized constructor). can not call parents methods-only constructor.

  • Every child constructor must call a parent constructor (either explicitly with super() for parametrized constructor or implicitly (java automatically call ) if parent has no-args constructor). otherwise compilation error.
    why? Because java needs to create the parent part of the object first.even if yo did not write extends ,your class still extends object class,this class parent of all class in java.

if the parent only has parameterized constructors, you must explicitly call super(args) in the child constructor.

To access parent class variables/methods (if child class has same name).You cannot inherit constructors – Only call them using super()
Why?
A constructor name = class name, so it’s always specific to its own class.

Explain constructor overloading with example?

Constructor overloading means creating multiple constructor with the same class name but different parameter(number,type,order),purpose to initialize objects different ways.

What happens if both this() and super() are used?

you can not use both this() and super() in the same constructor, because both must be the first statement in the constructor.

Why constructors can’t be inherited?
comment me in the blog.
hint: inheritance is allows a child class it inherit properties(fields) and behavior(method) from parent class.

How do this and super differ?

Image description

When is constructor called in real life?

Constructors are automatically called when an object is created using new keyword.
Real-time Use Cases:

When reading user data (like name, age) into an object.

When fetching data from a database and storing in object (e.g., Employee, Product).

While creating objects in Java applications, games, or backed APIs.

can we create object in instance method?
yes we can create object in instance method.

Allowed Modifiers/Keywords for Constructors

Allowed

1.public - unrestricted Access
2.protected - subclass(is-relationship(extends)+ same package access.
3.default(package-private) - only accessible within the same package.
4.private - only usable within the class,
not Allowed (use-case Singletons & factory methods)

Not Allowed

5.final - constructors are implicitly final
why constructor are not inherited or overridden
6.static - constructor are always instance-related(used to initialize objects). static keyword use for constructor useless, static is class specific .

  1. abstract - abstract class can not create it's object directly,if you have abstract method must to be implemented child class.that's why does not work with constructors. simply:- abstract means:
  2. No implementation (no body).
  3. Child classes must provide the logic. 8.Synchronized

Constructor Programme:

this() using constructor:

super() using construtor:-

package inheritence;

public class Vehicle {
int speed;


 Vehicle(int speed)
 {
     this.speed=speed;
     System.out.println("Vehicle constructor: speed set to "+speed);


    }

}

package inheritence;

public class Car extends Vehicle{
    String model;
    Car (int speed,String model)
    {
        super(speed);
        this.model=model;
        System.out.println("Car constructor: model set to " + model);
    }

    void display()
    {
        System.out.println("Car speed: " + speed + ", Model: " + model);
    }

    public static void main(String[] args) {

        Car c1 = new Car(100,"Honda");
        c1.display();
    }

}

output:-
Vehicle constructor: speed set to 100
Car constructor: model set to Honda
Car speed: 100, Model: Honda

this() Example Program


public class Student {

    int id; 
    String name;

    Student()
    {
        this(101,"Default");
        System.out.println("No-arg constructor");
    }
    Student(int id,String name)
    {
        this.id=id;
        this.name=name;

  System.out.println("Parameterized constructor");
    }

    void infoDisplay()
    {
        System.out.println(this.id + " " + this.name); 
    }

    public static void main(String[] args) {

        Student student = new Student();
        student.infoDisplay();
    }

}

Constructor vs Method

Image description

copy constructor:-

A copy constructor is a constructor that creates new object by copying another object of the same class.

java does not provide default copy constructor you can create manually.

why to use copy constructor?
To create a duplicate(copy) of exiting object with the same values (copy data from one object to another).

what is clone() method?

It is method in java built in object class
it creates a copy(duplicate) of the object.

Example:-

Myclass obj1 = new Myclass();
Myclass obj1 =  (Myclass) obj1.clone();

clone () is complex to use correctly and it needs to implements cloneable and can cause errors.
recommended is copy constructor.

Important:-

what is mutable and immutable in java?

Mutable:
can be changed after the object is created.
If you class contains:
mutable fields( like arrays.lists,String Builder)
copy constructor must create new copies of those fields. This is called a deep copy. it each object independent data.No shared references.

Immutable:-
can not be changed once the object is created.

If you class contains:
Immutable fields Like String,Integer,Double,Boolean..etc
safe to just copy reference , no need to clone. This is called a shallow copy.

Example:


public class Example_Mutable_Immutable {




    public static void main(String[] args)
    {
        String s1 ="Java";
        String s2=s1 ;
        s1=s1+ "Programming";
        System.out.println("Immutable");
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        StringBuilder sb1 = new StringBuilder("java");
        StringBuilder sb2= sb1;
        sb1.append("Programming");
        System.out.println("\nMutable:");
        System.out.println("sb1 = " + sb1);
        System.out.println("sb2 = " + sb2);

    }

}

Output:
Immutable
s1 = JavaProgramming
s2 = Java

Mutable:
sb1 = javaProgramming
sb2 = javaProgramming

shallow copy vs deep copy:-

Shallow copy(immutable fields ):-

  • copies references , not to objects
  • memory shares to referenced objects(original and copy point to the same object in memory).
  • if you change original ,copy is also affected.
  • performance faster (less memory allocation)
  • Implementation Default clone() method
  • used when field are immutable(like string,int)

Deep copy(mutable fields ):-

  • create new objects with copied values.
  • creates separate memory for all objects
  • Change in original would not affect the copy. -Best when fields are mutable like StringBuilder,ArrayList
  • performance slower(more memory allocation)
  • custom implementation needed.
class Book {
     StringBuilder title;

     //Normal constructor
     Book(StringBuilder title)
     {
         this.title=title;

     }
     //shallow copy constructor 
     Book(Book b)
     {
         this.title=b.title; //same reference
     }

     //Deep copy constructor
     Book(Book b,boolean deep)
     {
         this.title= new StringBuilder(b.title.toString());
     }
    void showTitle()
    {
        System.out.println("Title: "+title);
    }
    public static void main(String[] args) {
        StringBuilder originalTitle = new StringBuilder("Java Programming");

  //orginal object
        Book book1 = new Book(originalTitle);
        //shallow copy
        Book book2 =new Book(book1);
        //Deep copy 
        Book book3 = new Book(book1,true);


        // Modify the original title
        originalTitle.append(" - Beginner");

        System.out.println("After modifying the original title:\n");

        System.out.print("Book1: ");
        book1.showTitle();

        System.out.print("Book2 (Shallow Copy):  ");
        book2.showTitle(); // Will be affected (same reference)

        System.out.print("Book3 (Deep Copy):  ");
        book3.showTitle(); // Will not be affected




}
}

Redis Strings – The Building Blocks of Key Value Storage

Redis is famously known as an in-memory data structure store, often used as a database, cache, and message broker. The simplest and most fundamental data type in Redis is the string. This blog walks through everything you need to know about Redis strings with practical examples.

What Are Redis Strings?

In Redis, a string is a binary-safe sequence of bytes. That means it can contain any kind of data text, integers, or even serialized objects.

  • Maximum size: 512 MB
  • Default behavior: key-value pair storage

Common String Commands

Let’s explore key-value operations you can perform on Redis strings using the redis-cli.

1. SET – Assign a Value to a Key

SET user:1:name "Alice"

This sets the key user:1:name to the value "Alice".

2. GET – Retrieve a Value by Key

GET user:1:name
# Output: "Alice"

3. EXISTS – Check if a Key Exists

EXISTS user:1:name
# Output: 1 (true)

4. DEL – Delete a Key

DEL user:1:name

5. SETEX – Set Value with Expiry (TTL)

SETEX session:12345 60 "token_xyz"

This sets session:12345 with value token_xyz that expires in 60 seconds.

6. INCR / DECR – Numeric Operations

SET views:homepage 0
INCR views:homepage
INCR views:homepage
DECR views:homepage
GET views:homepage
# Output: "1"

7. APPEND – Append to Existing String

SET greet "Hello"
APPEND greet ", World!"
GET greet
# Output: "Hello, World!"

8. MSET / MGET – Set or Get Multiple Keys at Once

MSET product:1 "Book" product:2 "Pen"
MGET product:1 product:2
# Output: "Book" "Pen"

Gotchas to Watch Out For

  1. String size limit: 512 MB per key.
  2. Atomic operations: INCR, DECR are atomic – ideal for counters.
  3. Expire keys: Always use TTL for session-like data to avoid memory bloat.
  4. Binary safety: Strings can hold any binary data, including serialized objects.

Use Redis with Python

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('user:1:name', 'Alice')
print(r.get('user:1:name').decode())

static and non static

static and non static

static

  • static is class specific
  • static variable: only one copy of it exists, and all objects share that one copy.

  • static method: Can be called using the class name directly, doesn't need an object.

what can be static java?
1.varibles(fields)
class Student{
static String college = "Jaya College";
}

  1. static methods(class-level method)

used when:

  • you don't need to use object data(this)
  • you want to call it without creating an object.

`class Utility
{
static void printMessage()
{
System.out.println("hell from static method");

}
}

//calling using Utility.printMessage();
`
3.Static Blocks(Runs only once when class is loaded)
used to : initialize static variable


class Example
{
static int data;
static {
data =100;
System.out.println("Static block executed");
}
}

4.static Nested class

use when : you want a class inside another class without needing the outer class object.

`
class Outer {
static class Inner {
void show() {
System.out.println("Inside static nested class");
}
}
}

`
call using:

Outer.Inner obj = new Outer.Inner();
obj.show();

you cannot use static :

Local varibales (int x=5; inside a method) static
Constructor static
Classes (top-level) static ( unless they are nested inside another class)

Example

class car {
static int car =4;
}
// now whether you create 1 object or 100 , all cars shares the same number of weels 

//static = belongs to class, shared by all, only one copy.



public class MyClass2 {
      static int val =1;
    public static void main(String[] args) {


        MyClass2 obj1 = new  MyClass2();
        MyClass2 obj2  = new  MyClass2();

        obj1.val=10;
        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);


    }

}

output:
obj1 val:10
obj2 val:10
//

non static

  • non-static is instance specific
  • if a variable is non-static ,then every object has its own separate copy that mean Non-static members belong to the object, it gets own copy of non static variables and can use non-static method.
Example: 1

public class MyClass {
    int val =1;

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();

        obj1.val=10; // change  value for obj1

        System.out.println("obj1 val:"+obj1.val);
        System.out.println("obj2 val:"+obj2.val);

    // non-static = belongs to object, each object has its own value.   



    }

}

output:
obj1 val:10
obj2 val:1

  1. non-static variables (instance variable)

use when: Each object should have it own values.

example 2:

class Student 
String name;
int id;

Student (String name ,int id)

{
this.name =name;
this.id = id;

}


void display()
{
System.out.println(name +"  "+id);
}




public  class Test {

public static void main(String[] args)
{
Student s1 = new Student("John", 1);
Student s2 = new Student("Emma", 2);
s1.display(); //John
s2.display(); //Emma
}

}

  1. Non-static Method (Instance Method) used when you want to work with object data like name,id you need use this keyword
class Car {
    String brand;

    void showBrand() {  // non-static method
        System.out.println("Brand: " + brand);
    }
}

//you must to create object to call it:

public class Test {
public static void main(String[] args)
{
Car c = new Car();
c.brand="Tata";
c.showBrand();
}
}

  • you can not use non-static members inside static methods directly.
class Example {
    int x = 10;  // non-static

    static void show() {
        // System.out.println(x); // Error
    }
}

//To access x, you must create an object:
static  void show {
Example e shwo = new Example();
System.out.println(e.x);
}

Image description

Image description

What does “belong to class” mean?

  • It means the variable or method is shared by all objects of that class.
  • You don’t need to create an object to access it.
  • Use the static keyword.

What does “belong to object” mean?

  • It means each object has its own copy of that variable or method.
  • You need to create an object to use it.
  • Do not use static keyword.

why can not use to static in class(top-level)?

because not belong to any another class, only for static variable ,block,methods ,inner class

now see top level-class valid and invalid modifiers for class

Valid Modifiers for Top-Level Classes:

1.public -> class is accessible from anywhere
2.default -> no keyword=package-private, used only within the same package.
3.abstract -> class cannot-be instantiated(can not create object) ,must be inherited(extend) and If the subclass does NOT implement all abstract methods,
then the subclass must also be declared abstract. Abstract class can have normal methods too.
// we will detail info of abstraction concept

Why can't we create an object of an abstract class?

Abstract class is incomplete- it might have abstract methods(with out body). you must create a subclass that completes those methods. so that's why doesn't allow you to create object directly.

Why abstract class cannot achieve 100% abstraction?
Because:

  • An abstract class can contain concrete methods (with body).
  • So, not everything is hidden from the user.
  • That’s why it cannot achieve 100% abstraction. You can say: Abstract class = Partial abstraction

Why interface can achieve 100% abstraction?

Because:

  • All methods in an interface are abstract by default (before Java 8).
  • You cannot write method body (in older versions).
  • It only contains method declarations, no implementations. So, the user only sees "what to do", not "how".
Animal a = new Animal();  // Error: Cannot instantiate abstract class
Animal a = new Dog();  //  Allowed: Dog is a subclass of Animal/

4.final -> class cannot be extended( no sub classing) like not is-relationship or prevent inheritance

Invalid Modifiers for Top-Level Classes:

1.private -> No class can see it in the world, so it's useless.
2.protected -> used for members only (variable and methods), not for top-level class
3.static -> Only for inner class, not outer class.

how and where static, instance, and local variables and methods are called, accessed, and hold values.

class Variable {

int instancevar=10;
static int staticVar =20;

    public static void main(String[] args) {
//local variable must be initialized        
    int localVar=30;
    System.out.println("Local variable"+localVar);
    System.out.println("Static Varibale:"+staticVar);
    //accessing instace variable -> directely not allowed 
    //System.out.println("Instace variable:"+obj1.instancevar);

    Variable obj1= new Variable();
    System.out.println("Instace variable:"+obj1.instancevar);
    obj1.instanceMethod();




}
 static void staticMethod()
    {
        System.out.println("inside static method");
        System.out.println("Static Varibale:"+staticVar);
        Variable obj1= new Variable();

        System.out.println("Instace variable:"+obj1.instancevar);
    }
 void instanceMethod()
    {
        System.out.println("inside instace method");

        staticMethod();
        System.out.println("Static Varibale:"+staticVar);
        System.out.println("Instace variable:"+instancevar);

    }
}

Note:-

  • Static Method: Can only access static members directly.
    • To access instance members, create an object.
  • Instance Method: Can access both static and instance members directly.
  • Local Variables: Only exist inside the method, and must be initialized.

Java -> class & object

what is a Class in java?

  • A class in java is a blueprint/template/design ,it used to create objects.
  • It defines data(variable) and behaviors(method) that object can have.An object has its own copy of those variables, and it can run the methods.

  • No memory is allocated when a class is defined.

  • only memory allocated object create at runtime program execution.Written using class keyword.

  • Class is Logical Entity,it means

    • A logical entity is checked by the compiler when we write code ,like just writing structure or blue print of the program. this structure is called logical entity.
    • Only the compiler checks it
    • it does not take any memory until we create an object. class is idea/design/plan

example

class car{

String color; // declared , but no value stored yet
}

object

Car mycar =new Car();
mycar.color = "red"; // Real instance (holds real values and uses memory at runtime)

Just think car:-

  • What it has Variables (data) ->color,brand,speed
  • What it does Methods (behaviors) -> drive,stop,honk.
  • Object is the real thing created using the class.

  • It does not occupy memory  like object do , it just defines structure(variable + methods) but the actual values are not created or stored in memory until you make an object.
    
  • A class is compile-time entity .it means compiler sees and checks before the program runs like check syntax correct or not and variable type and method signature correct or not ,data type matching and rules of java followed .

  • class it the core concept of object-oriented programming(oops) in java.

example

public class Car
{
    // Data members (fields)- hold  the actual value

String brand;
int speed;
    // Behavior (method)
void drive()

{
System.out.println("driving a car");
}


}
//But it’s not a real car yet. It’s just the plan.

Class Name Rules:

  • 1.Must start with a Uppercase first letter or (_) underscore Or dollar sign ($).
  • 2.can not start with a number
  • 3.can not contain spaces or special characters
  • 4.use Pascal-case for naming

example

class EmployeeDetails

Access Modifier in class

  • Class is public accessible form anywhere,it default( not modifier) accessible only within the same package ( class have final,abstract) , class can not to use protected and private access modifier but inner class you can use all access modified we can see example.

example 1 : inner class

public class OuterClass {

    private class InnerPrivate
    {
        void show()
        {
            System.out.println("private inner class");
        }
    }

protected class InnerProtected
    {
        void show()
        {
            System.out.println("protected inner class");
        }
    }

class InnerDefault
{
    void show()
    {
        System.out.println("Default inner class");
    }
}


public class InnerPublic
{
    void show()
    {
        System.out.println("public  inner class");
    }
}


}
// we can see later inner-private class member how to access outer class.(Accessing Private Inner Class Inside Outer Class)

Top-Level Class

    Can use only:

-  public
-     default (no modifier)
-     Cannot use private or protected

Inner Class (class inside another class)

  Yes, inner classes can be:
-         private
-         protected
-         public
-         default

Because inner classes are members of the outer class (just like variables), they can have any access modifier.

example 2 : private in outer class

private  class PrivateClass
{
    public static void main(String[] args) {
    {
        System.out.println("private outer class ");
        //top-level classes (outer classes) cannot be private. Only inner classes can be private.

//modifier  private not allowed here, outer class is private, no other class can access it, even same package.it is useless that's why java does not allow  private outer class. 
    }
    }
}


// Simple term:-

private means: only accessible inside the same class
→ But if the class is private, no other class can use it, which defeats the purpose of defining it.

example 3 :- protected in outer class

protected class ProtectedClass {

    public static void main(String[] args) {

        System.out.println(" protected  outer class ");



    }

}
//protected is only useful for

- same package access
- subclass access  and even in another package,but top-level class can not be inherited if it is  protected in  another package.
- So, Java does not allow protected for top-level classes either.

why protected top-level class is not allowed?

*protected is for members and inner classes only
*top-level class need to be accessible by compiler
*subclass from another package can not even access it.

simple say:-

protected means: accessible to subclasses and same package
→ But you can't inherit or access a class that’s protected from another package, so Java does not allow it.

what a class can contain

  • *variable, methods ,constructors,blocks,inner classes,interface
  • *Only One Public Class Only one public class per .java file

File name rule

  • if the class is public , the file name must match the class name.
  • if the class is default( no access modifer) the file name does not match the class name.

correct
`// File: Car.java
public class Car { }

Incorrect
// File: Vehicle.java
public class Car { } // Error!
`

what is object ?

  • object is an instance of a class. It means example of the class.object created from the class that Uses the variables and methods of the class & Holds actual values in its variables.Memory is allocated when object is created.

  • A object is created runtime(while the program runs) is called runtime entity.Is created using the new keyword,Take memory and holds data(variable) and behavior(methods) from the class.

  • object is runtime entity ,real instance that uses class features.

  • object also called physical entity,it means
    *object created in memory when program runs(runtime)and allocated memory runtime,
    It holds real values (variable) and performs actions (methods).
    *data hold the real values and action can call methods.

  • multiple object can be created from class and each have different value.

  • Each object has its own copy of instance variables

    ` Car car1 = new Car();
    Car car2 = new Car();

    car1.color = "Red";
    car2.color = "Blue";
    

    `
    Objects can use the functions (methods) that are defined inside their class

class Car {
    void drive() {
        System.out.println("The car is driving.");
    }
}

public class Test {
    public static void main(String[] args) {
        Car myCar = new Car();   // object created
        myCar.drive();           // object calling the method
    }
}

Car myCar = new Car();

Car = class
myCar = reference variable
new Car(); = create a new object in memory.

Runtime -> mean when the program is actually running.
Enitity -> means something that exists

=> A runtime entity is something that is created and exists only while the program is running.

class & object

A class is a blueprint of an object. It defines variables and methods. The object uses those variables and methods, and holds actual values. For example, a car is a class may have variables like brand, color, and type, and methods like drive, stop,etc.

Example

public class Car {
    //Data = variables → what the object has.
    String color;
    String brand;

       //Behavior = methods → what the object does.
    void  drive()
    {
        System.out.println("The " + color + " " + brand + " is driving.");
    }
    void stop() {
        System.out.println("The car has stopped.");
    }


    public static void main(String[] args) {
        Car mycar = new Car ();
        mycar.color="Red";
        mycar.brand="Honda";
        mycar.drive();
        mycar.stop();

    }

}

runtime and compile time

syntax check - compile time
object-creation ,method execution ,value holding( in memory) -runtime

variable

  • variables is used to store data values like number,text,etc.access variable when needed,you can change the values until you set final. (or)

A variable is a container(name) used to store data values in memory. like label for a memory location that hold some values.

variables called fields, instance variables ,data members ,properties ,Attributes

syntax
datatype variablename = value;

example

int age = 25;           // declaring and initializing variable
String name = "Prasanth";
System.out.println(age); // using variable

Types of variables in java

  1. Local Variable Declared inside a method or block.Accessible only within that block

memory location : stack
Access: inside method only
Example: int sum =10;

2.Instance variable
Declared inside a class but outside methods, belongs to objects.
memory location : Heap
Example: obj.name

3.Static variable
Declared using static keyword.Belongs to class,not instance
memory location : method area
Example: class name.count or obj.count

// we will next blog heap,stack.

Important
*only static and instance variables get default values when you printing those variables not local variables ,you must initialize it, or you will get a compilation error.

public class car {

static String company ="honda"; // static varibale
string model; // instance variable

void setModel(String modelName)
{
String prefix ="Model: "; // local variable 
model= prefix + modelName;
}

}

// static is class specific
// non-static(instance) object specific 

Method-Used to Perform Actions (Behavior/Logic)

  • Define logic or instructions inside a method
  • Call the method to execute that logic
  • Pass values (arguments) to it

example

void greet() {
    System.out.println("Hello, Java!");
}

greet();  // calling the method

class vs object

Image description

Image description

Code Less, Prompt Better: Unlocking Python's Built-in LLM Enhancers

In the rapidly evolving landscape of Large Language Models (LLMs), effective prompt engineering has become a crucial skill. While much attention is given to the art of crafting effective prompts, less focus has been placed on how to efficiently manage these prompts programmatically. Python, with its rich set of built-in features, offers powerful tools to dynamically construct, optimize, and manage LLM prompts.
This article explores how Python's built-in features can transform your approach to LLM prompt engineering, making your code more efficient, maintainable, and powerful.

1. Using locals() for Dynamic Context Injection

The Problem
When working with LLMs, we often need to inject contextual information into our prompts. The traditional approach involves manual string formatting:

def generate_response(user_name, user_query, previous_context):
    prompt = f"""
    User name: {user_name}
    User query: {user_query}
    Previous context: {previous_context}

    Please respond to the user's query considering the context above.
    """

    return call_llm_api(prompt)

This works well for simple cases, but becomes unwieldy as the number of variables increases. It's also error-prone – you might forget to include a variable or update a variable name.

The Solution with locals()
Python's locals() function returns a dictionary containing all local variables in the current scope. We can leverage this to automatically include all relevant context:

def generate_response(user_name, user_query, previous_context, user_preferences=None, user_history=None):
    # All local variables are now accessible
    context_dict = locals()

    # Build a dynamic prompt section with all available context
    context_sections = []
    for key, value in context_dict.items():
        if value is not None:  # Only include non-None values
            context_sections.append(f"{key}: {value}")

    context_text = "\n".join(context_sections)

    prompt = f"""
    Context information:
    {context_text}

    Please respond to the user's query considering the context above.
    """

    return call_llm_api(prompt)

Benefits:

Automatic variable inclusion: If you add a new parameter to your function, it's automatically included in the context.
Reduced errors: No need to manually update string formatting when variables change.
Cleaner code: Separates the mechanism of context injection from the specific variables.

2. Using inspect for Function Documentation

The Problem
When creating LLM prompts that involve function execution or code generation, providing accurate function documentation is crucial:

def create_function_prompt(func_name, params):
    prompt = f"""
    Create a Python function named '{func_name}' with the following parameters:
    {params}
    """
    return prompt

This approach requires manually specifying function details, which can be tedious and error-prone.

The Solution with inspect
Python's inspect module allows us to extract rich metadata from functions:

import inspect

def create_function_prompt(func_reference):
    # Get the function signature
    signature = inspect.signature(func_reference)

    # Get the function docstring
    doc = inspect.getdoc(func_reference) or "No documentation available"

    # Get source code if available
    try:
        source = inspect.getsource(func_reference)
    except:
        source = "Source code not available"

    prompt = f"""
    Function name: {func_reference.__name__}

    Signature: {signature}

    Documentation:
    {doc}

    Original source code:
    {source}

    Please create an improved version of this function.
    """

    return prompt

# Example usage
def example_func(a, b=10):
    """This function adds two numbers together."""
    return a + b

improved_function_prompt = create_function_prompt(example_func)
# Send to LLM for improvement

This dynamically extracts all relevant information about the function, making the prompt much more informative.

3. Context Management with Class Attributes

The Problem
Managing conversation history and context with LLMs often leads to repetitive code:

conversation_history = []

def chat_with_llm(user_input):
    # Manually build the prompt with history
    prompt = "Previous conversation:\n"
    for entry in conversation_history:
        prompt += f"{entry['role']}: {entry['content']}\n"

    prompt += f"User: {user_input}\n"
    prompt += "Assistant: "

    response = call_llm_api(prompt)

    # Update history
    conversation_history.append({"role": "User", "content": user_input})
    conversation_history.append({"role": "Assistant", "content": response})

    return response

The Solution with Class Attributes and dict
We can create a conversation manager class that uses Python's object attributes:

class ConversationManager:
    def __init__(self, system_prompt=None, max_history=10):
        self.history = []
        self.system_prompt = system_prompt
        self.max_history = max_history
        self.user_info = {}
        self.conversation_attributes = {
            "tone": "helpful",
            "style": "concise",
            "knowledge_level": "expert"
        }

    def add_user_info(self, **kwargs):
        """Add user-specific information to the conversation context."""
        self.user_info.update(kwargs)

    def set_attribute(self, key, value):
        """Set a conversation attribute."""
        self.conversation_attributes[key] = value

    def build_prompt(self, user_input):
        """Build a complete prompt using object attributes."""
        prompt_parts = []

        # Add system prompt if available
        if self.system_prompt:
            prompt_parts.append(f"System: {self.system_prompt}")

        # Add conversation attributes
        prompt_parts.append("Conversation attributes:")
        for key, value in self.conversation_attributes.items():
            prompt_parts.append(f"- {key}: {value}")

        # Add user info if available
        if self.user_info:
            prompt_parts.append("\nUser information:")
            for key, value in self.user_info.items():
                prompt_parts.append(f"- {key}: {value}")

        # Add conversation history
        if self.history:
            prompt_parts.append("\nConversation history:")
            for entry in self.history[-self.max_history:]:
                prompt_parts.append(f"{entry['role']}: {entry['content']}")

        # Add current user input
        prompt_parts.append(f"\nUser: {user_input}")
        prompt_parts.append("Assistant:")

        return "\n".join(prompt_parts)

    def chat(self, user_input):
        """Process a user message and get response from LLM."""
        prompt = self.build_prompt(user_input)

        response = call_llm_api(prompt)

        # Update history
        self.history.append({"role": "User", "content": user_input})
        self.history.append({"role": "Assistant", "content": response})

        return response

    def get_state_as_dict(self):
        """Return a dictionary of the conversation state using __dict__."""
        return self.__dict__

    def save_state(self, filename):
        """Save the conversation state to a file."""
        import json
        with open(filename, 'w') as f:
            json.dump(self.get_state_as_dict(), f)

    def load_state(self, filename):
        """Load the conversation state from a file."""
        import json
        with open(filename, 'r') as f:
            state = json.load(f)
            self.__dict__.update(state)```



Using this approach:

# Create a conversation manager
convo = ConversationManager(system_prompt="You are a helpful assistant.")

# Add user information
convo.add_user_info(name="John", expertise="beginner", interests=["Python", "AI"])

# Set conversation attributes
convo.set_attribute("tone", "friendly")

# Chat with the LLM
response = convo.chat("Can you help me understand how Python dictionaries work?")
print(response)

# Later, save the conversation state
convo.save_state("conversation_backup.json")

# And load it back
new_convo = ConversationManager()
new_convo.load_state("conversation_backup.json")

4. Using dir() for Object Exploration

The Problem
When working with complex objects or APIs, it can be challenging to know what data is available to include in prompts:



def generate_data_analysis_prompt(dataset):
    # Manually specifying what we think is available
    prompt = f"""
    Dataset name: {dataset.name}
    Number of rows: {len(dataset)}

    Please analyze this dataset.
    """
    return prompt

The Solution with dir()
Python's dir() function lets us dynamically discover object attributes and methods:


def generate_data_analysis_prompt(dataset):
    # Discover available attributes
    attributes = dir(dataset)

    # Filter out private attributes (those starting with _)
    public_attrs = [attr for attr in attributes if not attr.startswith('_')]

    # Build metadata section
    metadata = []
    for attr in public_attrs:
        try:
            value = getattr(dataset, attr)
            # Only include non-method attributes with simple values
            if not callable(value) and not hasattr(value, '__dict__'):
                metadata.append(f"{attr}: {value}")
        except:
            pass  # Skip attributes that can't be accessed

    metadata_text = "\n".join(metadata)

    prompt = f"""
    Dataset metadata:
    {metadata_text}

    Please analyze this dataset based on the metadata above.
    """

    return prompt


This approach automatically discovers and includes relevant metadata without requiring us to know the exact structure of the dataset object in advance.

5. String Manipulation for Prompt Cleaning

The Problem
User inputs and other text data often contain formatting issues that can affect LLM performance:



def process_document(document_text):
    prompt = f"""
    Document:
    {document_text}

    Please summarize the key points from this document.
    """
    return call_llm_api(prompt)


The Solution with String Methods
Python's rich set of string manipulation methods can clean and normalize text:



def process_document(document_text):
    # Remove excessive whitespace
    cleaned_text = ' '.join(document_text.split())

    # Normalize line breaks
    cleaned_text = cleaned_text.replace('\r\n', '\n').replace('\r', '\n')

    # Limit length (many LLMs have token limits)
    max_chars = 5000
    if len(cleaned_text) > max_chars:
        cleaned_text = cleaned_text[:max_chars] + "... [truncated]"

    # Replace problematic characters
    for char, replacement in [('\u2018', "'"), ('\u2019', "'"), ('\u201c', '"'), ('\u201d', '"')]:
        cleaned_text = cleaned_text.replace(char, replacement)

    prompt = f"""
    Document:
    {cleaned_text}

    Please summarize the key points from this document.
    """

    return call_llm_api(prompt)


Conclusion

Python's built-in features offer powerful capabilities for enhancing LLM prompts:

Dynamic Context: Using locals() and dict to automatically include relevant variables
Introspection: Using inspect and dir() to extract rich metadata from objects and functions
String Manipulation: Using Python's string methods to clean and normalize text

By leveraging these built-in features, you can create more robust, maintainable, and dynamic LLM interactions. The techniques in this article can help you move beyond static prompt templates to create truly adaptive and context-aware LLM applications.
Most importantly, these approaches scale well as your LLM applications become more complex, allowing you to maintain clean, readable code while supporting sophisticated prompt engineering techniques.
Whether you're building a simple chatbot or a complex AI assistant, Python's built-in features can help you create more effective LLM interactions with less code and fewer errors.

💾 Redis Is Open Source Again – What that means ?

Imagine you’ve been using a powerful tool for years to help you build apps faster. Yeah its Redis, a super fast database that helps apps remember things temporarily, like logins or shopping cart items. It was free, open, and loved by developers.

But one day, the team behind Redis changed the rules. They said

“You can still use Redis, but if you’re a big cloud company (like Amazon or Google) offering it to others as a service, you need to play by our special rules or pay us.”

This change upset many in the tech world. Why?

Because open-source means freedom you can use it, improve it, and even share it with others. Redis’s new license in 2024 took away some of that freedom. It wasn’t completely closed, but it wasn’t truly open either. It hurts AWS, Microsoft more.

What Happened Next?

Developers and tech companies didn’t like the new rules. So they said,

“Fine, we’ll make our own open version of Redis.”

That’s how a new project called Valkey was born, a fork (copy) of Redis that stayed truly open-source.

Fast forward to May 2025 — Redis listened. They said

“We’re bringing back the open-source spirit. Redis version 8.0 will be under a proper open-source license again: AGPLv3.”

What’s AGPLv3?

It’s a type of license that says:

  • ✅ You can use, change, and share Redis freely.
  • 🌐 If you run a modified Redis on a website or cloud service, you must also share your changes with the world. (still hurts AWS and Azure)

This keeps things fair: no more companies secretly benefiting from Redis without giving back.

What Did Redis Say?

Rowan Trollope, Redis’s CEO, explained why they had changed the license in the first place:

“Big cloud companies were making money off Redis but not helping us or the open-source community.”

But now, by switching to AGPLv3, Redis is balancing two things:

  • Protecting their work from being misused
  • And staying truly open-source

Why This Is Good News

  • Developers can continue using Redis freely.
  • The community can contribute and improve Redis.
  • Fair rules apply to everyone, even giant tech companies.

Redis has come full circle. After a detour into more restricted territory, it’s back where it belongs in the hands of everyone. This shows the power of the developer community, and why open-source isn’t just about code, it’s about collaboration, fairness, and freedom.

Checkout this blog from Redis https://redis.io/blog/agplv3/

Weekly report 19 2025

  • Last weekend, Kids had their talent show at Tamil school. Happy to see all the kids in school, participated and performed well.
  • Spring is here in Canada. Its time for Cherry Blossoms. We visited High park and Kariya Park. Happy to see the trees with pink/rose colors. Read more here about it. https://en.wikipedia.org/wiki/Cherry_blossom
  • Attended KanchiLUG meet on sunday morning. If you know tamil and in Tech, dont miss the thoughtful discussions at KanchiLUG meet, every sunday. Check the calendar here – https://kaniyam.com/events/
  • At the meet, we discussed collecting open data for tamil. After the meet, wrote a code for scrapping for wordpress code and started to scrap the contents in CC license. Working on adding more features like resuming when stopped, alerts etc. Will share code and data soon.
  • Gave a online Talk on Tamil data collection on 05.05.2025. Will share the video soon.
  • Released few videos on GenAI in tamil, by Nithya. Watch them here – https://www.youtube.com/nithyaduraisamy
  • I am using facebook in computer. Annoyed by the short videos, advertisements, was looking for a way to get cleaner content. I want only the content from my friends, the pages I follow and the groups I am in. I dont want any other thing. Fortunately, found a nice firefox plugin. fbcleaner – https://addons.mozilla.org/en-US/firefox/addon/fbcleaner/

    With this plugin, the timeline is a breeze. It is available only for computer. Use this and save time.
  • By using computer, to access social media, I am more mindful. Not spending too much time there.
  • Completed reading two books. I am enjoying reading the physical books nowadays.
    1. எம்டன் செல்வரத்தினம், சென்னையர் கதைகள்
    2. நரகத்தில் இருந்து ஒரு குரல் – சாரு நிவேதிதா
  • Took G1 test for car driving. It is like LLR in india. After getting G1, we can learn driving car. After some 8 months, we can get G2 license, to drive car alone. Will learn car driving soon.

GIT configure in VSCode

Create a Github account:
https://github.com/pradeep-xxx

Create a repository and choose the generated link:
https://github.com/pradeep-xxx/python_workouts.git

Use in VS code Terminal:
PS C:\Users\para\Documents\PYTHON> git init
PS C:\Users\para\Documents\PYTHON> git config --global user.name "Pradeep xxx"
PS C:\Users\para\Documents\PYTHON> git config --global user.email "pradeep.xxxx@gmail.com"

PS C:\Users\para\Documents\PYTHON> git remote add origin https://github.com/pradeep-xxx/python_works.git

PS C:\Users\para\Documents\PYTHON> git add . [OR]
git add ToDoList.py ToDoList2.py todotask.txt todotask2.txt

PS C:\Users\para\Documents\PYTHON> git commit -m "Initial Commit" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add selected Python and text files" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add ToDoList.py, ToDoList2.py, todotask.txt, and todotask2.txt"

PS C:\Users\para\Documents\PYTHON> git push --set-upstream origin master [OR -1st time]
PS C:\Users\para\Documents\PYTHON> git push

Redis for Python - via Docker - No direct WSL

Redis doesn’t officially support native Windows installations anymore. Instead of setting up WSL (Windows Subsystem for Linux), Docker is the easier and more modern way to run Redis on a Windows machine.

Installing Docker Desktop gives you a full environment where you can run Redis (and many other tools) without friction.

🔹 Step 1: Install Docker Desktop
Download and install Docker Desktop from:
https://www.docker.com/products/docker-desktop/

Once installed:
Make sure Docker is running (look for the whale icon in your system tray).
Enable WSL2 integration if prompted during installation.

🔹 Step 2: Pull and Run Redis
Open PowerShell or Command Prompt and run:

docker run --name my-redis -p 6379:6379 -d redis
docker ps

🔹 Step 3: Connect to Redis
docker exec -it my-redis redis-cli
set name "DockerRedis"
get name
ping

Install RedisInsight and connect to:
https://redis.io/insight/
Host: localhost
Port: 6379

To find out whether your Windows PC uses an ARM64 or AMD64 (also called x64) architecture, follow these
from Command Prompt you can run:

C:\Users\pepsara>echo %PROCESSOR_ARCHITECTURE%

AMD64

C:\Users\pepsara>docker version
Client:
Version: 28.0.4
API version: 1.48
Go version: go1.23.7
Git commit: b8034c0
Built: Tue Mar 25 15:07:48 2025
OS/Arch: windows/amd64
Context: desktop-linux

Server: Docker Desktop 4.40.0 (187762)
Engine:
Version: 28.0.4
API version: 1.48 (minimum version 1.24)
Go version: go1.23.7
Git commit: 6430e49
Built: Tue Mar 25 15:07:22 2025
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.7.26
GitCommit: 753481ec61c7c8955a23d6ff7bc8e4daed455734
runc:
Version: 1.2.5
GitCommit: v1.2.5-0-g59923ef
docker-init:
Version: 0.19.0
GitCommit: de40ad0

C:\Users\pepsara>docker info

✅ Step-by-Step: Use Redis with Python in VS Code
🔧 1. Install Redis client for Python
In your terminal (inside VS Code), run:
pip install redis

🧪 2. Test Redis Connection in Python
Create a new Python file, e.g., redis_test.py, and add the following code:
import redis

Connect to Redis

r = redis.Redis(host='localhost', port=6379, db=0)

Set a key

r.set('mykey', 'Hello Redis!')

Get the key

value = r.get('mykey')
print(value.decode('utf-8')) # Output: Hello Redis!

Then run it: python redis_test.py
You should see: Hello Redis!

Financial Freedom is a long-term game. Why?

Imagine working hard for years, and then, after some time, reaching a point where you no longer need to work for the rest of your life. You can choose to work if you enjoy it, but otherwise, there’s no obligation. Sounds cool, right?

That is financial freedom. Today, I want to share my insights on financial freedom — why it’s important, how to train the mind psychologically for it, and why it’s a long-term game.

So, without wasting any time, let’s dive in.

What is Financial Freedom?

As I’ve already explained, financial freedom means living life without the need to work when you don’t want to.

Why is it Important?

We all have dreams. I do too. But can we achieve them easily? TBH, no. And why is that?

Because money isn’t readily available to us in the way we need it. However, once you achieve financial freedom, these dreams become possible.

So, how do you achieve it? If you ask me that, here’s what I’d say:

Training the Mind Psychologically

How do we train our minds psychologically, and why should we?

We need to condition our minds to avoid spending money unnecessarily. Many people, including myself, wonder: “I keep saving, but I see no results.”

Hold on — I’m not telling you to just save money aimlessly.

There are various saving and investing strategies, like the 60–40 rule, but I don’t follow them. Instead, I prefer a different approach:

Step 1: Build an Emergency Fund

Imagine your health suddenly declines, and you’re unable to work. What happens to your family if they depend on your salary? That’s why you need an emergency fund.

Personal Advice: Don’t save money just as cash. Instead, buy gold.

Many might think, “Okay, Anand, then I’ll buy gold jewelry.” But no, you need to buy gold coins or biscuits, depending on the amount you can invest. Your emergency fund should cover at least one year of expenses.

Why gold? Because of inflation, currency depreciation, and more. TBH, if I were to write about it, it would take at least two or more blogs. But to keep it simple, buy gold and store it safely for emergency situations.

Step 2: Get Insurance

Once you’ve secured an emergency fund, you’re slightly safe. Even if you face job loss or an unexpected crisis, you won’t be in immediate financial trouble.

The next step is taking out insurance for yourself and your family.

But TBH, insurance can be a headache. Choosing the wrong one becomes an unnecessary financial burden. So, do your research — watch YouTube videos, compare policies, and make an informed decision.

Step 3: Investing in Stocks and Bonds

At this stage, you now have an emergency fund + insurance, so you’re financially safer for the time being.

Now, it’s time to learn about the stock market and bonds and start investing.

Alert: I am not a SEBI-registered financial advisor; I am only sharing my personal thoughts.

Study stocks — understand their book value, integrity, and overall market behavior before investing. If you’re wondering where to learn about this, I recommend checking out Almost Everything, Animated Book Show, and Money Pechu — they provide great book summaries on stock market investing and psychology.

If you have extra money, don’t put it all in an FD (Fixed Deposit) because FD returns don’t even match inflation. Instead, consider bonds.

Salary Breakdown

Your salary should be distributed as follows:

Salary = Insurance + Investment + Expenses

Pay for insurance and investments first, then spend on expenses. If you spend first, you’ll struggle to invest. It’s human nature, boss.

Other Important Financial Practices

1. Practice Delayed Gratification:
Whenever you want to buy something, don’t purchase it immediately — even if you have the money. Stop yourself.

Wait for days, weeks, or even months. If, after a month, you still genuinely need it, then buy it.

Trust me, when you follow this method, you’ll notice that most of the things you initially wanted weren’t necessary. I am 100% sure about this.

2. Follow Your Mother’s Budgeting Practices:
Your mother is an excellent guide for financial management. TBH, I was shocked to realize that, despite studying personal finance extensively, my mother was already applying many smart financial practices — except investing.

Learn from her in areas like expense tracking, monthly budgeting, and financial discipline.

3. Avoid Spending via UPI Payments:
If you make transactions using UPI, even spending ₹10,000 won’t feel like a big deal. But when you pay in cash, you will hesitate — and that hesitation helps control spending.

Psychology Matters in Investing

Whenever you study investment-related content — whether through books, podcasts, or videos — also listen to at least one book on psychology.

Psychology plays a huge role in financial decisions.

Financial Freedom: A Long-Term Game

If you follow these principles for 10 to 20 years, your returns will be unbelievable.

Some may react by saying, “Are you kidding me? What will I do after achieving financial freedom in 10–20 years?”

Here’s my reply: Even Warren Buffett, one of the greatest investors in the world, became a billionaire at age 55.

Just think about it. I don’t want to scare you, but this is reality. Many jobs aren’t permanent, and financial security ensures an enjoyable life, not just for you but for your entire family.

TBF, following all these steps is tough — even for me. I’m still a beginner, like you. But compared to most people, I might be on step 5 or 10.

Final Thoughts

As already said, when you feel this content is valuable, follow me for more upcoming Blogs.

Connect with Me:

  • LinkedIn: Anand Sundaramoorthy
  • Instagram: @anandsundaramoorthysa
  • Email: sanand03072005@gmail.com

Weekly report 19 2025

  • Last weekend, Kids had their talent show at Tamil school. Happy to see all the kids in school, participated and performed well.
  • Spring is here in Canada. Its time for Cherry Blossoms. We visited High park and Kariya Park. Happy to see the trees with pink/rose colors. Read more here about it. https://en.wikipedia.org/wiki/Cherry_blossom
  • Attended KanchiLUG meet on sunday morning. If you know tamil and in Tech, dont miss the thoughtful discussions at KanchiLUG meet, every sunday. Check the calendar here – https://kaniyam.com/events/
  • At the meet, we discussed collecting open data for tamil. After the meet, wrote a code for scrapping for wordpress code and started to scrap the contents in CC license. Working on adding more features like resuming when stopped, alerts etc. Will share code and data soon.
  • Gave a online Talk on Tamil data collection on 05.05.2025. Will share the video soon.
  • Released few videos on GenAI in tamil, by Nithya. Watch them here – https://www.youtube.com/nithyaduraisamy
  • I am using facebook in computer. Annoyed by the short videos, advertisements, was looking for a way to get cleaner content. I want only the content from my friends, the pages I follow and the groups I am in. I dont want any other thing. Fortunately, found a nice firefox plugin. fbcleaner – https://addons.mozilla.org/en-US/firefox/addon/fbcleaner/

    With this plugin, the timeline is a breeze. It is available only for computer. Use this and save time.
  • By using computer, to access social media, I am more mindful. Not spending too much time there.
  • Completed reading two books. I am enjoying reading the physical books nowadays.
    1. எம்டன் செல்வரத்தினம், சென்னையர் கதைகள்
    2. நரகத்தில் இருந்து ஒரு குரல் – சாரு நிவேதிதா
  • Took G1 test for car driving. It is like LLR in india. After getting G1, we can learn driving car. After some 8 months, we can get G2 license, to drive car alone. Will learn car driving soon.

❌