❌

Normal view

There are new articles available, click to refresh the page.
Yesterday β€” 1 June 2025Main stream

Java Methods

By: Prasanth
30 May 2025 at 16:31

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;
    }
}

}








Constructor

By: Prasanth
23 May 2025 at 15:25

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




}
}

static and non static

By: Prasanth
20 May 2025 at 15:42

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

By: Prasanth
19 May 2025 at 13:40

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

Before yesterdayMain stream

To-Do Application on Spring boot

14 April 2025 at 20:13

I am going to create To-do list.

Spring boot dependencies.

  1. spring boot web
  2. jdbc postgreSQl driver
  3. spring- JPA
  4. Thyme-leaf

Entities

I am going to create two entities. They are task and Todo. It has one to many, It means todo has many task. Create the field and getter and setter methods.

TodoList class

It has id, name and List<Task>. Create getter and setter method.

Then we create bidirectional relationship between todo have task. so we create mappedBy the todo object on task. so task can create foreign key for todo list.

@Entity
public class TodoList {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	
	@OneToMany(mappedBy = "todoList", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER)
	private List<Task> taskList= new ArrayList<>();
	
	@ManyToOne
	@JoinColumn(name = "user_idn")
	private Users users;
	// no-arg constructor and getter and setter
}

Task class

It has id and name and todo object. Then we create getter and setter method.

The foreign key create in this table, because we mapped this todo object is mapped on that class. joinColumn name is the foreign key name.

@Entity
public class Task {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private boolean status;
//	private Locale locale; // date and time

	@ManyToOne
	@JoinColumn(name = "todo_list_id")
	private TodoList todoList;
}

Repository Interface

Simple that create two interface one for task and todo which can extend the JPARepository.

public interface TaskRepository extends JpaRepository<Task, Long> {
     }

     public interface TaskRepository extends JpaRepository<Task, Long> {
     }

DB and JPA configuations

 spring.datasource.url=jdbc:postgresql://localhost:5432/login
spring.datasource.username=progres
spring.datasource.password=1234
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Controller class with html

We are going to create 7 task with frontend html with thyme leaf. Map the class with β€œ/todos” using @RequestMapping.

Click the arrow or triange (|>) to see full details.

1. show all todo list

It method is used to default page of /todos page. It have List of Todo and newlist which can return to html page.

@GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }
2. create the todo list

Then we press create list button on html. we got newlist from getMapping that List pass through @modelAttribute. That list can save in repository.

  @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }
3. show tasks from todo list

Then we enter into the a list, it have many task. That can be shown by this method. we get the list by id and we pass that list of task and new task to html.

     @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }
4. create the task from todo list

Then we press create task button on html. we got new task from getMapping that task pass through @modelAttribute. That list can save in repository.

  // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
5. Toggle the task or not

Then we press todo checkbox it can be tick. Same find the task by taskId. That task setCompleted and save it again in task. Return redirect://todos/+listId, it redirect to getMapping or this Todo List.

     // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
6. delete the todo list

Then we press delete button from list on html. we remove from repository. Return the getMapping of current list.

     @PostMapping("/{listId}/delete")
    public String deleteTask(@PathVariable Long listId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }
7. delete the task from task list

Then we press delete button on html. We delete task from task repository. We return and redirect to getmapping of current task list.

  @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }

Controller full code

  @Controller
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    private TodoListRepository todoListRepository;
    
    @Autowired
    private TaskRepository taskRepository;

    // Show all todo lists
    @GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }

    // Create new todo list
    @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }

    // Show tasks from todo list
    @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }

    // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Delete a task
    @PostMapping("/{listId}/tasks/{taskId}/delete")
    public String deleteTask(@PathVariable Long listId, @PathVariable Long taskId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }

    // Delete a todo list
    @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }
}

Html code

Html has two page one for todo list and another for task list.

Todo list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Todo Lists</title>
	<link rel="icon" type="image/x-icon" href="/aaeranLogo.ico" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>My Todo Lists</h1>
	    <!-- Form to create new todo list -->
    <form th:action="@{/todos}" th:object="${newTodoList}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New list name" required>
            <button type="submit" class="btn btn-primary">Create List</button>
        </div>
    </form>

	<!-- display the todo list -->
    <div th:each="todoList : ${todoLists}" class="card mb-3">
        <div class="card-body">
			
		   <h2 class="card-title">
                <a th:href="@{/todos/{id}(id=${todoList.id})}" th:text="${todoList.name}">List Name</a>
                <span class="badge bg-secondary" th:text="${todoList.taskList.size()}">0</span>
            </h2>
            
            <form th:action="@{/todos/{id}/delete(id=${todoList.id})}" method="post" class="d-inline">
                <button type="submit" class="btn btn-sm btn-danger">Delete List</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Task.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Tasks</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>Tasks for <span th:text="${todoList.name}">List Name</span></h1>
    <a href="/todos" class="btn btn-secondary mb-3">Back to Lists</a>
    
    <!-- Form to add new task -->
    <form th:action="@{/todos/{id}/tasks(id=${todoList.id})}" th:object="${newTask}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New task description" required>
            <button type="submit" class="btn btn-primary">Add Task</button>
        </div>
    </form>
    
    <div th:each="task : ${todoList.taskList}" class="card mb-2">
        <div class="card-body d-flex align-items-center">
            <form th:action="@{/todos/{listId}/tasks/{taskId}/toggle(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="me-3">
                <input type="checkbox" 
                       th:checked="${task.status}" 
                       onChange="this.form.submit()"
                       class="form-check-input" 
                       style="transform: scale(1.5);">
            </form>
            
            <span th:class="${task.status} ? 'text-decoration-line-through text-muted' : ''" 
                  th:text="${task.name}" 
                  class="flex-grow-1">Task description</span>
            
            <form th:action="@{/todos/{listId}/tasks/{taskId}/delete(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="ms-2">
                <button type="submit" class="btn btn-sm btn-danger">Delete</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Reference :

