3

I am a beginner with the java language and programming as a whole.

I understand that to call methods from another class, we call that method with:

ClassName.methodName(arguments);

For example, when we want to find the square root of an integer using the Math classs:

int x = 4;
int root = (int)(Math.sqrt(x));

However, when we use certain methods in other classes, such as the charAt() method in the String class, we access that method using something like:

String str = "Greetings!";
char ch = str.charAt(0);

This is also true for other methods in the String class such as: codePointAt() and compareTo().

Why do we call methods differently when using methods from certain classes like the String class? How do we know when to call methods like this as opposed to the other way?

Thanks!

Zampanò
  • 574
  • 3
  • 11
  • 33

2 Answers2

3

There are two kinds ow methods.

  1. Static
  2. Non-Static

First case you are talking about is Static methods. If you read more, you'll know that you cannot instantiate a Static class. i.e. You can't create objects from an static class. So, if there is a method in a static class, you have to access them using the class name. There are also static methods in non-static classes.

eg.: Think about the square root method. Finding the square root is same procedure, no matter what number you want to find the square root. So there's no need of creating square root method at every time an object is created. Instead, we can access it using class name. Hence these methods are sometimes called class-methods

Non-Static methods in other hand may need to be instantiated every time an object is created as they are object specific.

eg. Think about charAt() method. charAt(0) will return a char depending on the String object you call it on.

Read This question and This article is also helpful.

Community
  • 1
  • 1
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
0

Methods which are declared as static can be called at the class level. I.e. You don't need an instance of that class to call them.

James Owen
  • 256
  • 1
  • 11