Reading view

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

Java Methods

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

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

Syntax

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

Access Modifiers:-

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

Method overloading:

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

Method Overriding:-

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

Types of methods:

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

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

without method

public class Test_Withoutmethod {

    public static void main(String[] args) {

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

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

}

with method:


public class Test_withMethod {


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

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


    public static void main(String[] args) {

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

}

Method Defining and Calling with return types and void :-


// method  defining and  calling
public class Method_Example1 {

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

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

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

    }

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

        return total;


    }

}


swapping values inside method:-

public class Method_SwappingValue {

public static void main(String[] args) {

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

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

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



}

}

Method&Calling_Passing_Parameters

public class Method_Passing_Parameters {

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

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

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

static void sendLetter(String sender,String career) {

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

    }

}

Example: method using to return value and void

public class JavaReturnandVoid{

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


    }

static void samInfo(int i, int j) {

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


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

}

static int myAccountBalance(int AccountBalnce ) {

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


}

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

public class MethodReturnExample {

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


}

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

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

return sum;

}
//3. return string

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

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

return new Object[] {id,name};

}

}



<u> Important Return Type Scenarios</u>

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


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


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

public class MethodandBlock_Scope_Example {

public static void main(String[] args) {

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

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

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

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


}

}



<u>Java Recursion:-</u>



package java_Method;

