Jump to content

[Guide]Java Methods


Ke$ha
 Share

Recommended Posts

It is hard for me to talk about the structure of methods without talking about classes. A method is like a function that is used to act on data in a class. With that in mind, I will use static methods to explain passing parameters and return values.

 

Static Methods

 

A static method is a method in a class that you can call without creating an instance of the class. The Math class contains a lot of static methods.

 

Example:

Math.round(5.35);

A static method is called by using the class name followed by the method name.

 

If I statically import the Math class then I can use the round method like this:

round(5.35);

However, I don't like to do this. It makes more sense to me when I know what class contains the method.

 

To write a static method you include the static keyword in the method prototype.

 

Example:

public static void out(int val) {
System.out.println(val);
}

 

The method is declared to be public and static. It doesn't have a return value. To call this method I would just use the name of the class followed by the method name.

 

Assume that the above method is defined in the class Test. I would then call the method like this:

Test.out(6);

The output would be:

7

One more thing to note about static methods is that main will always be a static method.

 

 

Passing Parameters by Copy

 

When you pass a primitive variable to a method, it will always be passed as a copy. Thus any changes in the methods are not made outside of the method.

 

Example:

public static void out(int v) {
v++;
System.out.println(v);
}

public static void main(String[] args) {
int nVal = 6;
out(nVal);
System.out.println(nVal);
}

The output is:

7
6

Why? When we call the out method the method receives a copy of nVal, and incrementing the variable in the method increments a copy of the variable. The changes are not made to the original variable.

 

Passing by reference

 

If you want to update a value in a method, you can't pass by copy. However, in Java you are not allowed to pass variables by reference. However, Objects are passed by reference. If you want to update a primitive in the method then you can pass the primitive wrapper instead.

 

Java provides wrapper objects for every primitive data type. Ex: the int wrapper is called Integer.

 

Try this:

public static void main(String[] args) {
Integer v = new Integer(5);
out(v);
v++;
System.out.println(v);
}

public static void out(Integer v) {
v++;
System.out.println(v);
}

The output of main will be:

6
7

Why? Since the object is passed by reference, when it is updated in the method is outpated in main as well. Arrays are also passed by reference. If you don't want the original array or object to be updated then you need to make a copy either in main before passing or in the method before you do any modification.

 

Local variables

 

When you create a variable in a method, it is local to that function. This means that once the function returns a value any variable created in the method no longer exists.

 

Try this:

public static void out(int v) {
int x = 2;
v+=x;
System.out.println(v);
}

public static void main(String[] args) {
out(6); // outputs 8
System.out.println(x); // ERROR
}

The output line will throw an error because the x variable doesn't exist in main or as a static variable that is public.

 

Returning arrays

 

Before you name the function, you indicate the return type of the function. You can return an array by writing the function like this:

public static boolean[] sieve(int n) {
boolean[] arbPrimes = new boolean[n+1];

for (int i=2;i<n;i++) {
	if (!arbPrimes[i]) {
		for (int x=2;x*i<n;x++) {
			arbPrimes[i*x] = true;
		}
	}
}
return arbPrimes;
}

This function will return a reference to a boolean array. So in main you can populate a boolean array like this:

boolean[] primes = sieve(500);

Returning values

 

You can return any data type you want. Similar to the function above, just replace boolean[] with whatever data type you want. The function must return a value. However, it can have multiple return points.

public static int ret(int n) {
if (n == 5) {
	return n*2;
}
}

This code will not compile because it doesn't return a value. You might say yes it does. No, it doesn't. It only returns a value if n is 5. The function must always return a value.

Credits chili5 + me

