OOPM JAVA - Create class that stores a string and all its status details

 Experiment No. 04

Aim: Write a program to create class that stores a string and all its status details such as number of upper case characters, vowels, and so on

Objective: To create a class and initialize them with different no of parameters by implementing constructors and their overloading in real time scenario. 

Outcome: Students successfully created and initialized object as per requirement of the real time scenario.

Theory: 

A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that is used to initialize instance variables of an object before the reference of this object is returned by new. Constructor can be defined as a method having same name as class name without any return type.

A constructor does look and feel a lot like a method but it is different from a method in two ways:

A constructor always has a same name as the class whose instance members they initialize.

A constructor does not have a return type, not even void. It is because the constructor is automatically called by the compiler whenever an object of the class is created.

Syntax of Constructor:

The syntax of constructor is as follows:

Constructor_Name([parameter List])

{

  //constructor body

}

Here, the Constructor_Name is same as the name of class it belongs to.

The parameter List is the list of optional zero or more parameters that are specified after the class name in the parenthesis. Each parameter specification, if any, consists of a type and a name and are separated from each other by commas.


Types of Constructor:

There are three types of constructors. These are:

  1. Default Constructor – Compiler automatically creates one constructor if we don’t create
  2. Parameterized Constructor – Constructor with parameter which make possible to initialize objects with different set of values at time of their creation
  3. Copy Constructor – Constructor which creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument.


  1. Default Constructor:Each time an object is created, a constructor is always invoked. But in some programs if we don’t create any constructor. So in such situations, the compiler automatically creates one constructor which is known as default constructor. It does not contain any parameters and doesn’t even contain any statements in its body. Its only purpose is to enable you to create object of class type.
  2. Parameterized Constructor:The constructor which has parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at time of their creation. These different set of values initialized to objects must be passed as arguments when constructor is invoked. The parameter list can be specified in the parenthesis in the same way as parameter list is specified in the method.
  3. Copy Constructor:Sometimes a programmer wants to create an exact but separate copy of an existing object so that any changes to the copy should not alter the original or vice versa. This is made possible by using the copy constructor. A copy constructor is a constructor that creates a new object that is using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.


Constructor Overloading:

Constructor can be overloaded in the same way as you can overload methods. Constructor overloading allows a class to have more than one constructor that have same name as that of the class but differs only in terms of number of parameters or parameter’s data type or both.


Algorithm:

Step 1: Create the class.

Step 2: Declare the constructors with different parameter type and list.

Step 3: Create the objects for the class.

Step 4: Object creation automatically call the type matched constructor.

Step 5: The matched type constructor procedure will be run.

Step 6: Compile and run the program.


CODE: 

import java.util.Scanner;

public class StringStatus {

  static int upper = 0, lower = 0, number = 0, spaces = 0, special = 0;

  StringStatus(String str){

    for (int i = 0; i < str.length(); i++) 

    {

      char ch = str.charAt(i);

      //checks whether the character is upper case

      if (ch >= 'A' && ch <= 'Z')

      //increments the upper counter

        upper++;

       //checks whether the character is lower case

      else if (ch >= 'a' && ch <= 'z')

      //increments the lower counter

        lower++; 

      //checks whether the character is number 

      else if (ch >= '0' && ch <= '9')

      //increments the number counter

        number++;

      //checks whether the character is a space

      else if (ch == ' ')

      //increments the spaces counter 

        spaces++;  

      else

      //increments the special counter 

        special++;

    }

      

    System.out.println("Lower case letters : " + lower);

    System.out.println("Upper case letters : " + upper);

    System.out.println("Number : " + number);

    System.out.println("Spaces : " + spaces);

    System.out.println("Special characters : " + special);

 

  }

  public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a string: ");

    String str = sc.nextLine();

    new StringStatus(str);

  }

}


OUTPUT: 


Observations and learning: 

In this program we have seen how to use upper case, lower case ,numbers and special 

symbols and to calculate how many and types of character present in the string given by the 

user In this program we have taken help of if else if else.

 

Conclusion: 

We have seen how to use upper case, lower case ,numbers and special symbols and to 

calculate how many and types of character present in the string given by the user.

 

Question of Curiosity  

  • What is a Constructor?

Ans-In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables. ... Immutable objects must be initialized in a constructor.

 

  • What is Constructor Chaining ?

Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the ini=aliza=on done in a single place.

 

  •  What happens if you keep a return type for a constructor?

So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.

 

  • What is No-arg constructor?

No-Arg Constructor - a constructor that does not accept any arguments. DefaultConstructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.

 

  • When do we need Constructor Overloading?

Ans- We need to initialize the object in different ways as per the requirement for which we use Java constructor overloading. If we do not specify anything about a thread, then we can use the default but if do want to specify then we use this syntax.

 

Similar Programs

 1. Write a program to create class with amount, period, and interest rate. Initialize the above parameters using constructor and also overload the constructor. 

2. Write a program to create class with height, width, and length. Initialize the above parameters using constructor. Also overload the constructor for calculate the volume of BOX and CUBE. 

3. Write a program create a class ‘simpleobject‘. Using constructor display the message.









Comments