Concept of Constructor Overloading



Constructor Overloading

Like methods, constructors can be overloaded. In other words, you can provide more than one constructor for a class if each constructor has a unique signature. Constructors with the same name as that of the Class name and has a different (number or Datatype) of parameters differ from each other is simply known as constructor overloading. If you have a class name ‘Student’ then the Eg of Constructor overloading in Student class be like: 

public Student(String first, String last, double mark)

{

    firstName = first;

    lastName = last;

    Mark = mark;

}

public Student(String first, String last,){

    firstName = first;

    lastName = last;

}

public Student(int rollNo, String last,){

     RollNo= rollNo;

     lastName = last;

}

public Student(double mark){

       Mark = mark;

}

The previous example has four constructors with the same name as that of its class name ‘Student’ but they contain different no of parameter list and different Datatypes from each other. and hence It defines the Constructor Overloading.

Default Constructor

If you do not provide a constructor for a class, Java will automatically create a default constructor that has no parameters and doesn’t initialize any fields. This default constructor is called if you specify the new keyword without passing parameters. For example:

Ball b = new Ball();

Here, a variable of type Ball is created by using the default constructor for the Ball class.

If you explicitly declare any constructors for a class, Java does not create a default constructor for the class. As a result, if you declare a constructor that accepts parameters and still, want to have an empty constructor (with no parameters and nobody), you must explicitly declare an empty constructor for the class.



Constructor in Java Programming

Concept of Constructor

constructor in Java is a block of code similar to a method it is called when an instance of an object is created. The key differences between a constructor and a method are given below:

  • A constructor doesn’t have a return type.
  • The name of the constructor must as same as the name of the class.
  • It is considered as the other member function of a class.
  • When an instance of the object is created it is called automatically.
  • It is called at the time of Object creation.

Syntax of the constructor:

//This is the constructor
public ClassName(Parameter list)
{
Statement(s)…
}

The public keyword in the constructor indicates that other classes can access the constructor. It can be defined under private and protected section but in such cases, the constructor is not available to the Non-member function. ClassName must be the same as the name of the class that contains the constructor.

The constructor allows you to provide initial values for class fields when you create the object. Suppose that you are creating a program to calculate the area of Rectangle and have a class named Rectangle that has fields named length and breadth. You can create a constructor for Any class:

public Rectangle(int l, int b)

{

       length = l;

       breadth = b;

}

         Then you create an instance of the Rectangle class by calling this constructor:

  Rectangle r = new Rectangle (“50″, ” 20″);                                                                                                    

The new keyword here creates the object of class Rectangle and invokes the constructor to initialize this newly created object. A new Rectangle object for 50, 20 is created. 

Types of Constructor

The constructor function in a java programming language has two types and they are

1.  Parameterized Constructor

This type of Constructor can receive Parameters. Its syntax seems like:

//This is the constructor

public ClassName(parameter list)

{

statement(s)…

}

And the Syntax for  Creating and Initializing an Object is:

  ClassName ObjectName = new ClassName(Arguments);

              2. Non- Parameterized Constructor

              This type of Constructor cannot receive Parameters. Its syntax seems like:

//This is the constructor

public ClassName()

{

Statement(s)…

}

                And the Syntax for Creating and Initializing an Object is:

 ClassName ObjectName = new ClassName();

Use of Arithmetic Operators

Use of Arithmetic operators in java program

There are some Arithmetic Operators which helps to make a comparison between numbers.

By the help of this picture, You can identify the proper operator and use it.

The program below may help you to learn how the arithmetic operators can be managed properly.

Output:-

           Is 20>25? false

           Is 20<25? true

           Is 20>=25? false

           Is 20<=25? true

           Is 20 not equal to 25? true

If you want the code in the editable format then, Please comment down below

Java Program to make a comparison between numbers



Conversion between Numbers

public class DoubleComparison

{

       public static void main(String []args)