Deploy our Spring boot application for free.

14 April 2025 at 18:46

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

To-Do Application on Spring boot

I am going to create To-do list.

Spring boot dependencies.

  1. spring boot web
  2. jdbc postgreSQl driver
  3. spring- JPA
  4. Thyme-leaf

Entities

I am going to create two entities. They are task and Todo. It has one to many, It means todo has many task. Create the field and getter and setter methods.

TodoList class

It has id, name and List<Task>. Create getter and setter method.

Then we create bidirectional relationship between todo have task. so we create mappedBy the todo object on task. so task can create foreign key for todo list.

@Entity
public class TodoList {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	
	@OneToMany(mappedBy = "todoList", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER)
	private List<Task> taskList= new ArrayList<>();
	
	@ManyToOne
	@JoinColumn(name = "user_idn")
	private Users users;
	// no-arg constructor and getter and setter
}

Task class

It has id and name and todo object. Then we create getter and setter method.

The foreign key create in this table, because we mapped this todo object is mapped on that class. joinColumn name is the foreign key name.

@Entity
public class Task {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private boolean status;
//	private Locale locale; // date and time

	@ManyToOne
	@JoinColumn(name = "todo_list_id")
	private TodoList todoList;
}

Repository Interface

Simple that create two interface one for task and todo which can extend the JPARepository.

public interface TaskRepository extends JpaRepository<Task, Long> {
     }

     public interface TaskRepository extends JpaRepository<Task, Long> {
     }

DB and JPA configuations

 spring.datasource.url=jdbc:postgresql://localhost:5432/login
spring.datasource.username=progres
spring.datasource.password=1234
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Controller class with html

We are going to create 7 task with frontend html with thyme leaf. Map the class with β€œ/todos” using @RequestMapping.

Click the arrow or triange (|>) to see full details.

1. show all todo list

It method is used to default page of /todos page. It have List of Todo and newlist which can return to html page.

@GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }
2. create the todo list

Then we press create list button on html. we got newlist from getMapping that List pass through @modelAttribute. That list can save in repository.

  @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }
3. show tasks from todo list

Then we enter into the a list, it have many task. That can be shown by this method. we get the list by id and we pass that list of task and new task to html.

     @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }
4. create the task from todo list

Then we press create task button on html. we got new task from getMapping that task pass through @modelAttribute. That list can save in repository.

  // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
5. Toggle the task or not

Then we press todo checkbox it can be tick. Same find the task by taskId. That task setCompleted and save it again in task. Return redirect://todos/+listId, it redirect to getMapping or this Todo List.

     // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
6. delete the todo list

Then we press delete button from list on html. we remove from repository. Return the getMapping of current list.

     @PostMapping("/{listId}/delete")
    public String deleteTask(@PathVariable Long listId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }
7. delete the task from task list

Then we press delete button on html. We delete task from task repository. We return and redirect to getmapping of current task list.

  @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }

Controller full code

  @Controller
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    private TodoListRepository todoListRepository;
    
    @Autowired
    private TaskRepository taskRepository;

    // Show all todo lists
    @GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }

    // Create new todo list
    @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }

    // Show tasks from todo list
    @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }

    // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Delete a task
    @PostMapping("/{listId}/tasks/{taskId}/delete")
    public String deleteTask(@PathVariable Long listId, @PathVariable Long taskId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }

    // Delete a todo list
    @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }
}

Html code

Html has two page one for todo list and another for task list.

Todo list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Todo Lists</title>
	<link rel="icon" type="image/x-icon" href="/aaeranLogo.ico" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>My Todo Lists</h1>
	    <!-- Form to create new todo list -->
    <form th:action="@{/todos}" th:object="${newTodoList}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New list name" required>
            <button type="submit" class="btn btn-primary">Create List</button>
        </div>
    </form>

	<!-- display the todo list -->
    <div th:each="todoList : ${todoLists}" class="card mb-3">
        <div class="card-body">
			
		   <h2 class="card-title">
                <a th:href="@{/todos/{id}(id=${todoList.id})}" th:text="${todoList.name}">List Name</a>
                <span class="badge bg-secondary" th:text="${todoList.taskList.size()}">0</span>
            </h2>
            
            <form th:action="@{/todos/{id}/delete(id=${todoList.id})}" method="post" class="d-inline">
                <button type="submit" class="btn btn-sm btn-danger">Delete List</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Task.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Tasks</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>Tasks for <span th:text="${todoList.name}">List Name</span></h1>
    <a href="/todos" class="btn btn-secondary mb-3">Back to Lists</a>
    
    <!-- Form to add new task -->
    <form th:action="@{/todos/{id}/tasks(id=${todoList.id})}" th:object="${newTask}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New task description" required>
            <button type="submit" class="btn btn-primary">Add Task</button>
        </div>
    </form>
    
    <div th:each="task : ${todoList.taskList}" class="card mb-2">
        <div class="card-body d-flex align-items-center">
            <form th:action="@{/todos/{listId}/tasks/{taskId}/toggle(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="me-3">
                <input type="checkbox" 
                       th:checked="${task.status}" 
                       onChange="this.form.submit()"
                       class="form-check-input" 
                       style="transform: scale(1.5);">
            </form>
            
            <span th:class="${task.status} ? 'text-decoration-line-through text-muted' : ''" 
                  th:text="${task.name}" 
                  class="flex-grow-1">Task description</span>
            
            <form th:action="@{/todos/{listId}/tasks/{taskId}/delete(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="ms-2">
                <button type="submit" class="btn btn-sm btn-danger">Delete</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Reference :

Deploy our Spring boot application for free.

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

Collections Tasks

By: Sugirtha
19 November 2024 at 01:55

TASKS:

  • // 1. Reverse an ArrayList without using inbuilt method
  • // 2. Find Duplicate Elements in a List
  • // 3. Alphabetical Order and Ascending Order (Done in ArrayList)
  • // 4. Merge Two Lists and Remove Duplicates
  • // 5. Removing Even Nos from the List
  • // 6. Array to List, List to Array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


public class CollectionsInJava {
	public static void main(String[] args) {
		// 1. Reverse an ArrayList without using inbuilt method
		// 2. Find Duplicate Elements in a List 
		// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
		// 4. Merge Two Lists and Remove Duplicates
		// 5. Removing Even Nos from the List
		// 6. Array to List, List to Array
		ArrayList<String> names = new ArrayList<>(Arrays.asList("Abinaya", "Ramya", "Gowri", "Swetha",  "Sugi", "Anusuya", "Moogambigai","Jasima","Aysha"));
		ArrayList<Integer> al2 = new ArrayList<>(Arrays.asList(100,90,30,20,60,40));
		
		ArrayList<Integer> al =  insertValuesIntoAL();
		System.out.println("Before Reversing ArrayList="+ al);
		System.out.println("Reversed ArrayList="+ reverseArrayList(al));
		
		System.out.println("Duplicates in ArrayList="+findDuplicates(al));
		
		System.out.println("Before Order = "+names);
		Collections.sort(names);
		System.out.println("After Alphabetical Order = " + names);
		Collections.sort(al);
		System.out.println("Ascending Order = "+ al);
		
		System.out.println("List -1 = "+al);
		System.out.println("List -2 = "+al2);
		System.out.println("After Merging and Removing Duplicates="+mergeTwoLists(al,al2));
		System.out.println("After Removing Even Nos fromt the List-1 = "+removeEvenNos(al));
		
		arrayToListViceVersa(al,new int[] {11,12,13,14,15}); //Sending ArrayList and anonymous array
	}
	
	// 1. Reverse an ArrayList without using inbuilt method
	private static ArrayList<Integer> reverseArrayList(ArrayList<Integer> al) {
		int n=al.size();
		int j=n-1, mid=n/2;
		for (int i=0; i<mid; i++) {
			int temp = al.get(i);
			al.set(i, al.get(j));
			al.set(j--, temp);
		}
		return al;
	}
	
	// 2. Find Duplicate Elements in a List 
	private static ArrayList<Integer> findDuplicates(ArrayList<Integer> al) {
		HashSet<Integer> hs = new HashSet<>();
		ArrayList<Integer> arl = new ArrayList<>();
		for (int ele:al) {
			if (!hs.add(ele)) arl.add(ele);
		}
		return arl;
	}
	
	//4. Merge Two Lists into one and Remove Duplicates
	private static HashSet<Integer> mergeTwoLists(ArrayList<Integer> arl1,ArrayList<Integer> arl2) {
		ArrayList<Integer> resAl = new ArrayList<>();
		HashSet<Integer> hs = new HashSet<>();
		hs.addAll(arl1);
		hs.addAll(arl2);
		return hs;
	}
	
	// 5. Removing Even Nos from the List
	private static ArrayList<Integer> removeEvenNos(ArrayList<Integer> al) {
		ArrayList<Integer> res = new ArrayList<>();
		Iterator itr = al.iterator();
		while (itr.hasNext()) {
			int ele = (int)itr.next();
			if (ele%2==1) res.add(ele);
		}
		return res;
	}
	
	// 6. Array to List, List to Array
	private static void arrayToListViceVersa(ArrayList<Integer> arl, int[] ar) {
		Integer arr[] = arl.toArray(new Integer[0]);
		System.out.println("Convert List to Array = " + Arrays.toString(arr));
		List<Integer> lst = Arrays.asList(arr);
		System.out.println("Convert Array to List = " +  lst);
	}
	
	private static ArrayList<Integer> insertValuesIntoAL() {
		Integer[] ar = {30,40,60,10,94,23,05,46, 40, 94};
		ArrayList<Integer> arl = new ArrayList<>();
		Collections.addAll(arl, ar);
		//Collections.reverse(al);   //IN BUILT METHOD
		return arl;
			//Arrays.sort(ar);  
		//List lst = Arrays.asList(ar);    //TBD
		//return new ArrayList<Integer>(lst);
		
	}

}

OUTPUT:

Exception Handling

By: Sugirtha
13 November 2024 at 03:06

What is Exception?

An Exception is an unexpected or unwanted event which occurs during the execution of a program that typically disrupts the normal flow of execution.

This is definition OK but what I understand : The program’s execution is getting stopped abnormally when it reaches some point which have some mistake/error – it may be small or big, compilation or runtime or logical mistake. And its not proceeding with further statements. Handling this situation is called exception handling. Cool. Isn’t it?

Why Exception Handling?

If we do not handle the exception program execution will stop. To make the program run smoothly and avoid stopping due to minor issues/exceptions, we should handle it.

So, how it is represented, In Java everything is class, right? The derived classes of java.lang.Throwable are Error and Exception. For better understanding lets have a look at the hierarchical structure.

Here I could see Exception and Error – when we hear these words looks similar right. So What could be the difference?

Errors are some serious issues which is beyond our control like System oriented errors. Ex. StackOverFlowError, OutOfMemoryError (Lets discuss this later).

Exception is a situation which we can handle,

  1. through try-catch-(finally) block of code
  2. Throws keyword in method signature.

try-catch-Finally :

What is the meaning? As we are the owner of our code, we do have some idea about the possible problems or exceptions which we can solve or handle through this try-catch block of code.

For Ex. Task : Make a Tasty Dish.

What could be the exceptions?

  1. Some spice added in lower quantity.
  2. Chosen vessel may be smaller in size
  3. some additional stuff may not be available

To overcome these exception we can use try-catch block.

try {
  Cooking_Process();
}
catch(VesselException chosenLittle) {
   Replace_with_Bigger_One();
}
catch(QtyException_Spice spiceLow) {
   add_Little_More_Spice();
}
catch(AddOnsException e) {
  ignore_Additional_Flavors_If_Not_Available();
}
catch(Exception e) {
  notListedIssue();
}
Finally {
  cleanUp_Kitchen();
}

Here there could be more catches for one try as one task may encounter many different issues. If it is solvable its called exception and we try to catch in catch blocks. The JVM process our code (cookingProcess) and if it encounter one problem like QtyException_Spice, it will throw the appropriate object. Then it will be caught by the corresponding catch, which will execute add_Little_More_Spice() and prevent the code from failing.

Here we see one more word, Exception, which is the parent class of all exceptions. Sometimes we may encounter the issue that is not listed (perhaps forgotten) but its solvable. In such cases, we can use the parent class object (since a parent class object can act as a child object) to catch any exception that is not listed.

Fine, all good. But what is the purpose of Finally here? Finally is the block of code that will always be executed, no matter if exception occurs or not. It doesn’t matter if you made a good dish or a bad one, but the kitchen must be cleaned. The same applies here: the finally block is used for releasing system resources that were mainly used (Ex. File). However, we can also write our own code in the finally block based on the specific requirements.

We have a situation where you have one cylinder to cook, and it gets emptied during cooking, so we cannot proceed. This will fail our process TastyDish, this situation cannot be handled immediately. This is called Error. Now lets recall the definition β€œErrors are serious issues that are beyond our control like a system crash or resource limitations.” Now we could understand, right?

Ex. OutOfMemoryError – when we load too much data, JVM runs out of memory. StackOverFlowError – when an infinite loop or recursion without base condition will make the stack overflow.

Lets revisit exceptions – they can be classified into two categories:

  • Checked Exception
  • UnChecked Exception.

What is Checked Exceptions?

Checked Exception is the exception which occurs at compile time. It will not allow you to run the code if you are not handling through try-catch or declares throws method.

Lets get into deeper for the clear understanding, the compiler predicts/doubts the part of our code which may throw the exceptions/mistakes which lead to stopping the execution. So that it will not allow you to run, it is forcing you to catch the exception through the above one of mechanisms.

If it is not clear, let us take an example, in the above code we have VesselException and QtyException_Spice . You are at your initial stage of cooking under the supervision of your parent. So we are ordered/ instructed to keep the big vessel and the spices nearby in case you may need it when the problem arise. If you are not keeping it nearby parent is not allowing you to start cooking (initial time ). Parent is compiler here.

throws:

So Expected exception by the compiler is called Checked Exception, and the compiler force us to handle. One solution we know try-catch-finally, what is that through declaration in the method? The exception in which method can be expected, that method should use the keyword β€œthrows <ExceptionClassName-1>” that is, it specifies this method may lead to the exceptions from the list of classes specified after throws keyword. After throws can be one class or more than one. whoever using this method with this declaration in method signature will aware of that and may handle it.

The good example for this is, IOException (parent) – FileNotFoundException (child). If you are trying to open a file, read it, the possible exceptions are: File Path Incorrect, File doesn’t exist, File Permission, Network issues etc. For Ex.

public static void main(String[] args) {
        try {
            // Calling the method that may throw a FileNotFoundException
            readFile("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            // Handle exception here
            System.out.println("File not found! Please check the file path.");
            e.printStackTrace();
        }
    }   

 // Method that throws FileNotFoundException
    public static void readFile(String fileName) throws FileNotFoundException {
        File file = new File(fileName);
        Scanner scanner = new Scanner(file);  // This line may throw FileNotFoundException
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }

What is Unchecked Exception?

The compiler will not alert you about this exception, instead you will experience at runtime only. This not required to be declared or caught, but handling is advisable. These are all subclasses of RunTimeException (Error also will throw runtime exception only). It could be thrown when runtime issues, illegal arguments, or programming issues.

Ex.Invalid index in an array, or trying to take value from a null object, or dividing by zero.

Ex. NullPointerException

String str = null; System.out.println(str.length()); /* Throws NullPointerException */

ArrayIndexOutOfBoundsException

int[] arr = new int[3]; System.out.println(arr[5]); /* Throws ArrayIndexOutOfBoundsException */

What is throw?

Instead JRE throws error, the developer can throw the exception object (Predefined or UserDefined) to signal some erroneous situation and wants to stop the execution. For ex, you have the idea of wrong input and wants to give your own error message.

public class SampleOfThrow {
    public static void main(String[] args) {
        // a/b --> b should not be 0
        Scanner scn = new Scanner(System.in);
        int a = scn.nextInt();
        int b = scn.nextInt();
        if (b==0) throw new ArithmeticException("b value could not be zero");
        System.out.print(a/b);
    }
}

Hey, wait, I read the word, User Defined Exception above. which means the developer (we) also can create our own exception and can throw it. Yes, absolutely. How? In Java everything is class, right? So through class only, but on one condition it should extend the parent Exception class in order to specify it is an exception.

//User Defined Exception
class UsDef extends Exception {
    public UsDef(String message) {
        super(message); //will call Exception class // and send the own error message
    }
}

public class MainClass {
    public static void main(String[] args) {
        try {
            Scanner scn = new Scanner(System.in);
            boolean moreSalt = scn.nextBoolean(); 
            validateFood(moreSalt);
 // This method will throw an TooMuchSaltException
        } catch (TooMuchSaltException e) {
            System.out.println(e.getMessage());  // Catching and handling the custom exception
        }
    }

    // Method that throws TooMuchSaltException if food contains too much salt and can't eat
    public static void validateFood(boolean moreSalt) throws TooMuchSaltException {
        if (moreSalt) {
            throw new TooMuchSaltException("Food is too salty.");
        }
        System.out.println("Salt is in correct quantity");
    }
}

Now Lets have a look at some important Exception Handling points in java of view. (The following are taken from chatGPT)

Error Vs. Exception

AspectErrorException
DefinitionAn Error represents a serious problem that a Java application cannot reasonably recover from. These are usually related to the Java runtime environment or the system.An Exception represents conditions that can be handled or recovered from during the application’s execution, usually due to issues in the program’s logic or input.
Superclassjava.lang.Errorjava.lang.Exception
RecoveryErrors usually cannot be recovered from, and it is generally not advisable to catch them.Exceptions can typically be caught and handled by the program to allow for recovery or graceful failure.
Common TypesOutOfMemoryError, StackOverflowError, VirtualMachineError, InternalErrorIOException, SQLException, NullPointerException, IllegalArgumentException, FileNotFoundException
Occurs Due ToTypically caused by severe issues like running out of memory, system failures, or hardware errors.Typically caused by program bugs or invalid operations, such as accessing null objects, dividing by zero, or invalid user input.
Checked or UncheckedAlways unchecked (extends Throwable but not Exception).Checked exceptions extend Exception or unchecked exceptions extend RuntimeException.
Examples– OutOfMemoryError
– StackOverflowError
– VirtualMachineError
– IOException
– SQLException
– NullPointerException
– ArithmeticException
HandlingErrors are usually not handled explicitly by the program. They indicate fatal problems.Exceptions can and should be handled, either by the program or by throwing them to the calling method.
PurposeErrors are used to indicate severe problems that are typically out of the program’s control.Exceptions are used to handle exceptional conditions that can be anticipated and managed in the program.
Examples of Causes– System crash
– Exhaustion of JVM resources (e.g., memory)
– Hardware failure
– File not found
– Invalid input
– Network issues
ThrowingYou generally should not throw Error explicitly. These are thrown by the JVM when something critical happens.You can explicitly throw exceptions using the throw keyword, especially for custom exceptions.

Checked vs. Unchecked Exception:

AspectChecked ExceptionUnchecked Exception
DefinitionExceptions that are explicitly checked by the compiler at compile time.Exceptions that are not checked by the compiler, and are typically runtime exceptions.
SuperclassSubclasses of Exception but not RuntimeException.Subclasses of RuntimeException.
Handling RequirementMust be caught or declared in the method signature using throws.No explicit handling required; they can be left uncaught.
ExamplesIOException, SQLException, ClassNotFoundException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Common UsageTypically used for exceptional conditions that a program might want to recover from.Used for programming errors or unforeseen runtime issues.
Checked atCompile-time.Runtime (execution time).
Effect on CodeForces the developer to handle the exception (either with a try-catch or throws).No such requirement; can be ignored without compiler errors.
Examples of CausesMissing file, network failure, database errors.Null pointer dereference, dividing by zero, illegal array index access.
When to UseWhen recovery from the exception is possible or expected.When the error typically indicates a bug or programming mistake that cannot be recovered from.

throw vs. throws:

Aspectthrowthrows
DefinitionUsed to explicitly throw an exception from a method or block of code.Used in a method signature to declare that a method can throw one or more exceptions.
UsageUsed with an actual exception object to initiate the throwing of an exception.Used in the method header to inform the compiler and the caller that the method might throw specific exceptions.
Keyword TypeStatement (flow control keyword).Modifier (appears in the method declaration).
Examplethrow new IOException("File not found");public void readFile() throws IOException { ... }
LocationCan be used anywhere inside the method or block to throw an exception.Appears only in the method signature, usually right after the method name.
ControlImmediately transfers control to the nearest catch block or exits the program if uncaught.Allows a method to propagate the exception up the call stack to the caller, who must handle it.
Checked vs UncheckedCan throw both checked and unchecked exceptions.Typically used for checked exceptions (like IOException, SQLException) but can also be used for unchecked exceptions.
Example ScenarioYou encounter an error condition, and you want to throw an exception.You are writing a method that may encounter an error (like file I/O) and want to pass the responsibility for handling the exception to the caller.

References : 1. https://www.geeksforgeeks.org/exceptions-in-java/

How to create Servlet and Deploy on Apache Tomcat 10.1 in Linux

4 April 2023 at 17:00

I am going to explain about how to create servlet and Deploy on Apache Tomcat Server 10.1 manually in any Linux distributions.

Directory Structure should be represented asΒ below

directory structure to runΒ servlets

You can keep β€˜aaavvv’ folder as any name youΒ want.

How to create Servlet on Apache Tomcat 10 inΒ Linux

Step:1

Create a folder in /usr/share/tomcat10/webapps folderΒ , In that folder create any folder name as you like, I create β€˜myapps’ folder name asΒ example.

cd /usr/share/tomcat10/webapps/;sudo mkdirΒ myapps

Step:2

Go into myappsΒ , then create β€˜WEB-INF’ directory

cd myapps;sudo mkdirΒ WEB-INF

Step:3

Go into WEB-INF, then create β€˜classes’ directory

cd WEB-INF;sudo mkdirΒ classes

Step:4

Go into classes directory, and create java file named β€˜TeamTesters.java’ for this example, you can create any name youΒ want.

cd classes;sudo nano TeamTesters.java

code for TeamTesters.java

Step:5

Run java program using javacΒ command

sudo javac TeamTesters.java -cp /usr/share/tomcat10/lib/servlet-api.jar

here -cp represents classpath to run theΒ program

Step:6

Go to backward directory (i.e., WEB-INF) and copy the web.xml file from ROOT directory present in the webapps folder present in tomcat10Β folder

cdΒ ..;sudo cpΒ ../../ROOT/WEB-INF/web.xml web.xml;

Then edit web.xml file by adding <servlet> and <servlet-mapping> tag inside <web-app> tag

sudo nanoΒ web.xml

<servlet> and <servlet-mapping> in web.xmlΒ file

Step:9

Goto backward directoryΒ , (i.e., aaavvv) then create index.html file

cdΒ ..; sudo nano index.html

content in index.html

Step:10

goto browser andΒ type,

http://localhost:8080/myapps

servlet running onΒ browser
Statement printed on html page declared inΒ java

Common Troubleshooting problems:

  1. make sure tomcat server and java latest version is installed on your systemΒ .
  2. check systemctl or service status in your Linux system to ensure that tomcat server isΒ running.

Automate thisΒ stuff…

If you wanted to automate this stuff… checkout my github repository

GitHub - vishnumur777/ServletCreationJava


How to create Servlet and Deploy on Apache Tomcat 10.1 in Linux was originally published in Towards Dev on Medium, where people are continuing the conversation by highlighting and responding to this story.

Finding SubArray

By: Sugirtha
30 October 2024 at 11:23
package taskPkg;

import java.util.Scanner;

public class SubArray {

	public static void main(String[] args) {
		// FINDING SUBARRAY AND ITS POSITION
		System.out.println("Enter a sentence to search in.");
		Scanner scn = new Scanner(System.in);
		String sentn = scn.nextLine();
		System.out.println("Enter a word to be searched.");
		String word = scn.next();
		scn.close();
		char[] sentence = sentn.toCharArray();
		char[] key = word.toCharArray();
		int n = sentence.length, m = key.length;
		int i = 0, j = 0, st = 0; // i- maintain index in the sentence, j-maintain index in key
		boolean match = false;
		while (i < n && j < m) {// 
			//System.out.println("i=" + i + "     sentence[i]=" + sentence[i] + "    j=" + j + "   key[j]=" + key[j]);
			if (sentence[i] == key[j]) { //if it matches incrementing both pos
				i++;
				j++;
				if (j == m) { //if the key reaches end, made the match and exit
					match = true;
					break;
				}
			} 
			else {    // if no match move on to the next letter, but key should start from 0
				j = 0;
				i=st+1;
				st = i;  // this is to save the starting of the subarray
			}
		}
		if (match)
			System.out.println("SubArray is found at " + st);
		else
			System.out.println("SubArray is not found");
	}
}

OUTPUT:

2D Matrix Addition, Multiplication, Largest in EachRow, Is Descending Order

By: Sugirtha
27 October 2024 at 17:25
package taskPkg;

public class MatrixCalc {
	public static void main(String[] args) {
		// 1. MATRIX ADDITION ( A + B )
		// 2. MATRIX MULTIPLICATION ( C*D ) IF C is nxk AND D IS kxm RESULTANT MUST BE
		// nxm
		int[][] A = { { 4, 2, 5 }, { 6, 3, 4 }, { 8, 1, 2 } };
		int[][] B = { { 5, 1, 3 }, { 2, 3, 2 }, { 1, 6, 4 } };
		int[][] C = { { 4, 2 }, { 2, 1 }, { 5, 3 } };
		int[][] D = { { 1, 2, 3 }, { 3, 2, 5 } };
		int[] desc = { 9, 5, 2, 1 };
		int[][] M = new int[C.length][D[0].length];

		MatrixCalc matOp = new MatrixCalc();
		matOp.add(A, B);
		System.out.println("-------------------------");
		matOp.multiply(C, D, M);
		System.out.println("-------------------------");
		matOp.LargestInEachRow(M);
		System.out.println("-------------------------");
		matOp.isDescendingOrder(desc);
	}

	private void add(int[][] A, int[][] B) {
		int r = A.length, c = A[0].length;
		int[][] S = new int[r][c];
		for (int i = 0; i < r; i++) {
			for (int j = 0; j < c; j++) {
				S[i][j] = A[i][j] + B[i][j];
			}
		}
		print2Darray(A, "A");
		print2Darray(B, "B");
		System.out.println("SUM : S = A+B");
		print2Darray(S, "S");
		System.out.println();
	}

	private void multiply(int[][] C, int[][] D, int[][] M) {
		int n = C.length, q = D.length, m = D[0].length;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				for (int k = 0; k < q; k++) {
					M[i][j] += C[i][k] * D[k][j];
				}
			}
		}
		print2Darray(C, "C");
		print2Darray(D, "D");
		System.out.println("MULTIPLY : M = CxD");
		print2Darray(M, "M");
	}

	private void LargestInEachRow(int[][] M) {
		int L[] = new int[M.length];
		System.out.println("LARGEST IN EACH ROW OF : M ");
		System.out.print("[");
		for (int i = 0; i < M.length; i++) {
			L[i] = M[i][0];
			for (int j = 0; j < M[0].length; j++) {
				L[i] = L[i] < M[i][j] ? M[i][j] : L[i];
			}
			System.out.print(" " + L[i] + " ");
		}
		System.out.println("]");
	}

	private void isDescendingOrder(int[] des) {
		boolean desc = true;
		System.out.print("Array des [");
		for (int i = 0; i < des.length; i++) {
			System.out.print(" " + des[i] + " ");
			if (i > 0 && desc && des[i - 1] < des[i])
				desc = false;
		}
		System.out.println("]");
		if (desc)
			System.out.println("Given Array des is In Descending Order");
		else
			System.out.println("Given Array des is NOT In Descending Order");
	}

	private void print2Darray(int[][] ar, String arName) {
		System.out.print("Array " + arName + " : ");
		for (int i = 0; i < ar.length; i++) {
			if (i > 0)
				System.out.print("          ");
			System.out.print("[");
			for (int j = 0; j < ar[0].length; j++) {
				System.out.print(" " + ar[i][j] + " ");
			}
			System.out.println("]");
		}
		System.out.println();
	}

}

