Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Why is the swap method static?

  1. #1
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Why is the swap method static?

    Bellow I have some code and I was interested in understanding why this method works when it is static? I expected the opposite

    public class demo {
    	int no;
     
    	demo(int no){
    		this.no=no;
    	}
     
    	public static void swap(demo c1, demo c2) {
    		int temp = c1.no;
    		c1.no = c2.no;
    		c2.no = temp;
    	}
     
    	public static void main(String args[]) {
    		demo c1 = new demo(1);
    		demo c2 = new demo(2);
    		swap(c1, c2);
    	    System.out.println("c1.no = " + c1.no); 
    	    System.out.println("c2.no = " + c2.no); 
    	}
     
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Why is the swap method static?

    The swap method does not use any class instance variables. It accesses variables via object references passed to it.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    jenniferruurs (October 4th, 2019)

Similar Threads

  1. What are the rules in using Static Method and Static Variable? HELP!
    By BALLISLIFE in forum Object Oriented Programming
    Replies: 3
    Last Post: August 7th, 2013, 03:52 AM
  2. How to call a static method within a static method in the same class?
    By EDale in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 10th, 2013, 04:13 AM
  3. Replies: 6
    Last Post: May 3rd, 2013, 04:25 PM
  4. Replies: 1
    Last Post: April 3rd, 2012, 06:32 AM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM