DataTypes and Variables

Data Types

Integer Data Type

Floating Point Data Type

Java provides two floating-point data types as specified by the IEEE-754 standard. These are the float and double data types. The float type represents single-precision numbers while the double type is used for double-precision numbers.

You suffix the value assinged to a float variable with the character f. This is done because the decimal value assigned to a variable is taken as a double data type value by default.

Character Data Type

Useful for storing alpha numeric characters. 16-bit type. It does not accept negative values. A Character literal is assigned to a variable by using single quotation marks.

Syntax: char blahVar;

Range: 0 to 65,535.

Boolean Data Type

A variable of the boolean data type can store only two possible logical values, true and false. It is defined using the boolean keyword.

Syntax: boolean blahVar;

Boolean values are returned when the relational operators are evaluated. The boolean data type is also used to direct the conditional expressions that govern control statements.

HINT: What are control Statements?
They are used in a Java Program to guide the flow of execution to advance and branch depending on the changes made to the data values that are used in the conditional expressions.

String Data Type

Syntax: String blahVar;

A String can contain any combination of 0 or more characters and may also be null. The variable can also store characters such as the slash sign (/). the parentheses signs ( () ), the colon sign (:), and the semicolon sign (;)

Java implements strings as objects of the String data type instead of as character arrays. String objects are immutable. When an object of the String data type is created, you cannot change the characters that are part of that string.

Whenever you change an existing string, a new String object is created that contains the modifications to the existing string. In specific cases where a modifiable string is essential, there is a companion class attached to the String class called StringBuffer. StringBuffer objects represent strings that can be modified after they are created.

A String constant enclosed within double quotation marks can be assigned to a String variable. You cannot perform mathematical calculations on a String object because it does not support operators. An exception to this rule is the addition operator (+). It is used to concatenate two strings and to generate a String object as the result.

HINT: (+) Operator is the best example for polymorphism.

Variables

Declaring Variables

Syntax:

datatype variableName;

Example:

int sum;

Variable Initialization

Before using a variable in a Java program, you must assign a valid initial value to the variable. This process is called initialization. A variable must be declared and initialized before it can be used in a Java program.

Syntax:
variable_name = value;

Example:
int x=13;
float y=23.4f;
z = 92 + 123;

You can also simultaneously declare and initialize a variable.

Syntax:
datatype variableName = value;

Related Posts: Introduction to Java | Classes, Methods & Objects | Objects and Variables | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

Advertisements

OOP Concept – Encapsulation

Overview

Encapsulation allows an object to separate its interface from its implementation. The data and the implementation code for the object are hidden behind its interface.

Encapsulation hides internal implementation details from users.

Example:
A Customer may issue a check and now know how it is processed. The internal processing is hidden from the customer. Similary, the inessential attributes of a class are hidden from users by using encapsulation. The hidden attributes of a class are called protected attributes.

It ensures that an object supplies only the requested information to another object and hides inessential information.

Example: When a user selects a command from a menu in an application, the code used to perform the actions of that command is hidden from the user.

Encapsulation packages the data and method of an object and provides protection from external tampering by users. It implies that there is visibility to the functionalities offered by an object, and no visibility to its data. The best application of encapsulation is making the data fields private and using public accessor methods.

However, you cannot hide an entire object. To use an object, a part of it needs to be accessed by users. To provide this access, abstraction is used. Abstraction provides access to a specific part of data while encapsulation hides the data. Therefore, abstraction and encapsulation compliment each other.

In OOP, abstraction defines the conceptual boundaries of an object. These boundaries distinguish an object from another objects.

Example: When a user designs an application by using existing templates, the complexity of the template is hidden from the user, but the essential features for creating the application are provided to the user. Abstraction enables an object to display these essential features to develop an application.

Encapsulation and Inheritance are two key concepts in OOP that serve different purposes. While encapsulation hides inessential information, inheritance allows the object of a class to adopt the attributes of another class.

When you implement inheritance in an application, the classes in the application are arranged in a strict hierarchy. The classes at the lower levels inherit the attributes of the classes at the higher levels.

In addition to inheriting the characteristics of the parent class, a class may have its own attributes. This feature implies that the code and characteristics of a class are reusable and extensible. However, inheritance compromises encapsulation because a subclass can directly access the parent’s protected attributes without using operations.

Related Post: Introduction to OOP | Inheritance | Polymorphism

OOP Concept – Polymorphism

Overview

Polymorphism means one entity existing in multiple forms. It provides flexibility to application systems. It simplifies coding and reduces the rework involved in modifying and developing an application. It refers to the ability of an object to take on different forms depending upon the situation.

According to the polymorphism design principle, the same message sent to different objects results in different behavior. The behavior depends on the type of object that receives the message.

Example:
Every key of a keyboard performs a specific action when a keystroke message is generated for that key. However, by using polymorphism, the same code with a small change can be used by different keys of the keyboard to trigger specific actions.

Polymorphism and Classes

In Java, type polymorphism may be implemented using class inheritance, interface implementation, or both. When using class inheritance to implement polymorphism, a class instance may take the form of itself, or any of its superclasses.

Fig 1.1

[Refer above Fig 1.1] When an instance of a class is created, it may always be referenced using its own type. Although this seems obvious, it is important because it is one of the forms that the object instance may take. In addition, since every class in Java has the class Object as a base class, the instance may also always be referenced as an Object.

When a class has a superclass, an instance of the class may also be referenced as if it is the superclass. For example, if a class Car is derived from the class Vehicle, an instance of Car may be referenced as a Vehicle. The possible type references for an instance of the Car class are shown below [Refer Fig 1.2].

Fig 1.2


Fig 1.3

[Refer Fig 1.3] A class instance can be referenced as any of the superclass types regardless of the depth of the inheritance

Example:
The class Mustang, which derives from Car, which derives from Vehicle. Here an Instance of the Mustang class may be referenced as any of its superclasses.

An instance of a class is also considered an instance of its superclass. The ‘instanceof’ operator can be used to show this relationship. When an object is an instance of a class, it is called an is-a relationship. The below example shows that the instance of the Mustang class, is also an instance of all of its superclasses. [Refer Fig 1.4,1.4a]

Fig 1.4

Fig 1.4a

Polymorphism and Interfaces

Fig 2.1

When an instance of a class is created, it may always be referenced using its own type. Refer Fig 2.1

If a class implements an interface, it may be referenced as the interface type. For example, a class CDPlayer implements MusicPlayer interface.[Refer Fig 2.2]

Fig 2.2

A class may implement as many interfaces as necessary. The example [Refer Fig 2,3] shows a new interface called MusicRecorder. The class CDPlayerRecorder implements the MusicPlayer and MusicRecorder interfaces.

Fig 2.3

When a class implements multiple interfaces, an instance of the class is considered an instance of the interfaces that it implements. Therefore, the class can be referenced as if it is any of its implemented interfaces.[Refer Fig 2.4]

Fig 2.4

An interface may extend other interfaces. When an interface extends other interfaces, a class that implements the interface also implements the extended interfaces. An instance of the class may be referenced using any of the interfaces, including the extended interfaces.[Refer Fig 2.5]

Fig 2.5

If a class has a superclass that implements an interface, an instance of the class may be referenced using the interface type.

Example: We have a CDPlayer class that implements the MusicPlayer interface. If we have a class CustomCDPlayer that derives from the CDPlayer class, the instance of the CustomCDPlayer may be referenced as a MusicPlayer. [Refer Fig 2.6]

Fig 2.6

Since a class may have superclasses as well as implemented interfaces, it therefore may be referenced both as superclass types and interface types.

Example: [Refer Fig 2.6] a CustomCDPlayer instance may be referenced using both the superclass CDPlayer, and the interface MusicPlayer.

Valid Variable Assignments

Java allows you to assign variables of a derived class with the instances of the base class and vice versa.

Upcasting:

When a derived class extends a base class, the derived class inherits all the members of the base class. It may also contain some additional methods and fields. In Java, you can assign an instance of the derived class to a variable type of base class.