OUTPUT:

Simple Student Mark List

By: Sugirtha
27 October 2024 at 10:08

import java.util.Scanner;

public class Array2DstudentsMarks {
	Scanner scn = new Scanner(System.in);
	String stud[];
	int[][] marks;
	int[] tot, highestScorer;
	int subj, totHighStud;
	public static void main(String[] args) {
		// STUDENTS MARKS WITH TOTAL - 2D ARRAY
		Array2DstudentsMarks twoDArray =  new Array2DstudentsMarks();
		twoDArray.studentMarksTotal();
		twoDArray.dispMarkAndTotal();
	}

	private void studentMarksTotal() {
		System.out.println("Enter no. of Students");
		int n = scn.nextInt();
		System.out.println("Enter no. of Subjects");
		subj = scn.nextInt();
		stud = new String[n];
		marks = new int[n][subj];
		tot = new int[n];
		highestScorer= new int[subj];
		int maxTot = 0, highScore=0;
		for (int i=0; i<n; i++) {
			System.out.println("Enter Student name.");
			stud[i] = scn.next(); 

			System.out.println("Enter "+subj+" subjects marks of "+stud[i]+" one by one.");
			for (int j=0; j<subj; j++) {
				marks[i][j] = scn.nextInt();
				tot[i] += marks[i][j];
				if (marks[highestScorer[j]][j] < marks[i][j]) {
					highestScorer[j] = i;
					//highScore = marks[i][j];
				}
			}
			if (maxTot < tot[i]) {
				maxTot = tot[i];
				totHighStud = i;
			}
		}
	}
	private void dispMarkAndTotal() {
		System.out.println("------------------------------------------------------------------------");
		System.out.println("                       STUDENTS MARK LIST                               ");
		System.out.println("------------------------------------------------------------------------");
		for (int i=0; i<stud.length; i++) {
			System.out.println("Student Name : "+stud[i]);
			for (int j=0; j<subj; j++) {
				System.out.println("Subject-"+(j+1)+" = "+marks[i][j]);
			}
			System.out.println();
			System.out.println("Total Marks = "+tot[i]);
			System.out.println("Percentage = "+(tot[i]/subj)+ "%");	
			System.out.println("------------------------------------------------------------------------");
		}
		for (int i=0; i<highestScorer.length; i++) {
			int student = highestScorer[i];
			System.out.println("Subject-"+(i+1)+" Highest Mark is "+marks[student][i]+" achieved by "+stud[student]);
		}
		System.out.println("------------------------------------------------------------------------");
		System.out.println("Over All Highest Total "+tot[totHighStud]+" achieved By "+stud[totHighStud]);
		System.out.println("------------------------------------------------------------------------");
	}
}

