Alternative method to Calculate the final price of the Laptop or Desktop after certain discount of total cost according to criteria

import java.util.Scanner; //Importing Scanner class from util package

public class Purchase

{

    //Declaring instance variables 

    private String name;

    private String address;

    private double purchase;

    private double finalPrice;

public static void main(String []args) //Main method

    {

        System.out.println(“Press L for laptop and D for desktop”); //Instruction for User

        char ch=new Scanner(System.in).next().charAt(0); //Getting Character from user

                if (ch==’L’|| ch==’l’) //Checking condition

                {

                    Purchase l= new Purchase();

                    l.inputLaptop();

                    l.calcLaptop();

                    l.display();

                }

                else if(ch==’D’ || ch==’d’) //Checking condition

                {

                    Purchase d= new Purchase();

                    d.inputDesktop();

                    d.calcDesktop();

                    d.display();

                }

                else

                    System.out.println(“oops!! Sorry, Please enter valid character”); //Printing error message

    }

public void inputLaptop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address= new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Laptop: “); //Instruction to user

        purchase= new Scanner(System.in).nextDouble();

    }

public void inputDesktop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address = new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Desktop: “); //Instruction to user

        purchase= new Scanner(System.in).nextDouble();

    }

public double calcLaptop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-0;

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public double calcDesktop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((15*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public void display() //Non return type,Non parameterized method

    {

        //Printing results

        System.out.println(“Your Name = “+name);

        System.out.println(“Your Address = “+address);

        System.out.println(“Final Price after discount = “+finalPrice);

    }

}

 Output of the above program is:-

   Enter L to get access to Laptop section and D to get access to Desktop section

   l

   Enter your Name:

   Gaman Aryal

   Enter your Address

   Pepsicola

   Enter the cost price of Laptop:

   175000

   Your Name = Gaman Aryal

   Your Address = Pepsicola

   Final Price after discount = 157500.0 

Alternative method to Calculate the final price of the Laptop or Desktop after certain discount of total cost according to criteria

import java.util.Scanner; //Importing Scanner class from util package

public class Purchase

{

    //Declaring instance variables 

    private String name;

    private String address;

    private double purchase;

    private double finalPrice;

public static void main(String []args) //Main method

    {

        System.out.println(“Press L for laptop and D for desktop”); //Instruction for User

        char ch=new Scanner(System.in).next().charAt(0); //Getting Character from user

                if (ch==’L’|| ch==’l’) //Checking condition

                {

                    Purchase l= new Purchase();

                    l.inputLaptop();

                    l.calcLaptop();

                    l.display();

                }

                else if(ch==’D’ || ch==’d’) //Checking condition

                {

                    Purchase d= new Purchase();

                    d.inputDesktop();

                    d.calcDesktop();

                    d.display();

                }

                else

                    System.out.println(“oops!! Sorry, Please enter valid character”); //Printing error message

    }

public void inputLaptop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address= new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Laptop: “); //Instruction to user

        purchase= new Scanner(System.in).nextDouble();

    }

public void inputDesktop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address = new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Desktop: “); //Instruction to user

        purchase= new Scanner(System.in).nextDouble();

    }

public double calcLaptop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-0;

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public double calcDesktop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((15*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public void display() //Non return type,Non parameterized method

    {

        //Printing results

        System.out.println(“Your Name = “+name);

        System.out.println(“Your Address = “+address);

        System.out.println(“Final Price after discount = “+finalPrice);

    }

}

 Output of the above program is:-

   Enter L to get access to Laptop section and D to get access to Desktop section

   l

   Enter your Name:

   Gaman Aryal

   Enter your Address

   Pepsicola

   Enter the cost price of Laptop:

   175000

   Your Name = Gaman Aryal

   Your Address = Pepsicola

   Final Price after discount = 157500.0 

Calculate the final price of the Laptop or Desktop after certain discount of total cost according to criteria

An electronics shop has announced the following seasonal discounts on the purchase of certain items. 

Purchase Amount in Rs. Discount on Laptops Discount on Desktop PC
 0 – 25,0000.0%5.0%
25,001 – 57,000 5.0% 7.5%
 57,001 – 1,00,0007.5% 10.0%
 More than 1,00,000 10.0% 15.0%
  • At first Scanner class is called to read the value from the user.
  • Then Required variables are declared.
  • Then String type is declared to enter the section of the laptop or desktop.
  • Then according to the question if the given string is L,l then the program enters into laptop section otherwise it enters int desktop section.

import java.util.Scanner; //Importing Scanner class from util package

public class Purchase

{

    //Declaring instance variables 

    private String name;

    private String address;

    private double purchase;

    private double finalPrice;

public static void main(String []args) //Main method

    {

        String type;

        System.out.println(“Enter L to get access to Laptop section and D to get access to Desktop section “);

        type = new Scanner(System.in).nextLine();

        String s =new String(type); //Creating object of String class

        boolean s1 = s.equals(“l”);

        boolean s2 = s.equals(“L”);

        boolean s3 = s.equals(“d”);

        boolean s4 = s.equals(“D”);

        if (s1==true || (s2==true))

        {

            Purchasel= new Purchase();

            l.inputLaptop();

            l.calcLaptop();

            l.display();

        }

        else if(s3==true || (s4==true))

        {

            Purchased= new Purchase();

            d.inputDesktop();

            d.calcDesktop();

            d.display();

        }

        else

        {

            System.out.println(“oops!! Sorry, Please enter valid character”); //Printing error message

        }

    }

public void inputLaptop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address= new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Laptop: “); //Instruction to user

        purchase= newScanner(System.in).nextDouble();

    }

public void inputDesktop() //Non return type,Non parameterized method

    {

        System.out.println(“Enter your Name: “); //Instruction to user

        name= new Scanner(System.in).nextLine();

        System.out.println(“Enter your Address”); //Instruction to user

        address = new Scanner(System.in).nextLine();

        System.out.println(“Enter the cost price of Desktop: “); //Instruction to user

        purchase= new Scanner(System.in).nextDouble();

    }

public double calcLaptop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-0;

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public double calcDesktop() //Return type,Non parameterized method

    {

        //Conditions according to the above criteria

        if(purchase<=25000)

        {

            finalPrice= purchase-((5*purchase)/100);

        }

        else if(purchase>25000 && (purchase<=57000))

        {

            finalPrice= purchase-((7.5*purchase)/100);

        }

        else if(purchase>57000 && (purchase<=100000))

        {

            finalPrice= purchase-((10*purchase)/100);

        }

        else if(purchase>100000)

        {

            finalPrice= purchase-((15*purchase)/100);

        }

        return finalPrice; //Returning the result value of variable finalprice

    }

public void display() //Non return type,Non parameterized method

    {

        //Printing results

        System.out.println(“Your Name = “+name);

        System.out.println(“Your Address = “+address);

        System.out.println(“Final Price after discount = “+finalPrice);

    }

}

 Output of the above program is:-

   Enter L to get access to Laptop section and D to get access to Desktop section

   l

   Enter your Name:

   Gaman Aryal

   Enter your Address

   Pepsicola

   Enter the cost price of Laptop:

   175000

   Your Name = Gaman Aryal

   Your Address = Pepsicola

   Final Price after discount = 157500.0

Introduction to java

 

Why Java and why is it important ?

 

Java is a high level programming language in the in the following tradition of C and C++. You will find yourself comfortable and in familiar with java environment, if you have any experience with C and C++ programming language. you can see various updated features in java. The extra features of the Java programming language are listed below.

 

  • C and C++ are platform dependent where as Java is platform independent.
  • Java is the object oriented programming language. And C and ++ are both procedure oriented and  object oriented programming language.
  • Java supports automatic Garbage collection(Garbage Collection is procedure of recovering the runtime unused memory consequently or It is a way to destroy the unused objects.)
  • Java is the software based programming language where as C and C++ are nearer to hardware based programming language.
  • Java provides more security than the other programming language.
  • A development environment, JT provides a large of suit of tools.
  • The Java language itself is very simple. 
  • Java accompanies a library of classes that give regularly utilized utility capacities that most Java programs can’t manage without.

 

 Types of Java Programs

 

  •  Internet Applets
  •  Stand-alone Applications

 