// Factorial Using Recursion
public class Recursion_Example {

int fact(int n)
{
    int result;

    if (n==1)

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

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


}


public static void main(String[] args) {

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

/*

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

    }

}


package java_Method;

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

public static void main(String[] args) {


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


}

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

    else
    {
        return 0;
    }
}

}








Constructor

What is constructor?

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

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

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

Constructor:-

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

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

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

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

Why Constructors Can’t Be Inherited?

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

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

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

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

Example:-

public class Parent_Child {

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

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

}


public class Child_parent  extends Parent_Child{

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


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


    }

}

Constructor cannot be overridden

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

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

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

Rules for creating java Constructor:-

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

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

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

Example:

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

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

output:-
Constructor called!

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

Creating constructor:-

Syntax

Class ClassName{



Classname()
{
}
}

Types of Java Constructors:-

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

Default constructor

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

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

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

    }
}

Example:2

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

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

    }
}

No-args Constructor.

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

Example:-


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

    }
}


Example;1

public class NoArgsConstructor {
    int id;
    String name;

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

    }

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

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

3. Parameterized Constructor

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

Example:1

public  class Parmet_Constructor {

    String name,jobStatus,jobFinding;
    static int age;

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

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


Example:2

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

Constructor Overloading:-

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

Example:

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


Example:-

public class Student_Constructor_DoandDonot {

    int id;
    String name,department;
    char gender;

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

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

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

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

=>this()

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

What this does not do:

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

=>super()

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

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

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

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

Explain constructor overloading with example?

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

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

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

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

How do this and super differ?

Image description

When is constructor called in real life?

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

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

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

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

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

Allowed Modifiers/Keywords for Constructors

Allowed

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

Not Allowed

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

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

Constructor Programme:

this() using constructor:

super() using construtor:-

package inheritence;

public class Vehicle {
int speed;


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


    }

}

package inheritence;

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

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

    public static void main(String[] args) {

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

}

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

this() Example Program


public class Student {

    int id; 
    String name;

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

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

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

    public static void main(String[] args) {

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

}

Constructor vs Method

Image description

copy constructor:-

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

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

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

what is clone() method?

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

Example:-

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

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

Important:-

what is mutable and immutable in java?

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

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

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

Example:


public class Example_Mutable_Immutable {




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

    }

}

Output:
Immutable
s1 = JavaProgramming
s2 = Java

Mutable:
sb1 = javaProgramming
sb2 = javaProgramming

shallow copy vs deep copy:-

Shallow copy(immutable fields ):-

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

Deep copy(mutable fields ):-

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

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

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

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

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


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

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

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

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

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




}
}

static and non static

static and non static

static

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

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

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

  1. static methods(class-level method)

used when:

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

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

}
}

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


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

4.static Nested class

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

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

`
call using:

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

you cannot use static :

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

Example

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

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



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


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

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


    }

}

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

non static

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

public class MyClass {
    int val =1;

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

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

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

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



    }

}

output:
obj1 val:10
obj2 val:1

  1. non-static variables (instance variable)

use when: Each object should have it own values.

example 2:

class Student 
String name;
int id;

Student (String name ,int id)

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

}


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




public  class Test {

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

}

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

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

//you must to create object to call it:

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

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

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

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

Image description

Image description

What does “belong to class” mean?

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

What does “belong to object” mean?

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

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

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

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

Valid Modifiers for Top-Level Classes:

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

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

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

Why abstract class cannot achieve 100% abstraction?
Because:

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

Why interface can achieve 100% abstraction?

Because:

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

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

Invalid Modifiers for Top-Level Classes:

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

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

class Variable {

int instancevar=10;
static int staticVar =20;

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

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




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

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

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

    }
}

Note:-

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

Java -> class & object

what is a Class in java?

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

  • No memory is allocated when a class is defined.

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

  • Class is Logical Entity,it means

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

example

class car{

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

object

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

Just think car:-

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

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

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

example

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

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

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


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

Class Name Rules:

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

example

class EmployeeDetails

Access Modifier in class

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

example 1 : inner class

public class OuterClass {

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

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

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


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


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

Top-Level Class

    Can use only:

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

Inner Class (class inside another class)

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

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

example 2 : private in outer class

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

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


// Simple term:-

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

example 3 :- protected in outer class

protected class ProtectedClass {

    public static void main(String[] args) {

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



    }

}
//protected is only useful for

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

why protected top-level class is not allowed?

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

simple say:-

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

what a class can contain

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

File name rule

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

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

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

what is object ?

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

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

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

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

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

  • Each object has its own copy of instance variables

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

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

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

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

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

Car myCar = new Car();

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

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

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

class & object

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

Example

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

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


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

    }

}

runtime and compile time

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

variable

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

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

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

syntax
datatype variablename = value;

example

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

Types of variables in java

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

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

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

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

// we will next blog heap,stack.

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

public class car {

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

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

}

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

Method-Used to Perform Actions (Behavior/Logic)

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

example

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

greet();  // calling the method

class vs object

Image description

Image description

Linux -top command

top is a monitor the system performance in real time

1.System Information

Image description

=>16:43:14 current time
=>up 4:31 system uptime is 4 hours 31 mintues
=>2 users - 2 user logged
=>load average
load-0.10 (last 1 minutes )
load-0.07 (last 5 minutes)
load-0.02 (last 15 minutes)
< 1.00 per core - good
= 1.00 per core - full used
=> > 1.00 per core - overloaded
for example
0.00 means system is idle(free) nothing do
1.00 means system busy, more then 1 overloaded

what is mean load?
no.of process waiting for cpu or input/output writing or reading from disk

=>check cpu core use nproc or lscpu after compare with core value and load average value, it tells your system low ,normal, high load

what is mean core?

each core can do one task at atime
example:
you system have 4 core ,1 work easily and fast done work.

example
*Load average value =or < or > No.of.core (nproc command use and get core value)

2.process information

Image description

=>237 - total no.of process
=>1 - one process actively running( every program in Linux treated as process)
=>236 - sleeping ,waiting particular action like user input and network request ....etc
=>0 stopped - 0 process not manually stopped
=>0 zombie - ( zombie is child process of parent process ,when parent process killed it also affect to child process ,child will takeover(adopt) the init by cleared or terminated form process table)

3.cpu usage line

Image description

us - user cpu time , used by normal process like apps ,scripts(0-50% is normal,<10% free,>70% high).
sy - system cpu time used system/kernel related tasks(good <10%,>20% system issue)
ni - nice ,it used to low priority process (0% unused, >20% id low priority jobs)
id -idle, mean cpu is free (>80% ideal,<20% heay load )
`wa` - wait i/o ,it means how much time cpu is waiting disk or network operation(<5%good ,bad>10%).
hi - hardware interrupts -> cpu time to spend handling hardware (keyboard, mouse...etc)tasks (<2% good ,bad >10%)
si -software interrupts -> cpu time to spend handling software interrupts (<2% good,bad>10%)
st - stolen time -> like stolen time virtual machine or hypervisor
mpstat -P ALL (similar to top)

4.Memory usage

Image description

total => total Ram in Mib ->1771 MiB
free => available ram
used => ram used by process
buff/cache => cached memory
avail Mem => available memory
buff/cache => memory use by system cache file and buffer data ,for example if open a file ,Linux keep the cache ,next time it faster to open file.

example:

MiB Mem
: 1771.0
MiB = Mebibyte = 1024 × 1024 bytes
1771/1024 =1.73GB
MiB Swap(vritual memory)
-swap is extra memory on HDD or SDD ,used only ram is full, ram is full inactive data moved swap place ,it avoid to system crash and other things .ram is very fast(rabbit), swap is slower(tortoise).

5.process Table

Image description

PID
=> process id ,in kernel every process to allocate the pid ,that pid stored in the /proc directory after kill or closed process, this process disappear.

USER => who(which user) run the process
PR =>priority of process like lower to higher
NI => nice value set the new process priority value ,renice command change nice priority value
VIRT => swap + Ram = virtual memory(total memory)
RES => only for physical ram
SHR => shared memory
S => process status, s-sleep, R-Running, z-Zombie, X -dead, T-stopped, I -idle
%CPU => cpu usage of process
%MEM => total ram used
TIME+ =>total cpu run time
COMMAND => command running ,name of the command or program that started the process

key of top commands:-

M => sort the memory usage
P => sort the cpu usage
T => sort Time
k => kill the process ( press k button then system ask pid then signal number you can see different signal was $kill -l( mostly used 1,9,15,2,3 the we will depth info kill command )
r => renice process priority
(k and r only work sudo top)
q => quit
z => switch the color for visibility
shift +e => switch the memory to display kb, gb, mb.
h=> help
1 =>display the cpu usage core level
top -u prasanth362k - display specific user
top -p pid=> display the specific process
top -d 1(number)=> delay updates in minutes top command

Centos-PackageManager

RPM(Red Hat Manager)

  • RPM is a low-level package manager of RHEL-based Linux system ,that is used to install, install ,update, remove and verify software packages. It mange .rpm(example: package.rpm) packages files, do not resolve the dependencies automatically and used manual installation and troubleshooting.

RPM options:-

rpm -ivh pacakge.rpm => install the package

-i = install
-v = verbose output(detailed information)
-h = show download progress.

rpm -qa => list all installed package
-q= querry
-a= all

rpm -Vf /path/to/package-file
=> verify the system modifed or not(auditing purpose)

Image description

output meanings:-

S- file size changed
M- permission changed
D - device major/minor number changed
L - sym link changed
U- user ownership changed
G - group ownership changed
c - configuration changed
T- Timestamp changed ( file modified date/time)
5 - MD5 checksum changed(file content changed)
. - Nothing changed

rpm -ev package-name => remove the pacakges
rpm -qf package-name => find out which package a file belong to

Image description

rpm -Fvh mypackage.rpm => -F is used for freshening installed package ( if already installed , it will be upgrade it)
-l => list file installed package
-qi => get info about package.

YUM(yellowdog updater, modified)

  • YUM is a package manager for RPM based linux system ,that automatically resolve dependencies when installing , updating, or removing software.
  • YUM configuration file location => /etc/yum.conf or/etc/yum.repo.d(later we will discuss local repo creation for offline package installation) YUM options:-

yum clean all => clean the yum cache directory
yum list all=> To show all available installed and available packages
yum list installed => To show all available installed packages .

yum install telnet => To install particular package
yum remove telnet => To remove particular package
yum search httpd => To search httpd related package give format like package name and description , summaries.

yum list httpd => check httpd installed or not and what are the version package is available
yum info httpd => Details about httpd

yum repolist
=> list the enabled repositories
$ sudo yum update => update

dnf (Dandified YUM)

  • It's faster, more reliable and handle dependencies better than yum . Syntax is almost same as yum .dnf faster and handling dependencies improved. sudo dnf install httpd -y=> Auto confirmation

dnf list intalled | grep httpd => check if package already installed or not.

Linux Configuration: Hostnames, Networking, sudo and Basic of Wildcards.

Table-content:-

  1. Wildcards in Linux
  2. Hostname setup
  3. Basic network Setup
  4. sudo configuration

1.Wildcards

  • In Linux wildcards are special character used in the command line to match multiple files or directory. They mostly used with command like ls, cp ,mv,

=> * match any characters, including zero charters

  1. ls *.log -> list the log files
  2. rm temp*
  3. mv *.txt directory/

=> ? match the exact one character like single character
1.ls file?.txt
list the file1 to file9 but to list out file10.txt
2.mv log?.txt logs/
move logs files from log1.txt to log9.txt
=> [] match the one character from set.
1.ls file[12].txt
list out only file1.txt and file2.txt not file3.txt
2.ls [abc]*.txt
list only matching character like a, b, c
=> [!] match any character except those inside brackets

1.ls file[!1].txt
list all .txt file except file1.txt
2.ls [!abc]*.txt
list all .txt except a, b ,c character

=> {}Expand to comma separate the values
1.touch {file1,file2,file3}.txt
create mutiple fiel once
2.delete specific files
rm {error,server,server}.log
3.copy the multiple file types


cp *.{jpg,png,gif,txt} backupdir/

** match file in subdirectories and

  1. ls **/*.txt find the all .txt file in all subdirectories
  2. rm **/*.log delete .log files inside any folder

Escape character \ prevent wildcard:

  • main purpose of using the escape character \ is to disable wildcard expansion or treat special characters as normal text in command.

Example:-

rm *text.txt -> delete all files ending in text.txt
rm \*test.txt-> delete only one fie named as *text.txt

**2. Hostname setup

**

I. Check host name

$ hostname

output:-

cyber.TAMIL.com

II. check hostname full info
**
$ hostnamectl or hostname status

*III. Change hostname temporarily
*

$ hostname Cyber.TAMIL.com

**IV. Change hostname permanently in terminal

$ hostnamectl set-hostname Cyber.TAMIL.com

V. Change hostname permanently in configuration file

$ sudo vim /etc/hostname

Output:-

Centos.TAMIL.com

=> you can press i button (insert mode) then Esc , save :wq then , sudo reboot or exec bash(refresh the shell)

VI. /etc/hosts (hostname <-> ip mapping)

*This file maps hostnames to ip address for local name resolution not applicable for Network-wide Resolution.

Example:-

$ sudo vim /etc/hosts

127.0.0.1 oldhostname

you can modify:-

127.0.0.1 newhostname

For real network-wide hostname resolution:

  • Set up a DNS server (like BIND, dnsmasq, or Unbound).Configure all machines to use the DNS server for hostname resolution.

3. Basic network Setup:-

I.# nmclid d -> shows all network iterface.
II. # nmcli d show eth0s3(my interface_name) -> Display details of eth0s3

III. Set the Static ip address

Image description

$sudo systemctl restart Networkmanger

or
$nmcli networking off && nmcli networking on

Restart on specific Network interface.

sudo ifdown eth0 && sudo ifup eth0

id=eth0 -> name of the network connection.
uuid=<uniqid> -> unique identifier (auto generated)
type=ethernet -> wired ethernet connection
autoconnect=true -> the system automatically connect the interface on boot
interface-name=eth0 → Ensures the settings apply only to eth0.
permissions=-> Restrict who can modify this connection (empty means restricted)
permissions=username1;username2; -> only can access specific user


timestamp=0
-> last modification timestamp(optional)

2 [ethernet] Section

mac-address= -> mac address of your network card, optional but useful for binding configuration.

3. [ipv4] Section (Static IP Settings)

method=manual -> assign the static ip address
addresses=192.168.1.100/24;
ip address -> 192.168.1.100
sub netmask -> /24
gateway=192.168.1.1 -> Default router IP
dns=8.8.8.8;1.1.1.1;
if you want to dynamic ip set only
[ipv4]
method=auto
dns=8.8.8.8;1.1.1.1;
ignore-auto-dns=true

-> google 8.8.8.8 & 1.1.1.1 Cloudflare servers,ignore-auto-dns=true -> prevent Dhcp fri changing your dns settings, use always manual Dns settings.
may-fail=false -> Forces the system to wait for a network connection before booting. I f network fails ,the system won't start until it's connected, it useful for server , may-fail=true the system will boot even if the network fails, it useful for desktop ,computer.

4. [ipv6] Section (Disabling IPv6)

method=ignore
-> Disable the IPv6 completely.
or
method=auto -> automatically get an ipv6 address.

Network manger GUI( CentOS, RHEL, Fedora)

$nmtui(text based gui )
(you can set Ip adress like static and dynamic)

Ip address:-
Ip address is unique ID your device ina device and allow device to communicate each other .
Types of version
ipv4 => 32 bit length ,format decimal with dots,
32-bit → it means 32 digits of 0s and 1s (binary)
Example
11000000.10101000.00000001.00000001 → this is 192.168.1.1 in binary
Each section (octet) = 8 bits
=> 8 bits × 4 = 32 bits
Total possible IPs = 2³² = 4,294,967,296 addresses

ipv6 => 128 bit leng . format hexa decimal wit colons
Total possible IPs = 2¹²⁸ = 340 undecillion (massive!)

!.private ip
it used to local networks like home wifi, offices,LAN. can not be accessed for the internet directly,if you want to access to internet use NAT ( take your private ip translatd to your router's public ip)

IP Range Class Devices Covered
10.0.0.0 – 10.255.255.255 A Very large private networks
172.16.0.0 – 172.31.255.255 B Medium networks
192.168.0.0 – 192.168.255.255 C Home/Small offices

  1. public ip

It used on the network, assigned by isp, unique globally and communicate with public avilable website and server and app.

  1. loopback ip
    used to testing purpose own system, you can not communicate the other system.

  2. gateway

the default router(gateway) used to send data outside your local networks ,without gateway your device can not reach the web ,gateway acts bridge between your device and the internet.

for realife example:-
you send a letter -post office(gateway) that post man(isp) send that the letter to destination point.

3.subnetmask
it used define local network range and help your device identify who is same network and who is not.

4.Broadcast address :
Special IP that sends data to all devices in your network.

Example:
in meting chat box say hi everyone instead text everyone

4.Sudo configuration:-

$sudo -l (check the who has the sudo access)
$sudo -l -U username
$sudo useradd username

$sudo gpasswd -a username wheel
or
$sudo usermod -aG wheel username
(add the user to wheel group)
$sudo gpasswd -d username wheel
(disabling the user to wheel group)

whell = defaul admin group of centos/RHEL os
$sudo visudo (edit the sudoers file)
(or)
$sudo visudo /etc/sudoers

Image description

  • I added user prasanth362k to give allow to root run any commands.

6.ALLOW a user to run only specific sudo commands :-

  • Restrict sudo access to only commands improves security and limits risks.
  • add the end of the file of /etc/sudoers without #
  • Allowing a user to run only specific commands:-
  • Tamil ALL= NOPASSWD: /bin/systemctl restart apache2( restart service with out password)
  • English ALL= PASSWD: /bin/systemctl restart apache2,/bin/systemctl restart nginx( restart service with password) -Akash ALL = PASSWD /sbin/ifconfig, /sbin/ip -Amala_paul ALL= NOPASSWD: /bin/mount, /bin/umount
  • think about ,one multination company is there work over 100000 employ , how it possible each user can set permission level . we can create group then we will restrict the group which command can execute and not execute.

Example:-

$ sudo groupadd it_team

%it_team ALL = NOPASSWD: /bin/systemctl restart apache2
%network_admin = PASSWD: /sbin/ip, /sbin/iptables
%hr_team ALL= NOPASSWD: /bin/cat /etc/payroll.conf
%dev_team ALL= NOPASSWD: /bin/git pull, /bin/systemctl restart app-service

/bin = permit only normal user can execute the small tasks like nano cat ,systemctl.

/sbin= permit only admin user can execute the system level tasks like reboot, ifconfig ,iptables.

Tamil ALL= NOPASSWD: /bin/cat =>only user Tamil environent execute command
Samantha ALL=(root) PASSWD : /bin/cat =>Samantha can run the specified command as root,password require when using sudo.

Trisha ALL=(ALL) PASSWD : /bin/cat => only Trish user can execute the command,She can run the command as any user(not regular human user) (including root) using sudo -u. password required, does not mean any user.

Example:-

sudo -u root /bin/systemctl restart apache2
sudo -u apache /bin/systemctl restart apache2
sudo -u www-data /bin/systemctl restart apache2

  • you can aks me question apche ,ww-data is user ?
  • This users all system service related specific user.

Example:-

www-data-> user all webservice like apache, nginx (debian/ubuntu)

mysql -> user for MYSQL
postgres-> user for PostgreSQL

=> Validate the sudoers file before applying changes:

$sudo visudo -c ( Check for syntax)

Vim-Editor

1.Basic vim commands

i.vim vim.txt => open file in vim
ii. :q => quit
iii. :q! => force quit
IV. :wq or ZZ => save and exit
V. :x => save and exit ,if only changes happen.

Esc (exit the current mode and return to normal mode) --> escape the mode

2.Modes in Vim:-

I. Normal Mode => Default mode (navigate and edit,delete , modifying ..etc) ,vim the default mode when open a file is Normal file.

II. Insert Mode => insert and edit the text => press i .

III. Command Mode => Execute the commands followed by : command.

IV. Visual mode => select text v for character-wise, V for line-wise.

3.Navigation Commands (Normal Mode):-

I. h => move left
II. l => move right
III.j => move down
Iv. k => move up
V. 0 => move the beginning of the file.
VI. ^ => move to first non-blank character of the line.
VII. $ => move to end of line
VIII. gg => go to beginning file
IX. G => go to end of file
X. nG => go to exact number line
example:

press any number and G , cursor move exact number line
Xi. Ctrl + d => scroll half-page down
XII. Ctrl + u => scroll half-page up
XIII. Ctrl + f = >scroll full-page down
XIV. Ctrl + b => scroll full-page up

4.Insert Mode:-

I. i => insert at cursor position
II. I => insert at beginning of line
III a => Append after cursor
IV A => Append at end of line.
"append" means adding text after the cursor
V o =>open a new line below the current line.
VI O =>open a new line Above the current line.

5.Deleting & cutting Text:-

I. x => Delete character under cursor
II. dw => Delete word
III. dd => delete entire line,3dd
IV. d0 => Delete from cursor to beginning of line
V. d$ or D => Delete from cursor to end of line
VI. dG => Delete from cursor to end of file
VII. :1,.d =>Delete from line 1 to current line
VIII. :.,$d => Delete from current line to end of file.
IX.

6.Copy & paste:-

I. yy => copy current line,3yy
II.y$ =>copy to end of line
III. yw => copy word
IV. yG => copy current cursor to end of file
V. p =>Paste after cursor
VI. P => paste before cursor.
VII. cc => deletes the entire line and enters insert mode, dd+i=c.

7.Undo & Redo:-

I. u +> undo last change
II. ctrl + r => Redo the last undone change

8.searching:-

I. /word => search for word forward ,after enter press n =same direction, press N =opposite direction
II. ?word => search for word backward ,after enter press n =same direction, press N =opposite direction
III. :%s/oldword/new_word/g => Replace all occurrences of old with new
IV.:%s/oldword/new_word/gc => Replace with confirmation

8.Important Vim option for productivity:-

I. :set number => show line number
II. :set nonumber => Hide line numbers
III.:set autoindent/:set noautoindent (தானாக உள்தள்ளல்) => Enable auto-indent
Now, when you press Enter in Insert mode, Vim will automatically indent the next line.

example:-


int x =10;
int y =20;( auto indent)
when you press Enter , the next line will start with same spaces

IV. :set tabstop=4
after executed ,when press tab key ,vim use 4 spaces
V. :set ignorgcase
after executed, when use to searching /,it do not care about uppercases and lowercase
VI. :set hlsearch
after executed, when use to searching /,highlighted the words

10.Working with multiple files:-

After opened file:-
I. :e filename => open another file
II. :bn => swith to next file
III. :bp => switch to previous file
IV. :bd => close current file
V. :sp => split screen and open file
VI. :vsp => verticular split screen
VII. :tabenew filename => open file in a new tab
VIII. :gt => go to next tab
IX. :gT => go to previous tab
X. :tabclose => close current tab
XI. :tabonly => close other all tabs except current.
XII. ctr + w + w => switch b/w splits.(works in both horizontal & vertical splits).

Linux-Basic command

Table-content:

1.Terminal Cursor movement
2.Basic commands
3.Standard Streams in Linux

1.Terminal Cursor movement

i. Ctrl + A - move to the beginning of the lin e
ii. Ctrl + E - Move to the end of the line
iii. Ctrl + B -- Move backward one character
iv. Ctrl + F - move forward one character
v. Alt + B - Move backward one word
vi. Alt + F - Move forward one word
vii. Ctrl + R - Reverse search command history, Ctrl + R after press up Arrow.
viii. Ctrl + G cancel search history.
ix. Ctrl + L - clear the terminal
X. TAB - auto completion filename or command
xi. Ctrl + Z - stop the current command and resume wit fg in foreground or bg in background
xii. !! = repeat last command.

2.Basic commands

1.check current working directory

=> #pwd

output:-

/root

2.check current logged user

i. $ whoami- Display the username of currently logged in user.
ii.$ who - shows all logged user along with terminal sessions
iii. $ w - shows all logged user along with terminal sessions with activities.

3.chck the system hostname

i. $ hostname

ii. Show the detailed information about Hostname
$ hostnamectl
iii. check system ip & mac with help of hostname
$ hostname -I
(we will see, up coming blogs how to set the hostname temporarily and permanent)

4. check ip address

$ ip a
$ ip addr
$ ifconfig
(we will see, up coming blogs how to set the ip address ,gateway, broadcast,...etc, permanent and detailed result information)
5.clear the screen - $ clear

6.man = man is manual page of all command provide detailed documentation, syntax, options, example.

example:-

$ man ls

7.sudo
sudo is you allows you run command as super user ( admin privileges)

Example:-

$ sudo dnf update
- dnf is RHCL based package manger

8.$ history
-used to find out all those commands we ran previously.

9. create directory(folder)

`$ mkdir dir

$ mkdir dir1 dir2

$ mkdir -p grandpa/father/son

10 . Change directory

$ cd /home/user/Documents
$ cd .. => parent directory (move up one level in the directory structure)
$ cd . -> stay in the current directory
$ cd ../../ => move up multiple level.
$ cd - => go back to the previous directory
$ cd / = change root directory
$ cd ~ = change the home directory

11. Create file:-

i. create empty file using touch

$touch file.txt
$touch file.txt file1.txt

ii. Using echo

$echo "Welcome to MyLinuxBlog" > welcome.txt

iii. using cat

$cat > file.txt

Hi, this the text file(text somthing)
then Ctr + D(save)

iv. printf

$printf " Line-1 \n Line-2 \n Line-3 " > file.txt

12. List the file and directory

i. $ ls -lah
-l = list
-a = hidden
-h = human readable format
ii. $ ls -li
-i check inode for files and directory.
iii. $ ls -R
-R = recursively search (show the content of sub-ls directory)
iv. $ ls -ld */ (list the directory only)
v. $ ls -ld .. (parent)
vi. $ ls -ld . (current)

-t = sort by modification time

13. Copy the file and directory.

$ cp f1.txt destination-path/dirname

Example:-

$ cp file.txt dir1

Source to Destination copy:

$ cp file.txt /home/user/backup/

$ cp -r dir1 /home/user/backup/

Destination to Source copy:

$ cp /home/user/backup/file2.txt /home/user

option:-

-v verbose
-i = confirmation
-n = copy with without overwriting

14. Move and rename the file and directory

Rename the file:-

mv Oldname.txt Newname.txt

Move the file:-

mv file1.txt /home/usr/backup/

mv file2.txt file3.txt /home/user/backup/

option:-

-i - before moving ask confrimation.
-u -update
-v -verbose
-f force

*same method to follow directory move and rename.

when use mv the directory why do not use -r only using cp -r for dir ?

15. Delete the File and Directory

$rmdir dir1
(empty directory)
$rm -rfi dir (delete everything inside all directory )

option:-

-i - confirmation
-r - recusively
-v - verbose
-f - force
$rm -if file.txt

*-rf * = Be careful to use this option when deletion ,make to confirm once or four before use this option, can not retrieve the data after deletion.
rm -rf * ==> (* means all)Be careful

16. cat – display the content of the file

$cat > file.txt (it create the new file ,
it waits for you enter some text(owerites)
Ctrl + D(save)
$cat >> file.txt
appends to the file without overwriting existing content.
$cat -n file.txt -> Show with line numbers
$cat file1 file2 > merged.txt -> Merge files
$cat file.txt | grep "word" -> Search for a word
$tac file.txt -> Display in reverse.

17.more -Display the content page by page only navigation to forward direction not backward direction.

Example:

$more file.txt

Enter – scroll down one line
space – scroll down one page
-q - quite

$more +n file.txt
$more -n file.txt
n = number,

Example:-

$more +10 file.txt

18. less -Display the content page by page only navigation to forward direction and backward direction.

$less file.txt

output:-

hello welcome to Linux world
/search_word

example:
/Linux
space – scroll down one page
q - quite
b – scroll up up one page
g - go the begning of the file
G -go to end of the file.

19.head -display the first few lines, not real-time monitoring.

Example:-

$head f1.txt

$head -n 420 f1.txt

$head -c 20 f1.txt

-c display first 20 byte of the file content

20.tail-display the last few lines, real-time monitoring.

Example:-

$tail f1.txt
$tail-n 420 f1.txt
$tail -c 20 f1.txt

21. Standard Streams in Linux:-

1.stdin(0) - Takes input from the keyboard and file
2.stdout(1) -shows output like what you see on the screen
3.stderr(2) -shows error message ,also on the screen

1. Standard Streams

i. Standard Input (stdin - File Descriptor 0):

  • Take the input from the user like keyboard, when run the cat, read command it required input , it wait for you type something other wise Ctr + D.

ii. Standard Output (stdout - File Descriptor 1):

*share the output on your screen like when you run echo, ls command .

Example:-

$echo "Hellow Linux world"

*echo command send to text stdout ,it displays on your screen.

iii. Standard Error (stderr - File Descriptor 2):

  • send the error message on your screen
  • when made mistake on terminal send the message stderr not for stdout.

Example:-

$cd dir1

*dir1 is not created really at the time error message sent to stderr.

2. Redirection in Linux: stdin , stdout ,stderr .

Example:-

i.Redirect Input (<):

  • Input from the keyboard:

< -> Take the input from a file instead of the keyboard .
$ sort < names.txt
$ wc -l < nmaes.txt (wc -l -word count line)

  • stdout (1) -Output to the screen: $echo "Welcome To My Blog" > file.txt

ii. Redirect Output (>):

$ echo "Hello" > file.txt
$ echo "Hello world" >> file.txt

iii. Redirect Errors (2>):

Example:-

$ls /usr/home/ 2> err.log

*/usr/home/ this actually not real path ,at the time error message sent to stderr.

output:

No such file or directory.

22.Pipe operator:-

  • Pipe operator (|) connect multiple command.

syntax:-

command1 | command2

Example:-

$ ls | wc -l
$ cat file.txt | grep "Linux" (grep- pattern searcher)

Grub

Grub: GRUb(GRand Unified Bootloader) is bootloader used in Linux system to load the operating system into primary memory RAM when computer starts. it is the first software that after runs firmware(BIOS/UEFi) complete the hardware initialization.

I.Grub2 configuration:-

  • main grub2 configuration file is /etc/default/grub
  • Actual grub2 bootloader configuration is stored in /boot/grub/grub.cfg file on Bios based machine UEFI is defer ,like /boot/efi/EFI/centos/grub.cfg ( do not edit manually it 'make trouble for when booting ),

Image description

*EFI not show why mine ? because i not generated to the exact location and my system is bios based machine.

II.Generate new grub configuration file

#grub2-mkconfig -o /boot/grub2/grub.cfg

grub2-mkconfig - generat the new grub2 config file
-o /boot/grub2/grub.cfg -specifies the output file location.

iii. check grub version

#grub-install --version

Image description

iv. view grub2 settings:-

#cat /etc/default/grub

/etc/grub.d/

Image description

/etc/grub.d/ useful fo grub detects and organizes boot entries and custom boot entry.

v. Editing Grub2 settings

*This part useful for set the boot menu timeout in second and grub boot entry and so on .

#sudo vim /etc/default/grub

Image description

let we see important only :-

i. GRUB_TIMEOUT=12

*It means 12 second delay before booting default Os in grub menu ,you can reduce time also.

ii. GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"

*Automatically sets linux distribution name in grub menu. /etc/system-release it helps to get os name with help sed command.

iii. GRUB_DEFAULT=saved

  • saves the last booted kernel and automatically boots the same one next time *You can also set GRUB_DEFAULT=0, which means the system will always boot into the first OS in the menu. Similarly, setting GRUB_DEFAULT=1 will boot into the second menu entry

iv. GRUB_TERMINAL_OUTPUT="console"

  • I force to grub display the output console mode ,that mean text mode not gui mode, you set also GRUB_TERMINAL_OUTPUT="gfxterm"

v. GRUB_DISABLE_RECOVERY="true"

  • Disable recovery mode in the boot menu ,preferred choice set as false ,incase of emergency it's useful.

vi.GRUB_ENABLE_BLSCFG=true

  • Enables loader specification ,BLS means modern boot entry format .

vii. #GRUB_HIDDEN_TIMEOUT=0

  • Uncommenting this line (by removing #) hides the GRUB menu and boots immediately after 0 seconds.

viii. GRUB_TIMEOUT_STYLE=menu

  • make sure always visible GRUB menu
  • You can set also =hidden, skipped the Grub menu immediately boot.

3.Apply the changes to grub

#sudo grub2-mkconfig -o /boot/grub2/grub.cfg

4.if grub corrupted or missing what can we do ?

1. Enter rescue mode from Grub menu

i. Restart your system
ii. press & hold Shift or press Esc for UEFI bios then GRUB menu show.

iii.select Advanced options , choose rescue mode or also called recovery mode and also c(command line interface) and e (edit) option available in grub menu.
iv press Enter to boot into rescue mode.
V. once you inside ,select into root shell prompt

2. manually Enter Rescue mode from GRUB

  • your system appeared on grub rescue at the time of problem occurred. after showed prompt you can fallow below steps. i. check all availability disk #ls

ii. find the linux root partition

=> #ls (hd0,1)/
=> #ls (hd0,2)/
=> #ls (hd0,3)/

when you see /boot/grub for like this is your boot partion.

iii. The correct the partition

*set root=(hd0,1) => set as root partion where to grub installed ,hd0 mean hard drive,1 is first partion
*set prefix=(hd0,1)/boot/grub = set the grub location
insmod normal = load grub normal mode
normal = load grub menu

3.fix the grub permanetly after booting into linux:-

sudo grub2-mkconfig -o /boot/grub2/grub.cfg
sudo grub2-install /dev/sda # Replace sda with your disk
sudo reboot

then,

regenerate the config file:-

=> #sudo update-grub

4.Boot into rescue and Emergency mode:

if you system is running but u need rescue mode fallow below steps;-

=> #sudo systemctl rescue
=> #sudo systemctl emergency

5. Boot int rescue and emergency mode using grub menu:

1.Restart your system.
2.Grub menu , select your Linux kernel.
3.after selected, press e (edit) then ,find the line starting with linux ,add the end of line below line then Ctr +x or f10

systemd.unit=rescue.target

Image description

  • Follow same steps are emergency mode

systemd.unit=emergency.target

then,remount the root filesystem in emergency mode

mount | grep " / " -current filesystem mount status
mount -o remount,rw / -remount root file system in read-write
fsck -y /dev/sdX - -sdX(yours disk) , if you want fix the filesystem . we will see detail information upcoming device management blog, then reboot.

5. Reset Root passwd

1.Restart your system.
2.Grub menu , select your Linux kernel.
3.after selected, press e (edit) then ,find the line starting with linux ,add the end of line below the command line then Ctr +x or f10

init=/bin/bash

*After see the panel type below command ,default filesystem is read-only mode,you need to remount read-write mode.
mount -o remount,rw /
*touch /.autorelabel (if your system use SELinux - Security Enhanced linux) to proctecte files.
(touch /.autorelabel if not follow this step lables get damage or lost, you get error like permission denied, can not login in after resetting root password. After reboot linux look on this empty file /.autorelabel and automatically fix security label ,after fixing system will delete the .autorelabel file and reboots again. Note:create with name of autorelabel empty file otherwise linux not understand ,because linux desinged the linux.SELinux won’t detect it, and relabeling won’t happen.
.autorelabel works because it's hardcoded in SELinux.
passwd root
exec /sbin/init (reboot)

or reboot -f

https://www.gnu.org/software/grub/manual/grub/html_node/index

https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/system_administrators_guide/ch-working_with_the_grub_2_boot_loader#sec-Making_Temporary_Changes_to_a_GRUB_2_Menu

Linux-Directory

1. / = Directory is called root directory . head/parent of the all directory.

Image description

*2./bin
*

*contains executable/program/commands to achieve the basic tasks that accessible for every system user and root user.
Eg: ls,cat,touch,cp,mv.
=> # = Root user
=> $ = Normal user

3. /sbin

=> *contains /executable/program/command to achieve the system level task or system level settings for Only root user can executable . Not accessible for normal user.
Eg: ifconfig,iptables,fsck,fdisk

*4. /dev = Linux/Unix is treats everything as file including hardware devices *

  • /dev is a directory that provides device files acting as interfaces between hardware and user-space programs. These files allow software to communicate with hardware without direct access. *what is mean user space user space - run regular program without direct access of hardware access,like browser and ,text editor, command line tool ls, cat.

/dev paths

/dev/sda - sata disk(primary device)
/dev/hda - IDE hard disk
/dev/sdb - secondary device
/dev/cdrom - CD/DVD drive
/dev/tty - terminal interface.

Two main type of device:-

i. Character device= Transfer the data byte to byte(used for serial communication),perform wise it slower and small data

Example: keyboard ,mouse, serial port,mic
/dev/tty - terminal interface,
/dev/input/mice

ii.Block device = Transfer data block to block, preform wise it faster and large data

example:

storage device:-
ssd ,usb , hhd

Image description

Image description

*we will see device management detailed info and create device and so on.

*5 . /etc
*

*Sytem directory ,it contains system-wide configuraiton file and installed program settings.it not for user specific ,does not contain binary executable like /bin or /sbin only contain text based configuration files, require root(sudo) access to modifying /etc .

  • Linux application and services read the setting from /etc . *etc/ contain ,system and network settings ,serives and boot and startup scripts......etc.

example:

$ sudo vim /etc/hostname

Image description

Common files and Directories:-

i./etc/passwd - store the use account information
ii. /etc/shaddow - store encrypted password
iii. /etc/group - define usr gourps
iv. /etc/hosts - map to hostanme to ip address
v. /etc/fstab - contains info on mounted(connected) filesystems
vi. .etc/hostanme - view hostnbame and also u can edit
vii. /etc/reslov.conf - configure of dns settings
viii. /etc/network/interfaces - stores nework configuration files
ix. /etc/ssh/sshd_config - store ssh server settings
x. /etc/systemd/ stores systemd serice configuation

  • Be careful when editing, as changes affect the entire system.

*6./home (home = ~)
*

  • /home directory in store user home directories , every user on the system has a personal folder inside of /home , you can view
    user related documents , downloads ,file, configuration and settings....etc.

    • System-wide configuration files are not stored here (those are in /etc). --- check

i. change the directory
cd ~
ii. List all user directors in /home
ls /home
iii. check the current home directory
echo $HOME
iv. Navigate the your home directory
cd /home/your-username
v. sudo userdel -r username
-r = recursively(remove)

it Deletes user + home directory
vi. disk usage of /home
du -sh /home
-s = summarizes the total size
-h = human readable
vii. sudo -u alice -s
-u = mean user
-s = mean open a new shell for that new user

viii. sudo userdel username

Deletes only user, keeps home directory

ix. sudo rm -r /home/username

Deletes only the home directory

Image description

*7. /lib = library
*

  • /lib directory contain shared libraries and kernel modules required by system and programs in /bin and /sbin .

Detailed information of /lib

  • Stores the shared libraries(.so files ) needed for basic system programs support commands stored in /bin and /sbin .

Example shared libraries in /lib

=> modules/ → Kernel modules (drivers)
=> systemd/ → System service manager files
=> firmware/ → Hardware firmware
=> libcrypt.so → Example shared library
=> libc.so - standard C library (important of C programm)
=> libc.so - basic system commands>
=> libssl.so - provide encrypt secure internet connerction , uded by google chrome,fire fox,vpns.
=> libGL.so - graphics Library for games ,drones
=> libusb.so - usb communication library
=> libm.so -Math functions (used in calculation)
=> Math functions (used in calculation)
=> libpthread.so - thread support.
=> lirobotics.so = drones,robots,Industrila automation.
.
*purpose of shared libraries:-
*

*Avoid duplicating the same code in every time
*Save disk space and Ram
*Allow programs to update without recompiling.
*shared libraries (.so shared object files) contain reusable code that helps to multiple program can use reducing duplication.
Without /lib, your Linux system won’t boot properly.
*used by applications ( firefox,VLX,chrome) in run is user space.

example

web browser(Chrome,Firefox)

  • All web page needs to display text and image for example you need to diplay the image on you website ,you not need to write your code instead you use to libfreetype.so which provide ready-made functions for text rendering.

Checking Shared Libraries Used by a Program:

=> #ldd /bin/ls

Image description

kernel module

*A kernel module is a driver or extension that can be loaded/unload the linux kernel without rebooting the system.

purpose:-

  • It allows Linux to support new hardaware feature like wifi , usb , graphics...etc.
    • adds new filesystem support (NTFS,ext4,xfx) and help communicate the hardware devise like keyboard ,mouse,printer and also add or remove dynamically without restart the file system.

example:-

when you plug in usb in system ,linux load a kernel usbstorage.ko to access the device then ,unplug usb Linux automatically remove the module.

*used by kernel & Hardware runs in kernel space

Example:-

lsmod | grep <your usb device

i. wl.ko -manage wifi drivers
ii. usb-storage.ko - mange storage device internal and external
iii. btusb.ko - manage Bluetooth device
iv. video.ko - .manage webcam drivers
v. ext4.ko - filesystem handling

Difference Between /lib, /usr/lib, and /lib64

/lib = system libraries for programs in /bin and /sbin for system beet neede
/usr/lib = Libraries for user applications (not critical for system boot not need for boot ).
/lib64 64-bit version of libraries (for 64-bit systems).

*Library files require to not only Linux os apart form Rockets, mobile apps,Autonomous Robots (librrobotics.so used to tesla autopilot,NASA MARS Rover),Ai,web Browser......etc.

*lib used for you do not write all code manually it already pre-written for example in your create website project not need calculation code instated of you use libm.so (which provides sin(), cos(), sqrt(), etc.).

*8. /media = Auto mount(connect) for External device *.

*/media directory is used to automatically mount external device like usb drives , CDs,DVDs,SD cards.

*when you insert a usb drive, it us usually mounted in /media/username/usb-drive//

example:-
ls /media/

*9. /mnt/ manual mounting of device
*

i. mount point directory
why mount in a directory?

*you don not access storage devise directly
instead , you attach(connect or mount) to dir ,then you can access the directory. without mounting do not know where to access the usb. if mount usb dirive /mydir/externdevice you can access it inside of folder.

$ sudo mkdir -p /mydir/externdevice
$ sudo mount /mydir/externdevice
ii. verify the mount
mount | grep /mydir/externdevice

or
df -h

sudo umount /mydir/externdevice
umount -disconnect

why umount?

*without umount you loss your data or corruption

*10. /opt = optional
*

=> *Directory used for store third party application or manually installed software not managed for system package manager

Image description

/usr/bin - system wide installed programs by package manager
/usr/local/bin - locally installed software by admin

*11. /proc
*

*The directory in linux special folder . which show the live system information and computer hardware ,it does not contain real files but create information on the spot .

Example:-

*when you run a program like firefox & ,kernel created the new process and assign to the pid. process details appear in /proc/PID-of-firefox

practical:-

$firefox &
$ps aux | grep firefox
show the snapshot firefox pid and other deatils.
$ls /proc/pidofirefox
show the firefox process,memory usage ...etc
when close or kill fire fox using kill command it pid disappear from /proc directroy because it virtual filesytem, only show live session on when run the process.
$pidof firefox
show the more pid, its mean fire fox separate process for ui ,web pages,extension and so on.

Image description

Image description

Image description

Important directory in /proc:-

/proc/cpuinfo = info about the cpu model,core,speed.
/proc/meminfo = system RAM details
/proc/upting = system how long will be running system.
/proc/version = kernel version info.
/proc/mounts = shows mounted fiessystems
/proc/loadavg = system load average.

12. /root

Image description

  • /root is the home directroy of the root (superuser) account.
  • it stores root personal files, configuration and scripts. Just like normal user.

*normal user can not access /root ,if you need to access you can choose sudo.

example
$sudo ls /root

$sudo cd /root

*13./tmp (temporary files)
*

*stores temporary files that are automatically delted after restart or some time.
*used by application to store temorarery files, like session data, logs,caches.

  • Any user can write file in /tmp delted automatically when restart.
  • the /tmp directory has write permisssion for all users.you can see the t it means sticky bit ,it means owner can delete their own files and every one read and write and execute.
  • Later we will see sticky bit, suid , sgid.

Image description

Example:-
$cd /tmp
$touh temp.txt
then restart system after use below command
$ls /tmp

14. /usr

  • Stores system programs, libraries and shared files for all users
  • / root after this /usr directory is main directroy ,it containg all installed software and tools it contain /usr/bin/ /usr/lib/ /usr/share => Documentation ,icons,fonts

if you read this directory tell me different
for example :
bin/ vs /usr/bin
lib/ vs /usr/lib

15. /var = variable data

*contains variable file like log files and printer spools.L

examlple;-
i. /var/log = system log,auth.log,dmesg
ii. /var/spool = Email queues and printer queues.
iii. var/tmp - Longer time temp file it mean still there after reboot.

example:-
ls /var/log
cat /var/log/syslog - view system log

16 . /boot

  • without /boot, your system won't start,it contains linux kernel,which control hardware and software. And also GRUB is locate in /boot it help you choose which os to boot

example

i.ls /boot
ii. ls /boot/vmlinuz* ( show installed kernels)
iii. cat/boot/grub/grub.cfg ( grub config file)

17 . /run -runtime data storage

  • stores temporary system and process information that is required to system operation. when reboot after you see the /run/ directory data will be wipe out. Note System services recreate necessary files, but manually created files disappear. run/ used to stored as RAM.
    • it store only temporary service-related files like pid,sockets,lock files,runtime configuration file

example

Image description

18 . /srv - service data storage

  • stores files related to service hosted on the machine.

Example:-

Image description

vim editor after opened press i add the last lines as per below image then double press Esc then :wq ,after restart serives, then type http:

Image description

Result:

Image description

19 . /sys - system information

/sys directory is a virtual file system that provide the information about hardware device and kernel,it allow to linux kernel to ineract with system hardware in real time.

Example:-

i.liste the storage device
ls /sys/block

ii.detailed hardware device info
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
iii. Check total memory in system
cat /sys/devices/system/memory/block_size_bytes

iv. ls /sys/module - list kernel modules

The command Line

Reference
1.Book: Linux Administration A Beginner's Guide

*Author * : Wale Soyinka

Bash:-

The login shell is a first program runs when user log into a system. Shell is command language interpreter, shell read and process command execute the user types ,it allow to the user interact with operating system by executing command. Bash(Bourn Again Shell) is improved version of shell , shell used to old linux system, now Bash is used to modern distro .Bash is command line only interface ,it does not have GUi only text-based interaction(CLI),contain built-in commands like cd, echo(print text),bash can lanuch programs and manage running process.
.
Job control:-

when you working in the bash environment, you can start multiple program simultaneously at same prompt . each program consider a job ,by default when run a program, it take over the control terminal, can not type other program until the current program job done. some program require full terminal control to display colored text and fromating for example text editor,now see graphical programs do not need full control the terminal, it just run the background.

example:-

$ firefox ( take over the control terminal)
or
$ firefox & ( run the background keep using terminal)
or
$firefox & gedit & vlc & (multiple program)
$jobs

output show the running

Image description

  • ctr + z pass the current running process
  • ctr + c stop the process (later we will see kill, pkill , killall)

syntax:-

fg job of the firefox number

example:-
$firefox &
$jobs
$ fg 1
fg is bring it to the foreground the job.

bg -background the process

example:-

$sleep 100 (you tell the system
pause 100 second, do nothing)
ctr + z (pause the process sleep)
$bg (resume the last process in the process background)
(bg %jobid = resume particular job in the background, if multiple job running background)
$jobs
$fg (bg jobs bring it to the foreground the job)

Image description

Environment Variables:-

  • Every time you open a new terminal (shell) or run a program (process) in Linux, the system loads environment variables like $HOME, $USER, and $PATH. Each shell session or running process has its own set of settings that control how it behaves. These settings are stored in environment variables, which can be modified to customize the system without changing the original program code.

  • Environment variables in Linux are stored as key-value pairs(VARIABLE=value), either globally or locally. They hold values like file paths, system configurations, and application settings (for example, configuring software behavior). Environment variables can be temporary (session-based) or permanent (saved across reboots).

Practicles:

  1. view all environment varibale $ printenv or $ env

2.set a temporary varibale for current session only

bash:-
$export MY_VAR="Hellow_Linux" (globally set env variable)
$echo $MY_VAR
(varibale set only capital)

3.Remove a temp variable
unset MY_VAR

4.set permeant variable
edit ~/.bashrc or ~/.bash_profile(for bash user only)
$ vim ~/.bashrc
press i for insert mode
Add:-
export MY_VAR="Hellow_Linux"
double tap Esc
then
:wq(save and quite)
then
source ~/.bashrc (apply the changes)

or

echo 'export MY_VAR="Permanent Value"' >> ~/.bashrc
source ~/.bashrc > Apply changes

5.Application configuration

export DB_URL="jdbc:postgresql://localhost:5432/mydatabase"
echo $DB_URL
result:-
jdbc:postgresql://localhost:5432/mydatabase

6.storing Api key securely
set port API_KEY="abcde-123456-fghijk"

7.Setting Language
export LANG="en_US.UTF-8"
echo $LANG
result: en_US.UTF-8

8.simple scripting ,temporarily environment variable:-

Image description

bash:-

mkdir -p ~/scripts

make the directory in scripts(dir name) in side of HOME(~)
-p parent

echo -e '#!/bin/bash\necho "welcome to MY Linux blog"' > ~/scripts/myscript.sh

echo -e = print the text in terminal -e enable escape sequence & \n new line.

!/bin/bash = shebang operator ,tell the system to runt eh script using BASH.
=> > = redirect
~/scripts/myscript.sh = script file location

  1. Commonly used Environment variable:- $PATH = specifies directories executable file $HOME = user home directory $SHELL = default shell $USER = current logged in user $LANG = Language setting $PWD = current working directory $HOSTNAME = Machine hostname

example: $echo $HOME

Installation of “CentOS Stream 9″

Installations way of Linux operating systems:-

1.single Boot(Linux only)
2.Dual Boot( Linux + windows or macOS)
3.other operating system + virtual machine( multiple os run simultaneously)

*Early stage way to choose 2 or 3 option and move to 1 option(Recommend way),now we have see the early stage ,if you need 1 option please commend me the blog.

Operating system: Linux CentOS Stream 9

Prerequisites:-

*Pendrive 32 gb
*Internet connection
*minimum 2 gb ram
*free storage 40gb more

step1: Create a Bootable USB (Pendrive)

for windows user(using Rufus)

1.Download Rufus from => https://rufus.ie/en/
Dowload iso image from -https://www.centos.org/download/(choose iso base d on you system info)most likely x86_64 .
2.insert your usb drive into computer or laptop
3.After installation open rufus, fallow the below option :-

device : select your usb drive
Boot selection : choose the centos 9 iso file.'
partion scheme : choose GPT for UEFI or MBR for Legacy bios
filesystem : FAT32(FILE Allocation TABLE) click start ,now you have ready bootable usb-device.

step2: Configure BIOS/UEFI Settings

1.Restart your machine press f2,f12,Esc based on the system model.
2.find the bootable order or boot priority setting ,enable usb boot ,set as usb drive are first boot options.
3.enable boot mode - Legacy Mode /UEFI mode
4.Disable secure boot if enabled
5.save and exit F10

*step3: start installation:-
*

  1. Insert the bootable USB and restart your pc now your machine start from bootable pen drive.

i. Now display show like this

Image description

choose the install centos stream 9

ii. choose your language

Image description

iii. Setup date and time, keyboard layout and language

Image description

Image description

iv. choose your location

Image description

v. setting up software options server whith GUI
as per below image.

Image description

Image description

vi. Installation Destination:-

Now i choose Automatic ,u can choose also custom(Recommended) if you not already available disk, network& host part skip now later we will discuses.
if you choose custom:-

Image description

  1. /boot = Directory store all boot configuration related files & Linux kernels relate file

Example:-
/boot/vmlinuz-5.14.0-70.el9.x86_64
/boot/initramfs-5.14.0-70.el9.x86_64.img
/boot/grub2/grub.cfg (GRUB configuration)
/boot/efi/EFI/centos/grubx64.efi (If using UEFI)
2.Swap

when you physical ram is full , Linux moves inactive data to swap area, it prevent your system crash and keep process running ,when ram is free now data move back from swap to ram.
3./ (Root)

head/parent of the all directory in the Linux. All important files and application ,configuration save this location.

4./home
Directory contain user related files and documents and personal data.

Image description

Image description

vii. user creation & root password set:-

Image description

Image description

Image description

Image description

viii. GNOME at Boot:-

once you reboot system, CLI appear on the screen, login with user and passwd then CLI to GUI change for the below command

$su
=># systemctl enable --now gdm

Image description

Linux Introduction-II

Table of Contents:

1.Linux Architecture
2.Linux vs unix
3.Linux Distro
4.Booting Process

1.Linux Architecture

Image description

1. Hardware Layer


*The hardware layer is base of the Linux
architecture, it contain all the physical parts of a computer for example CPU , Ram , Storage, i/o device. The linux kernel communicates withe hardware using device drivers to control the physical parts.

2. Kernel Layer


*Linux kernel is a core part of the operating system
It acts as a bridge between hardware and software. It directly interacts with the hardware and manages system resources like CPU, memory, and devices.
*users give commands to the shell and the shell processes these commands the by interacting with the kernel .
example, if you runs ls, the kernel requests the file system to get file information from the hard disk.
Types

  1. Monolithic kernel
  2. Micro kernel
  3. Hybrid kernle.

3. Shell Layer

* shell in linux is a command line interface that allow to user interact withe operating system . It Acts as bridge b/w the user and kernel
Type:

1.Bash - default shell used to linux globally
2.Zsh(Z shell) - extended version of Bash shell like auto suggestion
3.fish(fish shell - it provides auto suggestion and web based config.
4.c shell - work like c programming ,mainly used developers

for real case work example

$cat /etc/shells - show only you installed shells
$echo #SHELL -show current shell
$chsh -s /bin/youinstalledshellname

4. User Applications Layer


include all programs and utilites(small programme or tool that help user perform specfic task like ls,cp,ping,top,ps)

2.Linux vs unix

Origin:-
Linux -Created by Linus Torvalds (1991)

Unix -Developed by AT&T Bell Labs (1970s)
License:-
Linux - Open-source & free (GPL)

Unix - Mostly proprietary (licensed)& paid

Usage:-
Linux -Used in PCs, servers, mobile (Android)
Unix - Used in enterprises, mainframes(big companies (like banks, telecoms, government)

Shell Support:-
Linux - Bash, Zsh, Fish, etc.
Unix - Bourne Shell, C Shell, Korn Shell

File System:-
Linux - ext4, XFS, Btrfs... etc

Unix - UFS, JFS, ZFS .... etc

Hardware Support:-
Linux - Runs on all devices (PCs, ARM, etc.)
ARM is type of process used in mobile,tablet,computer.
Unix - Runs on specific hardware (IBM, HP)

Strong security, frequent updates
Linux - gets regular update and fix the security issues and performance
Unix - very secure and less updates

Performance:-
Linux - high performece and flexible(code-chage and install different software and use may device)
Unix - less flexible and run on specific hardware

Examples:-
Linux - ubuntu ,Red hat,fedora,arch
Unix - AIX,HP-UX,solaris,macos

*3.Linux Distro
*

  1. Ubuntu - ubuntu.com
  2. Debian - debian.org
  3. Fedora - getfedora.org
  4. Arch Linux - archlinux.org
  5. Linux Mint - linuxmint.com
  6. openSUSE - opensuse.org
  7. Manjaro - manjaro.org
  8. Kali Linux - kali.org
  9. CentOS - centos.org
  10. Rocky Linux - rockylinux.org

4.Booting Process

i. BIOS/UEFI (Basic input/output system):-

Bios is firmware(means something does not change) store on a non-volatile memory chip on the motherboard that initialize and tests hardware components when a computer is powered on. It also loads the operating system. firmware it stored in a type of rom (read only memory) called firmware ,simply say firmware is written on to the Rom (Read only memory) during manfacturing ,it cannot be alteret,updated or erased later, permantely fixed in the memory.Now current environment used EEPROM(Electrically Erasable Programmable Read -only memory) or flash memory.

Functions of BIOS:

1.POST (Power-On Self-Test) – Checks if hardware components (CPU, RAM, storage,hardware ...etc) are working correctly.if any problem occurred (for example hdd not connect propery in motherboard,ram dust and not detect) show like beeps or error code.

2.Bootstapping (boot process) -find and load the os from storage into ram.

3.Harwae initalization - configure and initialize system hardware before os take the control.

4.Bios setup utility - allows users to configure system settings (boot order,secure boot ,bios password set)

5.basic i/o operations - acts as an interface b/w the os and hardware.

Types of Bios:-

*Legacy Bios _ older system used , it support only MBR partitioning and 16 bit interface( 16 bit processor) not support to GPT, user interface text-based ,keyboard-only, storage support 2.2 TB and 4 primary partition ,basic password protection and slower boot time.
UEFI - (Unified Extensible Firmware Interface)
*Now modern system used UEFi , user interface support graphical and keyboard ,mouse. operating system used 32 64 bit processor , storage support 18 exabyte and 128 partition. security boot ,advanced security feature, faster boot time.

  • search the bootloader in the MBR if bios otherwise UEFI means GPT. bios passes the control bootloader.

ii. Bootloader (GRUB, LILO, etc.)

  • MBR is responsible for loading and executing the grub boot loader ,let we discuss depth , GRUb(GRand Unified Bootloader) is bootloader used in Linux sysem to load the operating system into primary memory RAM when computer starts. it is the first software that after runs firmware(BIOS/UEFi) complete the hardware initialization.

stage 1:(MBR/EFI Execution)
BIOS/UEFI load the first stage o GRUp the MBR if

BIos (or) EFI system partion for UEFI.
MBR fist stage 512 bytes in the boot disk

stage 2:(Loading Kernel & initrd)

GRUB Loads the kernel (vmlinuz) into ram .
vmlinuz = "Virtual Memory LINUx gZip-compressed"
*It is the compressed Linux kernel used for booting the system and also GRUB load the initrd(initial ram disk ) or initramfs(initial Ram Filesystem),which contains essential drivers and tools,
initrd(old)/initramfs(modern) temporary root filesystem load into ram by the bootloader like grub, before then mount root filesystem (mount attach(connect) ,umount detach(disconnect),initramfs not need to mounted like initrd,load the directely in the ram.

*The main GRUB menu is displayed here,
You can select the operating system or kernel version,
If you no selected , it will boot the default OS automatically.
Passes control to the kernel.ck3(custom file)

Kernel Initialization

  • The kernel starts execution and mount the root file system read only mode , it runs systemd/init process , start the essential sevices, you can check the Linux os first prosses(pid) is systemd using top command.

    • systemd is system manager it manage sytem services and control the run levels and so on.

*kernel manage the system resource(cpu,memory,device) and hardware components.

System Initialization (systemd/init)

*Systemd starts all required services and daemons (e.g., networking, logging).
*The kernel starts the init system (older Linux) or systemd (modern Linux).
*Systemd is the first process (PID 1) that manages system services.

  • It manages runlevels (SysVinit(older)) or targets (systemd) to start necessary services: 1.Networking 2.Filesystem mounting 3.Daemons (background services) 4.Login services

Runlevel/Target Execution

OldRunlevesl(SYsVinit)

runlevel
0 shutdown
1 singel user mode (resuce mode)
2 multi user mode (no networking)
3 multi user mode (with networking,CLI)
4 unused/custom mode
5 multi user mode with gui
6 reboot

example :
bash
$ runlevel
$ init 0

New Targets (systemd)

poweroff.target => Equivalent to Runlevel 0 (Shutdown)
rescue.target => Equivalent to Runlevel 1 (Single-user mode)
multi-user.target => Equivalent to Runlevel 2 & 3 (CLI, Networking)
graphical.target => Equivalent to Runlevel 5 (GUI mode)
reboot.target => Equivalent to Runlevel 6 (Reboot)

example :
bash
$ systemctl get-default (check runlevel)
$ systemctl isolate poweroff.target
$ systemctl set-default reboot.target
(isolate -temporary)
(set-default - permanent )

*Login Prompt (getty)
*

Displays a CLI login (TTY) or a Graphical Login (GDM/KDM).Allows the user to log in and access the system.
example:
$who
TTY column
tty1 - local terminal
pts/0 - remote ssh sessions1
pts/1 -remote ssh sessions2

Reference
https://medium.com/%40gangulysutapa96/6-stages-of-linux-boot-process-5ee84265d8a0
https://www.thegeekstuff.com/2011/02/linux-boot-process/
https://www.freecodecamp.org/news/the-linux-booting-process-6-steps-described-in-detail/
https://www.geeksforgeeks.org/linux-vs-unix/
https://www.linuxjournal.com/content/unix-vs-linux-what-is-the-difference
https://www.diffen.com/difference/Linux_vs_Unix

Introduction to Linux

Reference Book: Linux Administration A Beginner's Guide
*Author * : Wale Soyinka

Linux: The operating system:-

  • Linux is an open-source operating system; it contains a kernel, and that kernel is the heart of Linux. The kernel operates the hardware components (RAM, CPU, storage device, and input/output devices) and manages system resources, for example, files, processors, memory, devices, and networks.
  • The kernel is a nontrivial program; it means complex, significant, and not easy to implement.
  • Linux: All distros use different customized versions of the kernel, but core functionality is the same for all distros, such as file management, processing, and networking.
  • Linux distro RHEL, Fedora, Debian, Ubuntu, CentOS, Arch...etc. Linux differentiates two categories. One is commercial (supported by vendor company distro longer release life cycle; it means support and update for a long year with a paid subscription); another one is uncommercial (free), managed by the open source community with a short year release.
  • The open source (uncommercial) and commercial Linux distros are interconnected because commercial companies support free distros as testing grounds. Most Linux software is developed by independent contributors, not the company side.

kernel differences:-

Each company sells its own developed distro and customizes the kernel. The company says that its kernel is better than the others. Why say it is better than other kernels? Most of the company and vendor companies stay updated with patches that are posted on www.kernel.org, the "Linux Kernel Archives." However, the vendor company does not track the release of the single kernel version released on wwe.kernel.org; instead of applying the custom patches to it to run the kernel quality assurance process, it tells the production is ready to help the commercial customer; it makes them confident. Any exception that occurs on the kernel-related vendor team immediately takes the action and fixes the issue, so every vendor maintains its own patch maintenance. Every vendor makes its own market strategies in the traditional environment, and the distro is designed as per the user's requirements, like making the kernel version customizable for purposes such as desktop, server, and enterprise.

The GNU Public License:-

In 1980, Richard Stallman was the founder of the Free Software Movement and the initiator of the GNU Project.

Richard Stallman is quoted as saying:

“Free software” is a matter of liberty, not price. To understand the concept, you should think of “free” as in “free speech,” not as in “free beer.”

  • The main goal of giving away source code is freedom and flexibility. The user should have control over the software; the user cannot depend on the developer or officials. Open source's main goal is that anyone can modify and improve it. The advantage of open-source software is that it allows the community user with necessary skills to collaborate and add new features and contribute to improving software for the benefit of everyone.

  • The Gnu project is the GNU public license (GPL); it means any GPL software anyone can view the source code, edit, reconstruct, release the full source code, sell, and get profit, but one condition is the GPL editable version released under the GPL license. Other licenses are there, such as BSD and Apache, that have similar rules but differ in terms and redistribution. For the BSD license, anyone can change the source code and use it. You can hide that you made changes to keep it private from others, but GPL is not allowing this term. You must showcase what you modified in the software. You can see more related info from www.opensource.org.

Upstream and Downstream:-

  • Upstream is a source code of original project where the code is first developed , you take the code for open source project and modify it, original upstream means for example you buy the normal veg pizza in a pizza shop you gathered all ingrediencies info take it and make it new version chesses pizza include your ingrediency.

  • Downstream is modify version of code ,the project use, modify, extend the upstream code , you can take the opensource project build your own version your project is downstream. Key points is changes made upstream it affect downstream project for example Linux kernel upstream source code for the many Linux distro, ubuntu, fedora ,downstream project do not go back the upstream.

Single Users vs. Multiple Users vs. Network Users

  • window was originally designed purpose is one time one user can work in window . two people can not work with co incidentally at a time .Linux is support multiuser environment ,it means two user work single time multiuser environment in Linux.
  • Network user and server client model for both Linux and windows provide services like database example sql, mysql, postgresql over a network ,from windows designed for client and server communication with restrictive and Linux flexible ,any program run remotely with admin permission.

The Monolithic Kernel and the Micro-Kernel:-

The kernel has three different types of use in operating systems. One is a monolithic kernel, everything inside of a single program, like Unix and Linux. The second one is a micro-kernel, a limited core set of services needed to implement the operating system example window. The third one is a hybrid; it combines the first two kernels. The current industry uses a Windows hybrid kernel. The Windows kernel provides a small set of services that interface with other executive services like process and I/O management.

Domains and Active Directory:-

  • AD is a centralized device; it manages authentication and authorization for the domain. The domain synchronization model means that the domain controller checks everything for up-to-date information. DNS style, It means following the root domain and child domain architecture; for example, abc.com is the root domain, and it. ABC.com and sales.ABC.com as child domains; each domain maintains its own user and computer, but it is part of the root domain network.-
  • Linux does not have tightly coupled (components do not depend on each other directory) authentication/authorization. Linux handles authentication used for the PAM pluggable authentication module; it means multiple authentication methods follow. Name resolution libraries help Linux find and verify user and group information from different sources, like local files, LDAP, and NIS.-
  • Authentication option is linux, flat files basic authentications using /etc/passwd and /etc/shadow, NIC used to older network for centralized authentication ,LDAP (Lightweight Directory Access Protocol) work like AD but is open source, Kerberos secure authentication using tickets, Samba and Ad it allows to authenticate against windows domain.
❌