partho
partho

Reputation: 1084

Defining method in java

Let's say, 5 is considered a good number. A method is to define to check a number is good or not. Parameter type int and return type is boolean. If argument is 5 it will return true and false otherwise.

See this code:

class Library{
    boolean isGood(int num){
        return num==5;
    }
}

public class String_handling {
    public static void main(String[] args) {
       int num=8;
       System.out.println(new Library().isGood(num));
    } 
}

I know this code is okay.

But I want to define a method such that I can invoke in this way:

System.out.println(num.isGood());

As work on string like this:

MyString.contains("xy");

MyString.substring(0,4);

Is there any way? Give an example.

Upvotes: 1

Views: 100

Answers (1)

Kevyn Meganck
Kevyn Meganck

Reputation: 609

Since int is a primitive, the only way you can to that, is to make your own class MyInteger and add your method isGood(), like so

public class MyInteger{

    private int num;

    public MyInteger(int num){
        this.num = num;
    }

    public boolean isGood(int num){
        return this.num == num;
    }

}

Upvotes: 3

Related Questions