Link to comment
Share on other sites

  • 4 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share



  • Posts

    • Keto Gummies Dischem South Africa     Keto Gummies Dischem South Africa is a keto-accommodating bite that is scrumptious and nutritious. They are made with 100 percent normal fixings, so you can trust their quality. These chewy candies contain probiotics, which assist with supporting solid stomach microorganisms and help in assimilation. These chewy candies likewise contain electrolytes and nutrients, making them an ideal nibble for anybody hoping to get thinner or deal with their diabetes. They are a helpful and versatile tidbit that you can take with you anyplace. Their moderateness and simplicity of procurement online makes them an engaging choice for anybody hoping to add keto snacks to their eating regimen. Whether you're new to keto or as of now appreciate it, Keto Chewy candies Dischem Snaps are an incredible method for getting your fix without undermining your eating routine.   MAIN LINK: https://www.outlookindia.com/outlook-spotlight/keto-gummies-dischem-south-africa-carefully-used-lets-keto-gummies-takealot-za-does-dischem-sell-keto-gummies-where-to-buy-let-s-bhb-apple-keto-gummies--news-258315     MORE LINKS: https://www.outlookindia.com/outlook-spotlight/lets-keto-gummies-reviews-south-africa-2023-exposed-unexpected-facts-weight-loss-keto-gummies-dischem-price-news-253111 https://www.outlookindia.com/outlook-spotlight/keto-capsules-south-africa-let-s-keto-capsules-za-or-must-read-dischem-keto-capsules-south-africa-before-buying--news-247790 https://www.outlookindia.com/outlook-spotlight/keto-gummies-south-africa-reviews-weight-loss-keto-diet-scam-2023-exposed-tim-noakes-let-s-keto-gummies-dischem-clicks-at-price-where-to-order-dischem-keto-gummies-za--news-254942 https://www.outlookindia.com/outlook-spotlight/-facts-525mg-let-s-keto-gummies-clicks-price-south-africa-reviews-2023-scam-exposed-oprah-winfrey-does-dischem-keto-gummies-really-work--news-254933 https://www.outlookindia.com/outlook-spotlight/-exposed-au-nz-via-keto-gummies-australia-must-read-reviews-before-buying-news-238362 https://www.outlookindia.com/outlook-spotlight/authorized-impact-keto-gummies-review-exposed-keto-acv-gummies-2023-impact-keto-acv-gummies-and-keto-life-plus-gummies-does-it-really-work--news-259454  
    • Keto Life Plus Gummies Keto Life Plus Gummies Keto Life Plus Gummies   Weight loss is everyone’s hassle those days. Many humans combat with themselves to reduce off their greater weight however couldn’t get a result. This demotivates a number of them and they will lose preference of dropping weight. Overweight reasons many health-associated issues that might create troubles for your ordinary life. If you observed that your every day exercise or a few tablets can also furthermore need to make you shed pounds in a brief fraction of time. Then this isn't always flow that will help you solely. You want to perform a piece detail that is useful for you frame as well. You want to begin following keto fast as possible. It is the super form of  however it can restriction your flavor buds however doesn’t restriction your eating. It allows you to consume however limits to a few form of food. But to cope with keto flu and to offer hundreds of power there’s a supplement.   https://atozsupplement.com/keto-life-plus-gummies/ https://www.facebook.com/ketolifeplusgummies/ https://keto-life-plus-gummies.company.site/ https://infogram.com/keto-life-plus-gummies-weight-loss-scam-or-trusted-works-1h7z2l8z8xmrg6o?live https://www.scoop.it/topic/keto-life-plus-gummies-by-ketolifeplus-gummies? https://theamberpost.com/post/keto-life-plus-gummies-its-great-dont-by-it https://groups.google.com/g/ketolifeplusgummies/c/zR2GotIpUpc https://sites.google.com/view/ketolifeplusgummiesreviews/ https://www.sympla.com.br/produtor/ketolifeplusgummies https://educatorpages.com/site/getketolifeplusgummies/ https://ketolifeplusgummies.wixsite.com/ketogummies https://keto-life-plus-gummies-71.webselfsite.net/ https://keto-life-plus-gummies.hp.peraichi.com/ https://keto-life-plus-gummies.jimdosite.com/ https://keto-life-plus-gummies.yolasite.com/ https://www.dibiz.com/ketolifeplusgummies https://jemi.so/keto-life-plus-gummies  
    • Check net.sf.l2j.gameserver.handler.admincommandhandlers. In there you should see several classes representing various admin commands. You need to make a new class by observing the existing ones and check: if (command.startsWith("admin_add_pvp")) {         GameObject targetObject = player.getTarget();         if (targetObject == null  || !(targetObject instanceof Player))                 return;         try         {                 int pvp = Integer.parseInt(command.substring(14));                 Player target = (Player) targetObject;                target.setPvpKills(target.getPvpKills() + pvp);                target.broadcastUserInfo(); // Alternatively you can target.sendPacket(new UserInfo(target)) but in case you got systems like pvp color system use this.         }         catch (Exception e)         {                 player.sendMessage("Usage: //add_pvp amount");         } }     Please note that I wrote this code here in the reply section I didn't actually check it with aCis, it might need a few changes. You can easily make such a thing tho you don't even neeed to know java to understand how it works.
    • Let's me know if you have the answer.
  • Topics

×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock