Thursday, October 23, 2025

Java Basics

 

Class:

A class is a user-defined data type that serves as a blueprint or template for creating objects. Class encapsulates variables or attributes and functions (i.e. data members and member functions or method members). The method members are used to operate on that data i.e. data members. Encapsulation is a fundamental principle of Object-Oriented Programming (OOP), promoting data hiding and modularity.

 

Main components of a Java Class:

 

Ø  Fields/Attributes (Instance Variables):

These are variables declared within the class that represent the state or attributes of an object. For example, in a Car class, fields might include color, make, model, etc.

 

Ø  Methods / Functions:

The functions which are defined within the class make use of Fields of that class. These functions define the behavior or actions an object can perform. For example, a Car class might have methods like startEngine(), accelerate(), or brake().

 

Ø  Constructors:

These are the special methods /functions of class. The constructors are used to initialize new objects of the class. The constructors have the same name as the class and are called when an object is created using the new keyword.

 

Ø  Access Modifiers:

Keywords like public, private, and protected that control the visibility and accessibility of class members (fields and methods).

When no access modifier is specified for a class, method, or data member, it is said to have the default access modifier. This means only classes within the same package can access it.

 

Syntax:

class classname

{

      type instance-variable1;

      type instance-variable2;

      // ... type instance-variableN;

     type methodname1(parameter-list)

     {

           // body of method

      }

    ...

   

      type methodnameN(parameter-list)

      {

           // body of method

       }

}

 

Example:

class Student

{

       int rollNo;

       String sname;

       double per;

       public void getData()

       {

            rollNo = 90;

            sname = “Rajesh”;

            per = 95.25;

        }

        public void dispData()

        {

            System.out.println(“Roll No “ + rollNo);

            System.out.println(“Name “ + sname);

            System.out.println(“Percentage “ + per);

       }

}

 

In above example, Student is a Class and rollNo, sname and per are the fields / attributes of class Student. The getData() and dispData() are the methods/Functions of the class. These methods has public access modifies.

 

 

Object:

An object is an instance of a class, representing a specific entity with a defined state and behavior.

Each object has a unique identity, typically managed internally by the Java Virtual Machine (JVM). This identity allows the JVM to distinguish between different objects, even if they belongs to the same class.

Objects are created at runtime using the new keyword followed by the class's constructor. This process allocates memory for the object and initializes it.

 

Syntax:

               Class_Name ObjectName = new Class_Name( );

Example:

               Student obj = new Student( );

 

In above example obj is an object/instance of class Student. The keyword new is used to allocate memory and initializes it.

The object of the class is used to call the methods of that class. The dot (.) operator is used to class the methods.

 

Example:

                              obj.getData();

                              obj.dispData();

 

Programme:

class Student

{

       int rollNo;

       String sname;

       double per;

       public void getData()

       {

            rollNo = 90;

            sname = “Rajesh”;

            per = 95.25;

        }

        public void dispData()

        {

            System.out.println(“Roll No “ + rollNo);

            System.out.println(“Name “ + sname);

            System.out.println(“Percentage “ + per);

       }

}

class useofStudent

{

     public static void main(String args[ ])

     {

           Student obj = new Student( );

           obj.getData( );

           obj.dispData( );

      }

}

 

Note: Save the program with file name as useofStudent.java, Compile the program and execute.

 

Constructors and its types:

Constructor is a special member function name of class. It is used to build the object of that class. It is called when an object of a class is created.

Rules for writing the constructor:

1)    Constructor member function name and class name should be same.

2)    A constructor must not have any return type, not even void

3)    A class can have multiple constructors with different parameter lists.

4)    A Constructor can have public, private, protected, or default access modifiers.

5)    A constructor cannot be as final, static.

 

Syntax:

class ClassName

{

    // Constructor

       ClassName()

      {

        // initialization code

    }

}

 

Example:

class Student

{

      Student( )

      {

           System.out.println(“This is From Constructor… “);

      }

}

 

Java supports three types of constructors.

1)    Default Constructor

2)    Parameterized Constructor

 

1)    Default Constructor:

