Lecture 2

Lecture # 2


A class is a user defined datamember. A class is the description from which individual objects are created. You can instantiate many objects from one class defination. The section between the curly brackets { } are reffered to as its body. The variables declared in the body of a class are referred to as its member variable.

Syntax for class:-
[Access Specifier/Modifier-List] class < class name> [extends SuperClass] [implements Interface-List]


An object is an instance of a class and a programming unit of any particular class. In real wrold objects have state and behaviours compareitvely computer objects have state and behaviour as well. e.g., dog has color, name, breed as well behaviour like wagging, barking, eating etc. Computer objects has also state stored in fields and behaviours is shown by via of methods.

Creating an object

  • A class provides the blueprints for objects. Basically an object is created from class. Three steps when creating an object from a class.
  • Declaration:- A variable declaration with a variable name with an object type.
  • Instantiation:- The ‘new’ key word is used to create the object.
  • Initialization:- ‘new’ is followed by a constructor. This call initalize a new object.Syntax for object:-
    classname reference_variable = new classname([parameter-list]);



    //start of class Helo

    Class Helo


                     //Start of Main Method

                        public static void main(String args[])


                                Helo p = new Helo();

                             } //End of Main Method

          } //End of Person Class

Dot Operator

The dot operator is used to access the instance variables (data fields) of an object. The general form for accessing the data field of an object is.

  • Object-name.variable name
  • Object-name.method name (parameter list)





A Java method is a collection of statements that are grouped together to perform an operation.


Method are named blocks of code that can be called from elsewhere in your program in order to accomplish some task. A method is defined inside of a class definition at the same level as the instance variable.


modifier return-type class-method (parameter-list)


Method statments;


In the Java programming language, a method is a section of the program that contains a set of instructions or code. In a Java program, similar to a cake recipe, a method has a set of instructions. When the method is called, the set of instructions within the method is executed.

Parameters of a MethodHere, the name of the method is addNumbers. When the method addNumbers is called, the code within the method is executed, and the variable z is printed.

When following the method to make cake, the ingredients like sugar and butter are combined and processed to make the final product. Similarly, Java methods have parameters (like ingredients) or data that are inputted or passed into the method. The method uses these parameter values to do the necessary data manipulation and processing. The method then usually returns the final value after all the necessary data processing is successfully performed.

The parameters of a method are declared within parentheses following the method name. If there is more than one parameter, they are separated by commas. Both the data type and the variable name (int m, int n) are specified for the parameters.In this example, m and n are parameters. The Java method subtractNumbers finds the difference between m and n and saves the result in a new variable p. The values of the parameters m and n are used to generate the new variable p that is printed out on the computer screen.

Types of Java methods

Depending on whether a method is defined by the user, or available in standard library, there are two types of methods:

  • Standard Library Methods
  • User-defined Methods

Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

For example,

  • print() is a method of java.io.PrintSteam. The print(“…”) prints the string inside quotation marks.
  • sqrt() is a method of Math class. It returns square root of a number.

Here’s an working example:

public class Numbers {    public static void main(String[] args) {        System.out.print(“Square root of 4 is: ” + Math.sqrt(4));    }}

When you run the program, the output will be:

Square root of 4 is: 2.0

User-defined Method

You can also define methods inside a class as per your wish. Such methods are called user-defined methods.

How to create a user-defined method?

Before you can use (call a method), you need to define it.

Here is how you define methods in Java.

public static void myMethod()


               System.out.println(“My Function called”);


Here, a method named myMethod() is defined.

You can see three keywords public, static and void before the function name.

  • The public keyword makes myMethod() method public. Public members can be accessed from outside of the class. To learn more, visit: Java public and private Modifiers.
  • The static keyword denotes that the method can be accessed without creating the object of the class. To learn more, visit: Static Keyword in Java
  • The void keyword signifies that the method doesn’t return any value. You will learn about returning value from the method later in this article.

In the above program, our method doesn’t accept any arguments. Hence the empty parenthesis (). You will learn about passing arguments to a method later in this article.

The complete syntax for defining a Java method is:

modifier static returnType nameOfMethod (Parameter List) {               // method body}


  • modifier – defines access type whether the method is public, private and so on.
  • static – If you use static keyword in a method then it becomes a static method. Static methods can be called without creating an instance of a class.For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.
  • returnType – A method can return a value.It can return native data types (int, float, double etc.), native objects (String, Map, List etc.), or any other built-in and user defined objects.If the method does not return a value, its return type is void.
  • nameOfMethod – The name of the method is an identifier.You can give any name to a method. However, it is more conventional to name it after the tasks it performs. For example, calculateInterest, calculateArea, and so on.
  • Parameters (arguments) – Parameters are the values passed to a method. You can pass any number of arguments to a method.
  • Method body – It defines what the method actually does, how the parameters are manipulated with programming statements and what values are returned. The codes inside curly braces { } is the body of the method.

Returning a Value

When the method to make cake is completed using the necessary ingredients, the final result is a new product that is the cake. By using the parameters that are passed into the method, the method generates a new product or result. The result returned by the method is also available for use by the Java program to which this method belongs.

In this example, the variable p is returned by the method. The return statement is a Java keyword return followed by the variable name.

When the method is declared, the return type of the variable is listed just before the name of the method. Here, the name of the method is subtractNumbers, and the data type of the variable being returned, p, is int (or integer), so the method declaration states:

where int is the return type of the method subtractNumbers.

In Java, a method can return only one variable at a time. For example, the following code will generate an error:

Here, there are the return types of 2 variables (int int) listed before the name of the method, subtractNumbers. There are 2 return statements to return p and q. However, methods in Java can return only one value at a time. To return multiple values, you would need to use an array.

Methods that Do Not Return a Value

Now, let’s look at methods that do not return a value. Some Java methods do not return a value; they process a set of tasks without a return value. When a method does not return a value, it is indicated by the keyword void before the name of the method.

How to call a Java Method?

Now you defined a method, you need to use it. For that, you have to call the method. Here’s how:


This statement calls the myMethod() method that was declared earlier.

  1. While Java is executing the program code, it encounters myMethod(); in the code.
  2. The execution then branches to the myFunction() method, and executes code inside the body of the method.
  3. After the codes execution inside the method body is completed, the program returns to the original state and executes the next statement.

Example: Complete Program of Java Method

Let’s see a Java method in action by defining a Java class.

class Main


      public static void main(String[] args) {

      System.out.println(“About to encounter a method.”);       // method call      


      System.out.println(“Method was executed successfully!”);

   }   // method definition

   private static void myMethod()


       System.out.println(“Printing from inside myMethod()!”);


When you run the program, the output will be:

About to encounter a method.Printing from inside myMethod().Method was executed successfully!

The method myMethod() in the above program doesn’t accept any arguments. Also, the method doesn’t return any value (return type is void).

Note that, we called the method without creating object of the class. It was possible because myMethod() is static.

Here’s another example. In this example, our method is non-static and is inside another class.

class Main


       public static void main(String[] args)


       Output obj = new Output();

System.out.println(“About to encounter a method.”);       // calling myMethod() of Output class


       System.out.println(“Method was executed successfully!”);


class Output { 

  // public: this method can be called from outside the class

   public void myMethod()


       System.out.println(“Printing from inside myMethod().”);


When you run the program, the output will be:

About to encounter a method.Printing from inside myMethod().Method was executed successfully!

Note that, we first created instance of Output class, then the method was called using objobject. This is because myMethod() is a non-static method.

Java Methods with Arguments and Return Value

A Java method can have zero or more parameters. And, they may return a value.

Example: Return Value from Method

Let’s take an example of method returning a value.

class SquareMain {    public static void main(String[] args) {        int result;        result = square();         System.out.println(“Squared value of 10 is: ” + result);    }          public static int square() {        // return statement        return 10 * 10;    }}

When you run the program, the output will be:

Squared value of 10 is: 100

In the above code snippet, the method square() does not accept any arguments and always returns the value of 10 squared.

Notice, the return type of square() method is int. Meaning, the method returns an integer value.

As you can see, the scope of this method is limited as it always returns the same value.

Now, let’s modify the above code snippet so that instead of always returning the squared value of 10, it returns the squared value of any integer passed to the method.

Example: Method Accepting Arguments and Returning Value

public class SquareMain {    public static void main(String[] args) {        int result, n;        n = 3        result = square(n);        System.out.println(“Square of 3 is: ” + result);       n = 4        result = square(n);         System.out.println(“Square of 4 is: ” + result);    }static int square(int i) {        return i * i;    }}

When you run the program, the output will be:

Squared value of 3 is: 9Squared value of 4 is: 16

Now, the square() method returns the squared value of whatever integer value passed to it.

Java is a strongly-typed language. If you pass any other data type except int (in the above example), compiler will throw an error.

The argument passed n to the getSquare() method during the method call is called actual argument.

result = getSquare(n);

The parameter i accepts the passed arguments in the method definition getSquare(int i). This is called formal argument (parameter). The type of the formal argument must be explicitly typed.

You can pass more than one argument to the Java method by using commas. For example,

public class ArithematicMain {    public static int getIntegerSum (int i, int j) {        return i + j;    }    public static int multiplyInteger (int x, int y) {        return x * y;    }    public static void main(String[] args) {        System.out.println(“10 + 20 = ” + getIntegerSum(10, 20));        System.out.println(“20 x 40 = ” + multiplyInteger(20, 40));    }}

When you run the program, the output will be:

10 + 20 = 3020 x 40 = 800

The data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.

Example: Get Squared Value Of Numbers from 1 to 5

public class JMethods {    // method defined    private static int getSquare(int x){        return x * x;    }    public static void main(String[] args) {        for (int i = 1; i <= 5; i++) {            // method call            result = getSquare(i)            System.out.println(“Square of ” + i + ” is : ” + result); }    }}

When you run the program, the output will be:

Square of 1 is : 1Square of 2 is : 4Square of 3 is : 9Square of 4 is : 16Square of 5 is : 25

In above code snippet, the method getSquare() takes int as a parameter. Based on the argument passed, the method returns the squared value of it.

Here, argument i of type int is passed to the getSquare() method during method call.

result = getSquare(i);

The parameter x accepts the passed argument [in the function definition getSquare(int x)].

return i * i; is the return statement. The code returns a value to the calling method and terminates the function.

Did you notice, we reused the getSquare method 5 times?

What are the advantages of using methods?

  • The main advantage is code reusability. You can write a method once, and use it multiple times. You do not have to rewrite the entire code each time. Think of it as, “write once, reuse multiple times.”
  • Methods make code more readable and easier to debug. For example, getSalaryInformation() method is so readable, that we can know what this method will be doing than actually reading the lines of code that make this method.

Previous Lecture

Next Lecture

Lecture No

1     2     3     4     5     6     7     8     9     10     11     12     13     14     15

Please follow and like us:

Author: ilearnpoint

1 thought on “Lecture 2

Leave a Reply

Your email address will not be published. Required fields are marked *