Example: [Refer Fig 3.1]
Consider a class Wind that extends class Instrument. In this case, the class Wind inherits the methods of the class Instrument. In this case, the Wind derived class is a superset of the base class Instrument. It might contain more methods than the base class.

Fig 3.1

Downcasting:

Fig 3.2

It refers to assigning a variable of a base class to an instance of a derived class. This implies that the variables of the base class can be initialized to the base class or to one of the derived classes. [Refer Fig 3.2] If class Wind extends Instrument, you can initialize the variables of class Instrument to the instances of class Wind or class Instrument.

When downcasting, you should explicitly indicate a variable of type Brass to one of the variables of type Instrument. A faulty cast construct can cause a run-time error. If a base class is assigned to a derived class without a cast construct, it can lead to a compilation error. [Refer Fig 3.3]

Fig 3.3

Related Post: Introduction to OOP | Inheritance | Encapsulation

OOP Concept – Inheritance

Basics

Different kinds of objects often have a certain amount in common with each other. Tiger & Cow, for example share the characteristics of Animal; Yet each also defines additional features that make them different. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

Inheritance provides a way to extend existing classes to make a new classes with specialized behavior. Inheritance creates a hierarchy of classes and helps you reuse the code of a parent class in a child class.

A Class inherits the attributes and behavior of its parent class or superclass. The attributes and behavior of the superclass need to be public or protected. Members of the superclass can be inherited with some restrictions.

Subclasses inherit the superclass members that are declared with no access modifiers, if the subclasses are in the same package as the superclass.

Example:

Tiger and Cow are the subclasses of the Animal class. Animal class contains all common behaviors and states that belong to animals [tiger or cow] however Tiger / Cow has distinct behaviors too. These are defined in their respective classes. Tiger & Cow classes are called subclasses because they are derived from the Animal class – the super class. They inherit the attributes and behavior of the Animal class. The subclasses may also define more attributes and behavior.

Syntax:
<<Access modifiers>> class <subclass name> extends <superclass name>

<<Access modifiers>> – default access [nothing] or public access [public keyword]

There are two types of inheritance, single inheritance and multiple inheritance.

Single Inheritance: A subclass inherits from a single class.
Multiple Inheritance: A class inherits from more than one immediate superclass.

HINT: Java classes cannot extend multiple classes. In Java, Only interfaces are allowed to extend multiple interfaces. Also, classes can implement multiple interfaces.

Although a subclass inherits all the members of its superclass, it cannot access the private member variables of the superclass. The public and protected member variables of the superclasses are accessible to a subclass. If the subclass is in the same package as the superclass, default members are also accessible.

Method Overridding

A subclass inherits members and methods from its superclass. However, a subclass can change the functionality of an inherited method by overriding the method.

Encapsulation allows an object to supply requested information to another object.
Overriding is the ability of a subclass to modify the behavior that it inherits from the superclass. By overriding a method, the developer is free to charge the implementations of the method in the subclass.

In Java terminology, the method in the subclass that has the same name and signature as a method in the superclass is called the overridding method. The method in the superclass is called the overridden method.

Example: Consider the class Employee that contains a method named calculateSalary. Consider Manager and Engineer subclasses that extend Employee Class. The process for calculating salary for Manager and Engineer are different from each other. And So, to solve this problem, you can override calculateSalary method of Employee class and provide different implementations in Manager and Engineer class seperately.

Guidelines for Overriding a Method

  • The overriding and overridden methods should have the same return type, method name, and the number, type, and order of arguments.
  • The overriding method should have equal or greater access than an overridden method.

‘Super’ Keyword

The ‘super’ keyword is used when a subclass needs to refer to its immediate superclass.

Constructor Overriding

Constructors contain code that initializes an object during instance creation. The object should be properly initialized. This is to ensure that the object is not in an invalid state and is usable.

A subclass calls a constructor defined by its superclass by using the ‘super’ keyword.

Syntax: super(arg 1, arg 2, ..);