OUTPUT:

Playing with Char Array

By: Sugirtha
24 October 2024 at 09:23
    // 1. REMOVING UNWANTED SPACE
    // 2. CAPITALIZE EACH WORD
package taskPkg;

import java.util.Scanner;

public class PlayingWithCharAr {

	public static void main(String[] args) {
		// 1. REMOVING UNWANTED SPACE
		// 2. CAPITALIZE EACH WORD
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a sentence...");
		String sentence = scn.nextLine();
		scn.close();
		char[] sen = sentence.toCharArray();
		PlayingWithCharAr obj = new PlayingWithCharAr();
		obj.removeSpace(sen);
		obj.wordStartWithCaps(sen);
	}

	private void removeSpace(char[] words) {
		int k = 0, n = words.length;
		System.out.print("Removed unwanted spaces :");
		while (k < n && words[k] == ' ')
			k++;
		for (; k < n - 1; k++) {
			if (!(words[k] == ' ' && words[k + 1] == ' '))
				System.out.print(words[k]);
		}
		if (words[n - 1] != ' ')
			System.out.print(words[n - 1]);
		System.out.println();
	}

	private void wordStartWithCaps(char[] words) {
		int i = 0, n = words.length;
		System.out.print("Capitalize Each Word :");
		if (words[i] != ' ')
			System.out.print((char) (words[i] - 32));
		for (i = 1; i < n; i++) {
			if (words[i - 1] == ' ' && words[i] != ' ' && (words[i] >= 'a' && words[i] <= 'z'))
				System.out.print((char) (words[i] - 32));
			else
				System.out.print(words[i]);
		}
	}

}

OUTPUT:

Password Validator

By: Sugirtha
23 October 2024 at 18:17
import java.util.Scanner;

public class PasswordValidator {

