Calculate the area of Rectangle Using Constructor Overloading rules

Example of Constructor Overloading in Java program

This is a java program to calculate the area of Triangle.

This program is helpful to understand the constructor overloading. Here many constructors are called with the same name as same as of the class name ‘Rectangle’.

public class Rectangle { //Declaring global variables

int length;

int breadth;

double area;

Declaring global variables is accessible from wherever you want. Here many constructors are called and they need to be stored in the same variable so the global variables are created. The variables ‘length’, ‘breadth’, and ‘area’ stores the length breadth and the area of the rectangle respectively.

 public Rectangle() //Non-Parameterised Constructor    

{          this.length=4;         

 this.breadth=2;    

}

The constructors with no any parameters are called Non-Parameterised Constructor. Because of no parameters, the variables needed to perform calculation are initialized and stored some values.

Keyword “this” is a reference variable in Java that refers to the current object.

The features of ‘this’ keywords are:-

  • It helps to pass an argument in the method call.
  • It can be passed as an argument in the constructor call.
  • It helps to return the current class instance variables.
  • It can be used to initialize the variable inside the respected Constructor or Method.
  • ‘this’ keyword can be used to get the handle of the current class.

public Rectangle(int length, int breadth) //Parameterised constructor having multiple arguments    

{        

 this.length=length;          

this.breadth=breadth;     }

The constructors with parameter(s) are called Parameterised Constructor. Here two parameters ‘int length’ and ‘int breadth’ are passed which accept the values as an argument when the constructor is called from any other method(function).

 public Rectangle(int length) //Parameterised constructor having single arguments    
{          
this.length=length;     
}

Here only one parameter is passed which accepts the value as an argument when the constructor is called from any other method(function). The same named constructor ‘Rectangle’ inside the same class ‘Rectangle’ is defined with the different number of parameters and is all about Constructor Overloading.

public static void main(String []args)    


{          


// 1. Creating obj1 and calling non-paramaterised Constructor        

 Rectangle obj1= new Rectangle();   

       
obj1.area= obj1.length*obj1.breadth; //Processing    

   
 // 2. Creating obj2 and calling parameterised Constructor having multiple arguments          
Rectangle obj2= new Rectangle(4, 6);           

obj2.area= obj2.length*obj2.breadth; //Processing          

//3. Creating obj3 and calling parameterised Constructor        

 Rectangle obj3= new Rectangle(5);           

obj3.area= obj3.length*obj3.length; //Processing          

//Printing Result          

System.out.println(“Area of triangle  “+obj1.area); //1        

 System.out.println(“Area of triangle  “+obj2.area); //2         

 System.out.println(“Area of triangle  “+obj3.area); //3     } }

Output:


       Area of triangle  8.0

       Area of triangle  24.0

       Area of triangle  25.0

Basic Concept of Method In java



Introduction to the method

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name.  It is also called as sub-program/function it often returns value.

The method has its own name.  When that name is called in a program, the execution of the program goes inside the body of that method.  When the method is finished executing, it returns to the area of the program from which it was called, and the program continues on to the next line of code.

Process of calling method is given below: –

Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project.  The use of methods will be our first step in the direction of modular programming.

Methods are time savers; in that, they allow for the repetition of sections of code without retyping the code.  In addition, methods can be saved and utilized again and again in newly developed programs.

You are using the method when you write the code
 System.out.print( ) and System.out.println( ).

There are two basic types of methods: 

Built-in:  Build-in methods are part of the compiler package, such as System.out.println( ) and  System.exit(0).
 
User-defined: User-defined methods are created by the programmer. These methods take-on names that programmer assign to them and perform tasks that they are created for.

How to invoke (call) a method (method invocation):

When a method is called(invoked), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc.  The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires.  The required data for a method is specified in the method’s parameter list.

Consider this method that we have already been using from Breezy;

      String str = str1.toUpperCase(); //Converts all string contained in str1 to Upper class and store in variable str.

The method name is .toUpperCase() which is defined in the class “String”.  Since the method is defined in the class String, we must call String class before coding in current class.  This particular method returns all the lowercase letter contained in the str1 variable is converted in uppercase and stored in str variable.

You invoke (call) a method by writing down the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may (or may not) have information for the method.



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