In the displayed syntax, the super keyword specifies any arguments required by the constructors in the superclass. An implicit call to the zero argument is made, if the method does not appear on the first line of the subclasses constructor. The super method needs to be the first statement in a subclass constructor. These constructors run regardless of whether the super method exists. If the super method is not used, the default constructor of each superclass is automatically executed.

Final Classes

A Class than cannot have subclasses and the member variables of which cannot be overridden is called final class.
Similarly, methods and variables that cannot be overridden are called final methods and final variables, respectively.

When a class is declared as final, the class cannot be extended. Therefore, a final class cannot have subclasses. This provides security because other application developers cannot create subclasses for this final class or modify its behavior.

Example: String class in java.lang.String package. This class is declared as a final class because the authors of the class did not want anyone to extend it.

Syntax for Class: final class <Class Name>
Syntax for Method: final <return type> <method name>

Features of a Final Class In Short:

  • Restricts a class from being extended.
  • Prevents its methods from being overridden
  • Restricts the declaration of abstract methods.
  • Cannot be simultaneously declared as final and abstract.

HINT: Why Final class cannot have abstract methods?
This is because final classes cannot be extended and abstract methods need to be implemented in nonabstract subclasses.

Method lookup

Method lookup is the process that a Java program uses to identify the appropriate method to be invoked. The method lookup process in Java is derived from the inheritance hierarchy. Inheritance in Java is implemented by using the extends keyword.

Example:
class B extends A {…}
To denote that class B inherits from class A, you declare class B using the above syntax.

The method lookup process searches for the method in the class of the receiver object. If a matching method definition is not found, method lookup continues to look for the method in the superclass.

Java allows a subclass to access the methods and fields in the superclass by using the super keyword.

Fig 1.1
Fig 1.1
Let consider an example [Refer fig 1.1], class Vehicle is the base class that defines a variable wheels and a method displayDetails. Class Truck inherits from class Vehicle, and class Tanker inherits from class Truck. Although class Truck and class Tanker inherit from class Vehicle, the variable wheels declared in class Truck and class Tanker is local variable and does not refer to the variable wheels in the class Vehicle. Therefore, any reference to the variable wheels within a method of class Truck will refer only its local value.

To refer to wheels in Truck from within Tanker, you use the syntax super.wheels. Java casts this reference to the super type. Super.wheels is shorthand for ((Truck) this).wheels. However, you cannot use super to discover the value of wheels in Vehicle from within Tanker. To refer to the wheels in Vehicle from within Tanker, you use the syntax ((Vehicle)this).wheels from within Tanker.

The super keyword can be used to bypass the overridden version of a method in a subclass and run the version in the superclass. The super keyword can also be used to bypass a member variable in a subclass for accessing a member variable that has the same name in a superclass.

Suppose class Tanker contains the call super.displayDetails, this call actually invokes the method displayDetails in class Truck because Tanker has inherited it from Truck. If you use the syntax ((Vehicle) this).displayDetails(), it results in the execution of method displayDetails from Vehicle.

Related Post:
Introduction to OOP | Polymorphism | Encapsulation

Objects And Variables

Instantiating an Object

An Object is an instance of a Class. After creating an Object, you can access the member variables and methods of the object and assign values to them. An Object is declared in the same way that a variable of a primitive type is declared.

String sampleStr; //This code is used to define an object name of String type.

You can define a variable that will be used to refer to an object or an instance of a class.

When you create an object, you need to assign memory to the object. This is done using the new operator. The new operator is followed by the class name and parentheses. The syntax for creating an object is displayed below:

class_name variable_name = new class_name();
Example: Test aTest = new Test();

This code is used to create an instance of the Test class. The variable aTest is decleared. Notice that this is an arbitary variable name. This variable is used to refer to the instance of the Test class. You can also state that the name of this particular Test instance is aTest.

When multiple instances are created, each instance maintains a seperate copy of the member variables of the class.

Member Access – Dot Notation

The member variables declared in a class are accessed to assign values or manipulate the values stored in them. The public member variables may be accessed from any object using dot notation. In addition, member variables that are declared without a modifier are considered to have package scope. These variables may be accessed using dot notation from any object defined in the same package. Whereas private members cannot be accessed using dot notations. We need to define public methods [Getters] to access the private members and Setters for assigning values to private member variables