	public static void main(String[] args) {
		// PASSWORD MUST CONTAIN MIN 8 CHARS, MAX 12 CHARS, ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT, 1 SPL CHAR 
		Scanner scn = new Scanner(System.in);
		int maxLen = 12, minLen=8;
		System.out.println("Enter a password to validate");
		String pwd = scn.next();
		scn.close();
		int n = pwd.length();
		if (n<minLen || n>maxLen) {
			System.out.println("Password length must be between 8 to 12 characters");
			return;
		}
		char[] pw = pwd.toCharArray();
		int cntLower=0, cntUpper=0, cntDigit=0, cntSpl=0;
		for (int i=0; i<n; i++) {
			char ch = pw[i];
			if (ch>='A' && ch<='Z') cntUpper++;
			else if (ch>='a' && ch<='z') cntLower++;
			else if (ch>='1' && ch<='9') cntDigit++;
			else if (ch=='!' || ch=='Β£' || ch=='$' || ch=='%' || ch=='^' || ch=='&' || ch=='*' || ch=='-' || ch=='_' || ch=='+' || ch=='=' || ch==':' || ch==';' || ch=='@'|| ch=='#'|| ch=='~'|| ch=='>'|| ch=='<'|| ch=='?'|| ch=='.') cntSpl++; 
		}
		if (cntLower>0 && cntUpper>0 && cntDigit>0  && cntSpl>0) System.out.println("Password is valid...");
		else {
			System.out.println("Password is NOT VALID");
			System.out.println("PASSWORD MUST CONTAIN ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT AND 1 SPL CHAR FROM ! Β£ $ % ^ & * - _ + = : ; @ ~ # ?");
		}
	}

}

Arrays Task

By: Sugirtha
22 October 2024 at 18:29
  1. First Letter Occurrence, Last Letter Occurrence in the given Word
  2. Print Reversed Array
  3. Cricketers array and their best score array – Give name as input and get the high score.
package taskPkg;
import java.util.Scanner;
public class ArraysBasics {
//1. PRINTING 1ST LETTER OF THE CHAR ARRAY
//2. PRINT REVERSED A CHAR ARRAY	
//3. 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArraysBasics obj = new ArraysBasics();
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a name to find its first and Last Letter.");
		String nam =  scn.next();
		char[] name = nam.toCharArray();
		System.out.println("First Letter of "+nam+" is repeated at "+obj.findFirstLtr(name));
		System.out.println("Last Letter of "+nam+" is repeated at "+obj.findLastLtr(name));
		obj.printReversedArray(name);
		System.out.println();  
		
		String[] cricketers = {"Rohit","Suryakumar","Ashwin", "Jadeja","Yashasvi"}; 
		int[] scores = {100,120,86,102,98};
		System.out.println("Enter one cricketer name to get his high score");
		String givenName = scn.next();
		System.out.println("Score for " + givenName+  " is "+obj.getScore(cricketers,scores,givenName));
		
		
	}
	private int findFirstLtr(char name[]) {
		char ch = name[0];
		for (int i=1; i<name.length; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private int findLastLtr(char name[]) {
		char ch = name[name.length-1];
		for (int i=0; i<name.length-1; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private void printReversedArray(char[] name) {
		System.out.println("Reversed Array = ");
		for (int i=name.length-1; i>=0; i--) {
			System.out.println(" "+name[i]);
		}
	}
	private int getScore(String[] name, int[] score, String givenName) {
		int n = name.length;
		for(int i=0; i<n; i++) {
			if(name[i].equals(givenName)) return score[i];
		}
		return 0;
	}
	
}

OUTPUT:

Pattern Printing – Others

By: Sugirtha
21 October 2024 at 02:01
public class Patterns {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//PRINTING 1's and 0's IN SPECIFIC PATTERN
		int n=5;
		Patterns ptn = new Patterns();
		ptn.pattern1(n);
		System.out.println();
		ptn.pattern2(n);
		System.out.println();
		ptn.pattern3("SUGIRTHA");
	}
	private void pattern1(int n) {
		int val=0;
		for (int r=1; r<=n; r++) {
			val = r%2==0?0:1;
			for (int c=1; c<=n-r+1; c++) {
				System.out.print(" "+val);
				val=1-val;
			}
			System.out.println();
		}
	}
	private void pattern2(int n) {
		int val=1;
		for (int r=1; r<=n; r++) {
			for (int c=1; c<=n-r+1; c++) {
				System.out.print(" "+val);
			}
			val=1-val;
			System.out.println();
		}
	}
	private void pattern3(String name) {
		int n = name.length();
		for (int r=1; r<=n; r++) {
			for (int c=0; c<r; c++) {
				System.out.print(" "+name.charAt(c));  //TBD 
			}
			System.out.println();
		}
	}

}

OUTPUT:

Patterns – Printing Numbers 0-9

By: Sugirtha
20 October 2024 at 17:01
package taskPkg;

public class PatternsPrintNos {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PatternsPrintNos ptnNos = new PatternsPrintNos();
		int n=9;
		for (int i=0; i<=9; i++) {
			ptnNos.printNo(i,n);
			System.out.println();
		}
	}
	private void printNo(int num, int n) {
		int m=n/2+1;
		switch(num) {
		case 0:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || c==1 || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;			
		case 1:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (c==m) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 2:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || (r<=m && c==n) || (c==1 && r>=m)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 3:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || c==n) System.out.print(" *"); 
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 4:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if ((c==1 && r<=m) || c==m ||  r==m ) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 5:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || (r<=m && c==1) || (c==n && r>=m)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 6:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (c==1  ||  r==n || r==m || (r>m && c==n)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 7:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || (c==n-r+1)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 8:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==m || r==n || c==1 || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;		
		case 9:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==m || (c==1 && r<=m) || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;				
		}

	}
}

Output:

❌
❌