Java Character Sets

 

Character set is a set of valid characters that a language can recognize. A character represents any letter, digit or any other sign. Java uses the Unicode character set (Unicode is a two-byte character code set that has characters representing almost all characters in almost all human alphabets and writing systems around the world including English, Arabic, Chinese and many more.)

 

Demonstration of the simple java program

 

     /* program HelloWorld*/

class HelloWorld

 

     {

 

           public static void main(String []args)

 

           {

 

                  System.out.println(“Hello World!!”);

 

           }

 

      }

 

Introduction to Classes and objects

 

As we already described that java is an object oriented programming language above. The basic unit of object-orientation in Java is the class. It is often called as templates or blueprints of objects. It allows a programmer to define all of the properties and methods that internally define the behavior/state of the object.

 

An object is a distinct instance of a given class that is structurally identical to all other instances of that class. A class is an object factory because once the class is created n number of  object can be created and use them. A class is the program code you write to create objects. The class describes the data and methods that defines objects behavior. 

 

The world we live in is composed of objects. Everything that we see around us is an example of object. We, ourselves, are examples of objects. All the living and Non-living things like:- Chair, car, pets, bikes, dog, computers, cellphones, house you live in etc can be consider as the example of objects.

 

Elements Inside Java

 

Tokens 

 

The tokens are the various Java program elements which are identified by the compiler. they are the smallest elements of program that is meaningful to the compiler. Individual words and punctuation marks. Every unit that makes a sentence.

 

Keywords

 

The Special words that convey a special meaning to the language compiler. Reserved words for special purpose and must not be used as normal identifier names. There are only 57 keywords in java.

 

Examples of keywords:

 

    abstract                                                 default                                                 if
    private                                                   this                                                      boolean
    do                                                          implements                                         protected
    throw                                                     break                                                   double
    import                                                    public                                                  try

 

Identifiers

 

The name given to variables, objects, classes, functions, arrays etc.

 

Some of the Identifier forming rules of Java:

 

  • Identifiers can have alphabets, digits and underscore and dollar sign.
  • They must not be a keyword or boolean literal or null literal
  • They must not begin with a digit.
  • They can be of any length.
  • Java is case sensitive.

 

Some valid identifiers:

 

       myName

 

       first_name

 

       lastName

 

       my_address

 

       …

 

Some invalid identifiers:

 

       first-name

 

       int

 

       phone-no.

 

       ……

 

Identifier Naming Conventions

 

The names of public methods and instance variables should begin with a lower case letter.

 

E.g. num1, str_a etc.

 

For names having multiple words, second and subsequent words beginning character is made

 

capital. E.g. myName, dateOfBirth etc.

 

Private and local variables should use lower case letters. E.g. height, width etc.

 

Constants should be named using all capital letters and underscores. E.g. RATE, PI, CHARGE etc.

 

Class names and interface names begin with an uppercase letter. E.g. MyClass, Person, Car etc.

 

Data Types

 

There are 8 primitive and 2 Non-primitive Date Types in Java language and they are as follows:-

 

     Primitive Date Types 

 

  1.  int
  2.  byte
  3.  short
  4.  long
  5.  boolean
  6.  float
  7.  double
  8.  char 

 

     Non-primitive Date Types

 

  1. String
  2. Object

 

Description of different Data Types:

 

  • Any thing enclosed in single quotes are character(char) data types.

 

            char alphabet= ‘A’;

 

  • Numbers without fractions are int, short, byte and long data type.           

 

            int num = 150;

 

            byte length= 10;

 

            short breadth= 30;

 

            long height= 50;

 

  • Numbers with fractions are float and double data type.

 

            double number= 210.5;

 

            double dis= 0.03;

 

            float res=78.82;

 

  • Anything enclosed in double quotes are a string.

 

             String name= “John”

 

  • Variables that take in either true or false value are a boolean data type.

 

             boolean result= true

 

Variables

 