HINT:: Getters and Setters
A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property.

Variable Scope

A scope defines the logical boundary for accessing a variable.

HINT: Java allows you to use the same identifier for multiple variables as long as they are declared in a different scope.

Member Scope
A variable is in the member scope if it is accessible to the methods of the class. This variable is declared as the member variable of the class (i.e) Variables declared directly after class declarations.

Local Scope
A variable is considered to be in the local scope if it is declared within any block of code or if its declared inside a loop condition. A block is a group of statements that are enclosed within braces.

HINT: How Compiler handles?
The Java compiler refers to the variable definitions in a sequence to distinguish the current value of the variable. If first checks the variable in the current block. The current scope depends on the current statement being executed. If the compiler is unable to find the variable in the current block, it searches the variable in the current class. Finally, the compiler searches in the superclasses of the current class.

Variable Access – ‘this’ Keyword

The ‘this’ keyword can be used to access the member variables of the current object. These member variables of an object are also known as instance variables.

HINT
What is Instance Variables?
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.

What is Class Variables?
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Benefits of Static Variables

  • They are initialized once for all instances of the class.
  • They can be accessed directly using the class name, without a reference to an instance of the class.
  • They are used to store a single value for all instances of a class.
  • Related Posts: Introduction to Java | Classes, Methods & Objects | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

    OOP – Introduction

    Advantages of OOP

    OOP provides advantages over traditional structural programming languages. OOP facilitates writing applications by turning real-world objects into code components. OOP enables users to model real-world objects. Modeling means representing real-world objects as components in Java. Object-Oriented Programming allows programmers and customers to use the same terminology to explain the business domain and the program.

     

    In Summary:

    • Enables the use of real-world modeling

    • Promotes the reuse of code

    • Provides flexibility in the modification of an existing application

    • Helps with the maintainability of code.

    Let’s go in detail with the advantages…

    Enables the use of real-world modeling

    Consider an example. A car is an object that has specific attributes, such as an engine and wheels. Using OOP principles, you would model the car as a car object in Java that would have the same properties.

    Creating applications that model the real world closely enables developers to understand an application faster than any other applications. Therefore, an application that implements OOP concepts effectively is implemented and used.

    Promotes the reuse of code

    Another advantage of OOP is that it promotes the reuse of code. The code used to define an object can be shared by several objects of an application. For E.g.: the code used to design a type of car can be used for designing different types of cars. This saves you from rewriting code for various types of cars. A benefit of code reuse is that it reduces the amount of code to write, debug, test, and possibly upgrade in the future.

     

    Provides flexibility in the modification of an existing application

     

    OOP promotes flexibility in the design and implementation of a solution. Maintenance and upgrades are seen as further cycles in application development. By using OOP practices, applications become easier to extend.

    Consider an example of XYZ Corporation. The application used by the production department of this organization is currently designated to create two types of chairs, plastic and metal. To meet the demands of its customers, the organization decides to produce wooden chairs as well. To meet the change in the requirement, the XYZ

    corp. needs to incorporate changes into its current application system. If the current system was built using OOP best practices, extensions to the system may be simplified. For Eg: the new chair type would be able to share or reuse some of the other chair types’ code.

     

    Helps with the maintenance of Code

     

    Finally, OOP helps in the maintenance of code. By using OOP, you can create separate components for different requirements. In OOP, a component is known as a class. For example, to design a payroll system of an organization, you could create classes such as Employee and Payroll. By creating the Employee and the Payroll classes, information related to each class can be segregated. An internal change in one of these classes should not affect the functionality of the other class. Therefore, the maintenance of a system is simplified by reducing dependencies in between classes.

     

    OOP Design Principles

    An application that implements Object-Oriented Programming (OOP) concepts is distinguished by four design principles. The four design principles are encapsulation, abstraction, inheritance, and polymorphism.

    Encapsulation

    Encapsulation hides the inner workings of an object from outside users of the object. This protects outside users from making internal changes or optimizations to such objects. The object needs only to maintain its external functionality to support its clients. Internal details, such as data representation, should not be accessible externally.

     

    Abstraction

    The principle of abstraction is modeling real-world objects as objects in Java. However, these objects are only modeled at a certain level of detail. Only the behavior and data that is needed by your application will be included in your model.

    The abstraction design principle focuses on the essential characteristics of an object. In OOP, abstraction defines the conceptual boundaries of an object. These boundaries distinguish one type of object from another

    Inheritance

    The inheritance design principle allows a class to inherit the characteristics of another class. When inheritance is used in an application, the application consists of classes that are arranged in hierarchies. The classes defined at the lower levels of a hierarchy inherit from the classes higher up in the hierarchy.

    By creating a hierarchy of classes, the characteristics and code of a class are made reusable. A class can inherit characteristics from other classes and provide additional features. The new class has its own attributes and the attributes of the existing class. This feature provides extensibility and reusability in classes.

     

    Polymorphism

    Polymorphism refers to the ability of an object to take on different forms depending upon the situation. Consider an example of a class Sedan that inherits from the class Car that inherits from the class Vehicle. An instance of the Sedan class can be referred to as a Sedan, a Car, or a Vehicle.

    Polymorphism provides flexibility to an application based on requirements. It simplifies coding and reduces the rework involved in developing and modifying an application. This is because different types of objects can react to the same type of stimulus.

    Related Post:
    Inheritance | Polymorphism | Encapsulation

    Classes, Methods and Objects

    Classes and Objects

    The idea of Object-Oriented Programming (OOP) is to place data and methods together in a single entity. The single entity holding the data and methods is called a class. An Object is an instance of a class.
    To create a Java application, you organize programming structures by creating classes that consist of reusable code. You can create a class in Java to perform simple tasks, such as declaring the member variables of the class and perhaps initializing the member variables by using the methods of the class.

    An instance of a class is declared the same way that a primitive data type is declared. A class defines both data and methods. You can reuse the same class in several applications without rewriting it. You can create as many instances or objects of a class as needed. When multiple objects are created, each object maintains a separate copy of the member variables defined by the class.

    Creating a Class

    1. Specify the class name.

    2. Declare data members.

    3. Declare methods.

    4. Define the processing.

    In order to define a class, you must specify the class name, declare the member variables, and declare the methods of the class.
    There are certain naming conventions that should be followed when naming a class. First, class names should be nouns. The first character of the class name should be upper case, and each internal word of the name should be upper case. The rest of the characters in the name should be lower case. The words in the name should be whole words. Acronyms and abbreviates should be avoided.

    In addition, you must define the processing that is required for the method. For example, operations such as addition or subtraction on member variables can be specified in the methods. The contents of the class definition are enclosed within braces.

    public class Rectangle {
     //class name and Body begins now... 
      int length=10; 
      int width=5; 
      String color; 
    
    
      void calculateArea() { //method declartion 
        int totArea = length * width;//processing 
        System.out.println("The total area " + totArea); 
      } 
    }//end class body

    Consider the Rectangle class shown above. It consists of the class keyword followed by the class name. The class body begins with an opening brace. The class body consists of member variables and a method. In the method declaration, the member variables are accessed and processed. To end the class declaration you use a closing brace.

    A class declared in Java usually contains an access modifier. The access modifier determines the type of access other classes and objects can have to a specific class and the fields and methods that it defines. In our example, Rectangle class is declared using “public” access modifier meaning it can be accessed by anyone.

    Access Modifiers for Class
    The access modifiers that can be used while declaring a class are public, private, and protected. When the class is declared without an access modifier, the class is accessible by the other classes in the current package. When a class is declared with the public access modifier, the class is accessible by all the other classes.
    The private and protected access modifiers may only be used on inner classes. They cannot be used for top-level classes. When a class is declared with the private access modifier, the class is not accessible by any other classes. When a class is declared with the protected access modifier, the class is accessible by subclasses of the class.

    In addition to the access modifiers, the modifiers final, abstract, and strictfp may be specified.

    If the final modifier is specified, the class represents a complete class and cannot be overridden by a subclass.

    The abstract modifier is used to declare that a class is considered incomplete. An abstract class may have abstract methods that are not implemented within the class. The final modifier cannot be used with the abstract modifier.

    The strictfp modifier is used to force the code within the entire class to use strict floating-point logic. This applies to all float and double values that are used within the class.

     

    Declaring Methods

    A class is defined by its state and behavior. The member variables of the class define the state of the class. The methods of a class define the behavior of the class.
    Consider an example, To add the values stored in the member variables of a class, you declare a method that operates on these member variables to compute their sum. The result can be displayed by another method that calls the computed method.

    The six basic components of a method include the access modifier, other modifiers, the return type of the method, the name of the method, a list of the arguments passed to the method, and the body of the method.

    <access modifiers> <other method modifiers>
    <return type> methodName(arg1, arg2, ...)
     { //method body }

    Access Modifier for Methods
    It is a Subset of the method modifier group. This specifies the type of access granted to other objects for that method. You can declare a method public, private, or protected. If no access modifier is specified, the method is accessible to all classes in the current package. A public method may be accessed from any class. A protected method may be accessed from any subclass of the class in which the method is defined. A private method may only be accessed from within the class in which it is declared.

    void myPackageMethod() { 
    // This method may be accessed from any 
    // class declared in the same package 
    }
    public void myPublicMethod() { 
      //This method may be accessed from any class 
    }
    private void myPrivateMethod() {
       // This method cannot be 
       // accessed from other classes.
    }
    protected void myProtectedMethod() { 
      // This method may be accessed from any 
      // subclass of the class that declares it. 
    } 
    public final void myFinalMethod() { 
      // This method cannot be overridden or hidden 
    } 
    public abstract void myAbstractMethod();
    //This method must be overridden 
     // to create a concrete class
    
    
    
    
    public static void myStaticMethod() {
      //Do Work 
    } 
    public native void someExternalMethod(String name); 
    public strictfp void myStrictFpMethod() {
      // All float and doubles 
      // use strict floating point logic. 
    } 
    public syncrhornized void mySynchronizedMethod() { 
      //Multiple threads will not be able to 
      //access this method at the same time. 
    }

    Other Method modifiers
    In addition to the access modifiers, the modifiers static, final, abstract, native, strictfp, and synchronized may be specified.

    Static methods are scoped to the class and not to the instance of the object. These methods may be called without an instance of the class being created. These methods may be called without an instance of the class being created. They may access static variables, but do not have direct access to member variables.

    If the final modifier is specified, the method cannot be overridden or hidden by a subclass. The abstract modifier is used to declare that a method is not implemented in a class. In this case, the method must be implemented by a subclass in order to create a class that can be instantiated. This final modifier cannot be used with the abstract modifier.

    The native modifier is used to define a class that is implemented in code external to the Java Code. This is typically used to allow a Java application to call code in languages such as C++.

    The strictfp modifier is used to force the code within the method to use strict floating-point logic. This applies to all float and double values that are used within the method.

    The synchronized modifier is used when access to the method needs to be synchronized in order to prevent multiple threads from accessing it at the same time. This can be used to keep multiple threads from modifying variables or accessing resources at the same time.

    Return Type
    The return type of the method indicates the return type of the method. The return type of the method indicates the type of value that the method provides to a calling method. The return type is specified by a primitive or object data type, such as void, int, char, String, or Date. The return type is always followed by the method name.

    Method Name
    A method name that follows the int data type would signify that the method returns a type integer when its is involved. Note if the method does not return any type, the method name is preceded by the void return type.

    The method name is user-defined and should be meaningful. According to Java variable naming conventions, if a name consists of two or more words, you join the words to form a single word and capitalize the first letter of each word, except for the first word.

    The name of the method must not be a Java Keyword, such as int, package, or void. In addition, the method name should not begin with a digit and must not contain embedded spaces or periods. For example, findFile is a valid method name.

    If a method defines a return type, then the return keyword is used to return the value. The keyword is followed by the value that is to be returned by the method. Note that this keyword is not required if the method does not return a value because its return type is void.

    Method Arguments
    This is a comma separated list of variable declarations that are defined within enclosing parentheses. Arguments are optional. The parentheses are mandatory.

    Method Body
    The body contains statements and expressions that run when the method is invoked. The body of the method can have conditions and loops, and it can send messages to other instances or to other objects.

    Method Overloading

    Programming languages like C require unique names for different methods in the same program. In Java, you can declare methods with the same name. This process is called method overloading.
    In C, a program contains many methods that perform different tasks. Therefore, it is difficult for an application developer to remember the function and name of each method.

    In Java, you can declare methods with the same name. However, these methods must accept different arguments. This process of declaring methods with the same name is called method overloading.

    In Java, every method has a signature, which consists of a method name and an argument list. The data type of the arguments and their sequence helps define the signature of a method.

    A Class cannot have two methods with the same signature. This is because compiler will not be able to determine which method to invoke.

    In addition to overloading a method with a different number of arguments, you can overload a method by specifying different data types for the arguments. You can also overload a method by providing a different sequence for arguments.

    void addNum(int num, float num1)
    void addNum(float num, int num1)

    Consider an example in which you declare a method that adds an integer value and a float value. In such situation, a user can pass an integer value first and then the float value or vice-versa. To conform to this requirement, you declare two methods with a different sequence of arguments but with the same name.

    Pass By Value: Primitives

    When you invoke a method, you may pass arguments to the method. The arguments are used by the method. Either the value of the argument or a reference to an object is passed.
    When you invoke a method by passing arguments by value, it is know as passing by value. When you invoke a method by passing a value to a method, it is known as passing arguments by value. Java passes all method arguments by value for primitive data types. By passing the arguments by value, the original value of arguments is not altered inside the method. The method only receives a copy of the variable.

    void computePrice(int unitPrice, int numberOfUnits) {
      unitPrice = unitPrice * numberOfUnits; 
      System.out.println(
        "unitPrice in the computePrice method : " 
        + unitPrice); 
    }

    For example, to calculate the total price for four identical items, you multiply the unit price of the item by four. This will not change the price of the individual item. This is because the price was passed by value.
    When you invoke a method by passing a value, a local copy of each argument is made in the called method. Consider the code of the item class shown in the above example. This class contains the computePrice method. This method has a piece of code that changes the value of the unitPrice parameter. The computePrice method calculates the price of the number of items and stores the total in the unitPrice variable. The method also displays the total value.

    In Summary: Calling a method and passing the arguments by value does not affect the original value.

    Pass By Reference: Objects

    Whenever arguments of type Object are passed to a method, their references are passed as opposed to a copy of the object. An object is passed by reference when it is an argument of a method. This ensures that the changes to the object are retained because the actual object is being updated.

    class Employee { String name; 
     String department; 
     double salary;
    
    
      public Employee(String empName, 
                      String empDept, 
                      double empSalary) {
        this.name = empName;
        this.department = empDept;
        this.salary = empSalary;
       }
    
    
       void printAll() {
         System.out.println("Name : " + name);
         System.out.println("Department : " + department); 
         System.out.println("Salary : " + salary); 
       } 
    
    
       public static void main(String args[]) { 
         Employee jane = new 
                      Employee("Jane", "Research", 60000); 
         Employee tempEmp = jane;
         tempEmp.name = "Tom";  
         jane.printAll();  
       } 
    }

    Consider a situation where each employee is assigned three details. These details are name, department, and salary. In addition, an employee can print all the details through the printAll method. The sample code in the example instantiates a new Employee object, bound to the variable jane. The code then assigns Jane to the name, Research to the department, and 60000 to the salary. Next, a variable of type Employee called tempEmp is declared and assigned to the same instance that the variable jane is bound to. Both jane and tempEmp are references pointing to the same object. A change to one will be reflected in the other.

    Related Post: Introduction to Java | Objects and Variables | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements