Instantiation of Class, Method, Variable (ICMV)

Instantiation is used to create an object or an instance of a class. We use the new operator. For example, if you want to create an instance of the string class, we use the following code:

String str2 = new String("Hello world!");

That means the same as:

String str2 = "Hello";

Class and Method Variables

In addition to instance variables, it is also possible to define class variables, which are variables that belong to the entire class. This means that they have the same value for all objects in the same class. They are also called static member variables.

Why do you need to use methods / functions?

In the example we discussed earlier, we only have one method, and that is the main() method. In Java, we can define multiple methods that we will call from different methods.

A method is a separate part of code that will be called by the main program and some other methods to perform some specific functions.

The following are the characteristics of the method:

  • can return one or no values
  • it may accept as few required parameters or no parameters at all. Parameters are also referred to as function arguments.
  • Once the method has finished executing, it will return to the method that called it.

Now why do we need to create methods? Why don't we put all the code in one big method? The solution here is decomposition. We can also do this in Java by creating methods to address specific parts of the problem. Taking a problem and breaking it down into small, manageable pieces is essential to writing large programs.

How to Call Instance via Method & Passing Variables

Now let's illustrate how to call a method, let's use the string class as an example. You can use the Java API documentation to see all the available methods in the string class. Later, we will create our own methods. But for now let's use what is available.

To call an instance method, we write:

nameOfObject.nameOfMethod(parameters);

Let's take two examples found in the String class.

Using the method:

String str1 = "Hello";
char x = str2.charAt(0); //will return the character H
//simpan pada variabel x
String str2 = "hello";
//return boolean
boolean result = str1.equalsIgnoreCase(str1);

Post a Comment

Previous Next

نموذج الاتصال