Variables are the name of memory location. There are three types of variable ( Local, Instance and Static) in java. In other word Named storage locations which holds a data value of a particular data type whose value can be manipulated during program run. They must be declared before initialized.

 

The following statement declares a variable name of the data type String

 

String name;

 

Some more examples:

 

         double salary, area, volume;

 

         int month, day, year;

 

         long distance, breadth;

 

Initialization of Variables

 

         boolean result = true;

 

         String last_name= “Adhikari”;

 

         int num= 200;

 

Constants

 

Constant is the kind of variable whose value never changes. The only way to define constant in java is by using final keyword Often in a program you want to give a name to a constant value.

 

For example, you might have a fixed tax rate of 0.13 for electric materials and a tax rate of 0.05 for services.

 

These are constants because their value is not going to change when the program is executed.

 

The syntax for declaring constant are:

 

        modifier final datatype variableName= value; // global constant

 

        modifier static final datatype variableName= value; //constant within a class

 

Operators in Java

 

Java’s rich set of operators comprises of arithmetic, relational, logical, bitwise , assignment and certain other types of operators.

 

  • Arithmetic Operators

 

      Those operators which are required to performs all kinds of Arithmetical operations. Arithmetic          operators are used in mathematical expressions in the same way that they are used in algebra.              The  following table lists the arithmetic operators: Such as:-

 

  1.  Addition (+)
  2.  Subtraction (-)
  3.  Division (/)
  4.  Multiplication (*)
  5.  Modulus (%)

 

  • Relational Operators

 

      Those operators which area required to perform comparison between operands. Such as:-

 

  1. Greater than (>)
  2. Smaller than (<)
  3. Greater equals to (>=)
  4. Smaller equals to (<=)
  5. equals to (==)
  6. not equals to (!= or <>)

 

  • The Logical Operator

 

      Those operators required to check the conditions and generates the result in the form of true or             false. Such as:-

 

  1. AND operator (&&)
  2. OR operator (||)
  3. NOT operator (!)

 

  • Assignment Operator

 

      This operator is used to assign the value in variable. 

 

            For e.g. String name= “naranshiva”;

 

                       (Note- ‘=’ is the assignment operator)

 

Expressions

 

An expression is composed of one or more operations. The objects of the operation(s) are referred to

 

as operands. The operations are represented by operators. Therefore, operators, constants, and variables are the constituents of expressions.

 

The expressions in Java can be of any type:

 

  • Arithmetic expressions
  • Relational /logical expressions
  • Compound expressions

 

Java Statements

 

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following type of expressions can be made into a statement by terminating the expression with a semicolon(;):

 

Assignment expressions

 

Any use of ++ or —

 

Method calls

 

Object creation expressions

Convert temperature Celsius to Kelvin

Convert temperature in degree Celsius to Kelvin

Different Method like ‘Calculate’ and the setter method ‘setc’ is defined in a class called ‘Conversion’ and the main method is defined in another class named ‘Test’.

In this program getter method is used to set the value in the variable c. And the value is passed as an argument form another method from the main method.

Here is the program written inside the class ‘Calculate’.

Methods are either return type or Non-return type. If a void is used in syntax then it is Non-return type and if Data types like(int, String, Double) are used instead of void then it is called a return type method. so, to return value of the variable k the method the keyword ‘return’ is used. 

public class Conversion

{

double c;

double k;

public void setc(double c)

{

this.c=c;

}

public double calculate()

{

k=c+273.15;

return k; } }

And the main function written inside the Test class is.

public class Test

{

public static void main(String []args)

{ Conversion c = new Conversion();

c.setc(60.0);

double a= c.calculate();

System.out.println(c.c+” degree celsius to kelvin is “+a); } }

The output of this program seems like this:-

Convert Celsius to Fahrenheit

Convert temperature in degree Celsius to Fahrenheit

Different methods are defined to convert temperature into Fahrenheit. you can define the sub-methods and the main method in the same class or the two different two classes, and here we did the same. The calculation method ‘Calculate’ and the setter method ‘setc’ is defined in a class called ‘Conversion’ and the main method is defined in another class named ‘Test’.