A constructor that has no parameters is known as default constructor. A default constructor is invisible, and if we write a constructor with no arguments, the compiler does not create a default constructor. The default constructor can be implicit or explicit.

a)    Implicit Default Constructor: If no constructor is defined in a class, the Java compiler automatically provides a constructor. This constructor doesn’t take any parameters and initializes the object with default values, such as 0 for numbers, null for objects.

b)    Explicit Default Constructor: If we define a constructor that takes no parameters, it's called an explicit default constructor. Once you define any constructor (with or without parameters), the compiler no longer provides the default constructor.

 

Example:

class Student

{

      Student( )

      {

           System.out.println(“This is From Constructor… “);

      }

}

class useofStudent

{

     public static void main(String [] args)

     {

          Student obj = new Student( );

     }

}

 

2)    Parameterized Constructor

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor is used.

 

Example:

class student

{

    // data members of the class

          String name;

          int sno;

 

      Student(String stdname, int no)

      {

            name = stdname;

            sno = no;

      }

     public void dispData( )

     {

           System.out.println(“ID =   ” + sno);

           System.out.println(“ID =   ” + name);

     } 

}

 

class useofStudent

{

    public static void main(String[] args)

    {

        //This would invoke the parameterized constructor

           Student obj = new Student("Ramesh", 401);

           obj.dispData( );

    }

}

 

Static fields and methods:

The static keyword is used to declare members (fields / methods) that belong to the class itself, rather than to any specific instance/object of that class.

Java will create only one copy of a static member, which will be shared by all objects of the class. The static members can be accessed directly using the class name, without creating an object of that class.

 

Characteristics of the static Members in Java:

Ø  Static variables and methods use memory only once when the program runs, and this memory is shared by all the objects of the class.

Ø  There is no need of creating objects of the class to use static methods

Ø  One can call static members using the class name directly.

Ø  Static members belong to the class, not to any specified object.

Ø  Static members can not access non-static members.

Ø  Static methods can only directly call other static methods.

Ø  Static methods can only directly access static data.

Ø  Static methods cannot refer to this or super in any way.

 

Static Fields /variables: We can create a static field by using the keyword static. The static fields have the same value for all the instances /objects of the class. The static fields are created and initialized when the class is loaded for the first time. We can access static fields using the class name (without instantiation).

 

Static Methods: We can create a static method/function by using the keyword static. Static methods/functions can access only static fields, methods. To access static methods there is no need of creating an object of the class. We can call them using the class name.

 

Difference Between the Static Method and Instance Method

Instance Methods

Static Methods

It requires an object of the class.

It does not require an object of the class.

It can access all attributes of a class.

It can access only the static attribute of a class.

The methods can be accessed only using object reference.

The method is accessed by class name.

Syntax: Obj_Name.methodname()

Syntax: className.methodname()

It's an example of pass-by-value programming.

It is an example of pass-by-reference programming.

 

 

Program 1:

// Use of Static Function

class StaticFun1

{

    // static method

    static void Function1()

    {

        System.out.println("From Static Method… ");

    }

}

class UseofStaticFun1

{

    public static void main(String[] args)

    {

          // calling Static member without creating

          StaticFun1.Function1( );

    }

}

 

Program 2:

// Use of Static Variable

class StaticFun2

{

    // static Member

    static int counter = 0;

    public void dispData()

    {

        System.out.println("Static data member "+counter);

    }

}

class UseofStaticFun2

{

    public static void main(String[] args)

    {

          StaticFun2 obj = new StaticFun2( );

          StaticFun2.counter = 9;

       // calling Static member without creating

          obj.dispData( );

    }

}

 

Program 3:

// Use of Static Methods

 

class MyCalc

{

    public static int add(int a, int b)

    {

        return a + b;

    }

 

    public static int mul(int a, int b)

    {

        return a * b;

    }

}

class useofMyClac

{

    public static void main(String[] args)

    {

        int res;

        // Calling static methods directly using the class name

        res = MyCalc.add(10, 5);

        System.out.println("Addition: " + res);

        res = MyClac.mul(4, 6);

        System.out.println("Multiplication: " + res);

    }

}