       {  

              boolean result; //declaring variable

              int a=30 , b=27 ; //value assign


              result = (a>=b)&&(b>=a); //comparison

              System.out.println(“is (30>=27)and(27>=30) ? “+result); //output


              result = (a>=b)||(b>=a);//comparison

              System.out.println(“Is (30>=27)or(27>=30) ? “+result); //output

        }


Output of the given program is :-


Is (30>=27)and(27>=30) ? false 
Is (30>=27)or(27>=30) ? true   



Java program to print ‘Hello World’



Simple program to print ‘Hello World’

This is the starting phase of the java program to print “Hello World”. You can change the sentence inside the double quote sign like:- “Hello World” to “Hii This is my first java program”, or anything according to your wish.

public class PrintHello

{        

      public static void main(String []args)

      {                

            System.out.println(“Hello World “);//Printing Hello            

       }

}

Output of the above program is: Hello World



Java program using Scanner Class



Scanner Class in Java

The scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.

  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read the numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string

Program to calculate

import java.util.Scanner; //Calling Scanner class

public class Arithmetic

{

     public static void main(String []args)

    {

           double num1, num2, sum, prod, div; // Declaring Variables

           Scanner value= new Scanner(System.in); //Creating object for Scanner class

           System.out.println(“Enter first number”);

           num1= value.nextInt(); //Getting value from keyboard

           System.out.println(“Enter second number”);

           num2= value.nextInt(); //Getting value from keyboard

           sum= num1+num2; //Calculating sum

           prod= num1*num2; //Calculating Product

           if (num1>num2) //Condition to check which number is greater

           {

                 div= num1/num2;

           }

           else

           {

                  div= num2/num1;

            }

             //Displaying result

            System.out.println(“Entered number are “+num1+” and “+num2);

            System.out.println(“Sum = “+sum);

            System.out.println(“Product = “+prod);

            System.out.println(“Division = “+div);

    }

}

Output of the above program is:

         Enter first number

8 Enter second number 4 Entered number are 8.0 and 4.0 Sum = 12.0 Product = 32.0 Division = 2.0



Java program using Increment and Decrement Operators

Increment ++ and Decrement — Operator as Prefix and Postfix in java

Increment and decrement operators are unary operators that add or subtract one, to or from their operand (an operand is the part of a computer instruction that specifies data that is to be operating on or manipulated and, by extension, the data itself.) respectively. In different programming language(Java, C, C++, Vala, PHP, etc…) the increment operator (++)  increases, the decrement operator (–) decreases the value of the variable(operand) by 1.

let us suppose, num= 10

     using increment operator,

num++;          //Increase value by 1 and the value of num becomes 11

++num;          //Increase value by 1 and the value of num becomes 11

     using decrement operator,

num–;            //Decrease value by 1 and the value of num becomes 9

–num;            //Decrease value by 1 and the value of num becomes 9

It is quite simple till now, But Here is the the main difference which matters a lot when the Operators are used as prefix and postfix.

Working mechanism of prefix and postfix  operators

  • If you use the prefix operator like –num then It decrements the value num by 1 at first and then returns its value.
  • If you use the postfix operator like num– then It returns its initial value at first and then decrements the value of num by 1.

Demonstration of the prefix and postfix form of the Increment (++) and Decrement (–) operators

  Example of the prefix Increment(++) Operator  and postfix Increment(++)

     public class Increment

     {

         public static void main(String []args)

         {

             int num=10; //value assign

             //Initially,num = 10. It is increased to 11 then, it is displayed.

             System.out.println(“The increased value using prefix = “+ ++num); //output


             //11 is displayed then, num is increased to 12.

             System.out.println(“The increased value using postfix = “+num++); //output

          }

      }

  Example of the prefix decrement (–) Operator  and postfix decrement (–)

     public class Decrement

     {

         public static void main(String []args)

         {

             int num=10;//value assign

             //Initially,num = 10. It is decreased to 9 then, it is displayed. 

             System.out.println(“The decreased value using prefix = “+ –num);//output


             //9 is displayed then, num is decreased to 8.

             System.out.println(“The decreased value using postfix = “+num–);//output

          }

      }

  • Output of the prefix Increment(++) Operator  and postfix Increment(++)

                                The increased value using prefix = 11

                                The increased value using postfix = 11

  • Output of the prefix decrement (–) Operator  and postfix decrement (–)

                                The decreased value using prefix = 9

                                The decreased value using postfix = 9