Getter methods are used to set the value in variables. The data gets set here when the values are passed as an argument form another method that might be the simple method or the main method.

The syntax for the setter method is,

public void [methodName](Parameter){ Statement(s);}

Here is the program is written inside the class ‘Calculate’.

And the main function written inside the Test class is.

public class Test

{    

public static void main(String []args)   

{       

Conversion c = new Conversion(); //Creating object of the ‘Conversion’ class     

  c.setc(37.0); //calling setter method ‘setc’ to set the value 37.0 in variable c

double a= c.calculate(); //Calling ‘Calculate’ method       

System.out.println(c.c+” degree celsius to fahrenheit is “+a); //Printing result    }}

The output of this program seems like this:-

Calculate the area of Triangle



Calculate the Area of Right angled Triangle

Parameterized Methods are defined to calculate the area of a simple triangle and the Right angled triangle and the values are passed as an argument from the main function. Values are taken from the user with the help of Scanner (built-in class of util package in java project ).

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

public class TriangleArea

{

      //Declaring Variables

      private int height;

      private int base;

      private int a;

      private int b;

      private int c;

      private int s;

      private boolean T;

      public void Area(int height, int base) //Method for calculating area of Right-angled Triangle

     {

          double area= (height*base)/2; //Processing

          System.out.println(“Area of right angled triangle is “+area); //Printing Result

      }

      public void Area(int a, int b, int c) //Method for calculating area of Scalene Triangle

     {

           s= (a+b+c)/2; //Processing

          double area= Math.sqrt(s*((s-a)*(s-b)*(s-c))); //Processing


          System.out.println(“Area of triangle is “+area); //Printing Result

      }

      public static void main(String []args)

      {

          System.out.println(“To calculate area of triangle”);

          Scanner area1= new Scanner(System.in); //Creating object


          System.out.println(“Enter Side 1”); //Instruction for User

          int s1=area1.nextInt(); //Getting value from Key-Board


          System.out.println(“Enter Side 2”); //Instruction for User

          int s2=area1.nextInt(); //Getting value from Key-Board


          System.out.println(“Enter Side 3”); //Instruction for User

          int s3=area1.nextInt(); //Getting value from Key-Board


          TriangleArea obj= new TriangleArea(); //Creating object

          obj.Area(s1, s2, s3); //Calling Area method which calculates Area of scalene Triangle

          System.out.println(“To calculate area of Right angled triangle”);

          System.out.println(“Enter height”); //Instruction for User

          int h= area1.nextInt(); //Getting value from Key-Board


          System.out.println(“Enter base”); //Instruction for User

          int b=area1.nextInt(); //Getting value from Key-Board

          obj.Area(h, b); //Calling Area method which calculates Area of Right-Angled Triangle

      }

}

Output:



Java program to calculate the simple interest Using ‘Scanner’ Class



Calculate the Simple Interest

The data needed to calculate simple interest can be initialized with the default value inside the class and also can be taken from the user. Here ‘Scanner’ class, the built-in class inside the ‘util’ package of ‘java’ project is imported to get value from the keyboard.

import java.util.Scanner; //Calling Scanner class to read input from Keyboard

public class SimpleInterest

{

     public static void main(String []args)

    {

         //Declaring Variables

         double Principal;

         double Time;

         double Rate;

         double Interest;

         System.out.println(“Enter amount of Principle”); //Instruction for User

         Principal= new Scanner(System.in).nextDouble(); //Getting value for Principal from user


         System.out.println(“Enter Time period”); //Instruction for User

         Time= new Scanner(System.in).nextDouble(); //Getting value of Time from user


         System.out.println(“Enter Rate of Interest”); //Instruction for User

         Rate= new Scanner(System.in).nextDouble(); //Getting Interest Rate from user


         Interest= (Principal*Time*Rate)/100; //Processing

         System.out.println(“Simple Interest =  “+Interest); //Printing Result

    }

}

Output:

     Enter amount of Principle

     1500

     Enter Time period

     2.5

     Enter Rate of Interest

     15.1

     Simple Interest =  566.25



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.