Jav Body Swap

Jav Body Swap



👉🏻👉🏻👉🏻 ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻

































Jav Body Swap


Sign up with email
Sign up




Sign up with Google



Sign up with GitHub



Sign up with Facebook




Asked
10 years, 5 months ago


Active
2 years, 4 months ago


This question already has answers here :



Java method to swap primitives

(8 answers)



1,057 1 1 gold badge 9 9 silver badges 25 25 bronze badges


547 1 1 gold badge 5 5 silver badges 3 3 bronze badges



Instead of simply giving a swap method, I'd give you this article . It explains how to make a swap-method, but also explains how not to make it, and why it is not possible in the form you expect it, due to the fact Java is only pass-by-value (unlike C/C++)

–  Bozho
Sep 2 '10 at 7:14






wrong answer.. java is not only pass by value.. When you pass a none-native value you're passing a pointer. If you have to new it, it's a pointer. javadude.com/articles/passbyvalue.htm

–  baash05
Mar 7 '12 at 10:48



you are passing a reference to the object - yes, but the reference is copied. "pass reference by value" is probably a better description. You can't change the reference that was passed, you can only change the target obejct

–  Bozho
Mar 7 '12 at 11:03



I think this method is the closest you can get to a swap function in Java.

–  dansalmo
Jun 25 '14 at 16:20



I found this article trying to figure out the same thing. link

–  Jaca
Feb 5 '15 at 5:40


105k 61 61 gold badges 295 295 silver badges 388 388 bronze badges



You'd hire someone who would write code that obscure? Maybe if they would then explain why they would never, ever actually do that in production code.

–  ToolmakerSteve
Sep 9 '15 at 19:53



plus one for the trick, minus one for the fact it cannot be widely use in production without some good explanation. It cannot be enclosed in separate method, can it?

–  Bart
Feb 24 '16 at 14:21






See here stackoverflow.com/questions/1363186/… to learn how it works.

–  marcus
Apr 5 '17 at 21:39



Thank you for this. Not having had Java as my primary language for a long time, I misunderstood part of the grammar. I thought one change Java had made from C/C++ was that assignments are not expressions. In fact, the change was that Java introduced a proper boolean type that can't be used interchangeably with integers, so you can't use an assignment in an if statement that does not return a boolean. Assignments return whatever type is involved in the assignment and they return the right hand side of the assignment expression.

–  froggythefrog
Nov 22 '18 at 18:25






@GabrielŠčerbák I would make the caveat that if the employee who uses this can express it in such a way that it's clear a swap is being performed, then they should be applauded. The downside of this solution is the downside of trying to make a swap function in Java in the first place. You can't actually swap the basic types without stuffing them into an object or array first. :/

–  froggythefrog
Nov 22 '18 at 18:31


270k 58 58 gold badges 438 438 silver badges 561 561 bronze badges



Since I am doing some sorting algorithms, I have array of ints. Do I need to typecast normal ints to AtomicInteger before calling swap?

–  Melinda
Sep 2 '10 at 7:23



if you want to sort an array of ints, use Arrays.sort() download.oracle.com/javase/6/docs/api/java/util/…

–  Sean Patrick Floyd
Sep 2 '10 at 7:26



btw there's no way to typecast a primitive type to an object, but AtomicInteger has a constructor with an int

–  Sean Patrick Floyd
Sep 2 '10 at 7:35



@Melinda: Arrays.sort is the answer, but if you want to swap two simple values follow the ol'good method: int aux = b; b = a; a = aux;

–  helios
Sep 2 '10 at 7:37



But one may not always want to sort only ints, let alone only sort primitives. The real "will always work in Java" answer is your swap method using setters and getters. It worked for me and was a big help, thank you.

–  Benjamin R
Oct 22 '14 at 8:03


3,317 3 3 gold badges 33 33 silver badges 44 44 bronze badges



because this does not answer the question. the question is about an independent function which can take two variables as argument and swaps them.

–  mightyWOZ
Aug 20 '16 at 10:19


4,124 3 3 gold badges 35 35 silver badges 42 42 bronze badges


67.7k 14 14 gold badges 113 113 silver badges 166 166 bronze badges



Integer objects are immutable, so that won't work either.

–  Michael Borgwardt
Sep 2 '10 at 7:16



Integers won't help, they are immutable. You need a container, either AtomicInteger (see my answer) or a 1-element List or array or any such thing

–  Sean Patrick Floyd
Sep 2 '10 at 7:16



Again, Integer objects will be passed by value. This won't work either. javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

–  Lunivore
Sep 2 '10 at 7:16



@Lunivore: no, Integer objects are not passed by value. They are not passed at all. A reference to an Integer object will be passed by value. You can only pass references and primitive values in Java, never objects!

–  Joachim Sauer
Sep 2 '10 at 7:39



Sorry. I was being lazy, and your description is far more accurate. In my defence, the URL explains it very well, even for objects which aren't immutable.

–  Lunivore
Sep 2 '10 at 11:24


51.9k 12 12 gold badges 89 89 silver badges 186 186 bronze badges


1,778 1 1 gold badge 16 16 silver badges 25 25 bronze badges


107k 16 16 gold badges 167 167 silver badges 248 248 bronze badges



True. And even interesting. But its more coding than inline swap using a temp variable. Perhaps would be good to point out that if a programmer is willing to carry the two values around in some object, then they can be swapped within that object. However, I can't think of any algorithms where that helps in practice.

–  ToolmakerSteve
Sep 9 '15 at 20:33





404k 78 78 gold badges 476 476 silver badges 510 510 bronze badges



It's not possible to swap two anythings by passing them into a method as parameters - not just primitives.

–  Lunivore
Sep 2 '10 at 7:25



@Lunivore I thought that objects where passed by reference. So, in that case, why couldn't you swap their references?

–  Cristian
Sep 2 '10 at 7:33



@Cristian: not correct: java objects are references that are passed by value. That's a difference

–  Sean Patrick Floyd
Sep 2 '10 at 7:43



@seanizer thanks for the clarification!

–  Cristian
Sep 2 '10 at 12:54



C also uses pass-by-value, only C++ has pass-by-reference. Even in the example given it passes the value of both pointers. That's why not having pass-by-reference doesn't have anything to do with this limitation in Java.

–  Trinidad
Jan 27 '17 at 18:13


16.2k 7 7 gold badges 34 34 silver badges 73 73 bronze badges



This is a useful observation.

–  ToolmakerSteve
Sep 9 '15 at 20:26


1,809 2 2 gold badges 14 14 silver badges 21 21 bronze badges



Not sure why this got downvoted as it's actually accurate. If you have those two values and you want to swap them, you can inline the method and it works just fine - but I agree, I can't really see why you'd need it in Java either.

–  Lunivore
Sep 2 '10 at 11:26



Thanks. I was also suprised. It may be too laconic, but the code indicates C-like coding style which totally isn't the way to do things in Java.

–  Bart
Sep 2 '10 at 11:35






A sweeping statement like "You really don't need that swap in Java" merits a downvote. The utility of swap as a programming concept is indisputable. There are numerous algorithms in which swap is a key step. If Bart wishes not to be downvoted, he needs to provide an alternative solution, for situations where swap is traditionally used in algorithms (as several other answers do, however incompletely).

–  ToolmakerSteve
Sep 9 '15 at 20:18


16.1k 3 3 gold badges 40 40 silver badges 84 84 bronze badges


34.5k 24 24 gold badges 123 123 silver badges 180 180 bronze badges



This doesn't work. You need to read the question more carefully and read some of the other answers.

–  Andrew Martin
Aug 21 '13 at 21:13



Try to do carefully @AndrewMartin. Because I has worked without any problems.

–  Yunus Seçgin
Aug 22 '13 at 21:23



You've missed the point of the question. The OP was asking how to do a swap in a method like in C . Java cannot do that, as it passes by value. If a swap is done in a method, it cannot be stored (unless values are returned). If two values were passed into a method and your code was executed, it wouldn't store the results out of the method. Read the question against and some of the other answers.

–  Andrew Martin
Aug 22 '13 at 22:00





13.5k 5 5 gold badges 36 36 silver badges 51 51 bronze badges


public class swaptemp {
public static void main (String[] args) {
String s1= "10" ;
String s2= "20" ;
String temp;
System.out.println(s1);
System.out.println(s2);

temp=Integer.toString(Integer.parseInt(s1));
s1=Integer.toString(Integer.parseInt(s2));
s2=Integer.toString(Integer.parseInt(temp));

System.out.println(s1);
System.out.println(s2);
}
}



650 11 11 silver badges 18 18 bronze badges



Please try to include the comments/explanation with your code to help others understand it better.

–  user2004685
Feb 22 '16 at 13:56


//here is also another answer:
class SwapDemo {
static int a= 1 , b= 2 ;
public static void main (String [] args) {
Swap swp = new Swap();
swp.swaps(x,y);
System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
}
}
class Swap {
void swaps ( int c, int d) {
SwapDemo f = new SwapDemo();
f.a = c;
f.a = d;
}
}




This looks a little bit dizzy, but it simply not OOP. Hope this will also helps.

–  Tepken Vannkorn
Dec 8 '10 at 15:47



x and y is undefined, and this is not swapping the passed variables.

–  Lie Ryan
Dec 8 '10 at 16:10






This is not an answer to the question. This is not what "swap two variables" means in computer science. Instead, this is "alter the value of two members". Not even close.

–  ToolmakerSteve
Sep 9 '15 at 20:24





class Swap2Values {
public static void main (String[] args) {
int a = 20 , b = 10 ;

//before swaping
System.out.print( "Before Swapping the values of a and b are: a = " +a+ ", b = " +b);

//swapping
a = a + b;
b = a - b;
a = a - b;

//after swapping
System.out.print( "After Swapping the values of a and b are: a = " +a+ ", b = " +b);
}
}




the question is how to write a swap function in java and not how to do swap in java

–  Muthu Ganapathy Nathan
Aug 14 '11 at 5:27

Business Process Optmization, Enterprise Software, Software Development / Engineering
Business to Business, Health Care, Logistics & Distribution

Stack Overflow

Questions
Jobs
Developer Jobs Directory
Salary Calculator
Help
Mobile
Disable Responsiveness


Products

Teams
Talent
Advertising
Enterprise



Company

About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us



Stack Exchange Network

Technology
Life / Arts
Culture / Recreation
Science
Other


Join Stack Overflow to learn, share knowledge, and build your career.
I am new to java. How to write the java equivalent of the following C code.
The short answer is: you can't do that, java has no pointers.
But here's something similar that you can do:
You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.
BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int) :
apparently the real objective is to sort an array of ints.
That's a one-liner with Arrays.sort(int[]) :
And here is a simple helper function to swap two positions in an array of ints:
Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator .
Use this one-liner for any primitive number class including double and float :
There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.
So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).
An alternative is to let the method return an array or pair of ints.
In cases like that there is a quick and dirty solution using arrays with one element:
Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:
What about the mighty IntHolder? I just love any package with omg in the name!
Java uses pass-by-value . It is not possible to swap two primitives or objects using a method.
Although it is possible to swap two elements in an integer array.
You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:
However, swapping mutable objects may be possible by rewriting properties:
You have to do it inline. But you really don't need that swap in Java.
Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.
In Java there aren't really pointers, so this won't work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection .
We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn't help you, try posting the calling code as we'll probably have a good idea of how to solve the real problem Java-style.
Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.
You can swap variables with or without using a temporary variable.
Here is an article that provides multiple methods to swap numbers without temp variable :
Swapping by using pointer is not possible in java. However , you can implement swapping by passing array containing two objects.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa . rev 2021.2.10.38546


Функция swap для обмена данных между переменными
How to write a basic swap function in Java - Stack Overflow
Метод swap - Java программирование | ExamClouds
Можно ли написать метод swap в Java ? [дубликат]
Java - урок 7.6 (меняем местами переменные - " swap ")




Главная



Java программирование



Алгоритмы на Java



Метод swap



Читайте также:

Среднее арифметическое

Числа Фибоначчи

Вычисление сложности алгоритма

Инвертирование массива

Сортировка пузырьком

Сортировка выбором

Поиск элемента

Задания



Часто в процессе решения той или иной задачи, две переменные должны обменяться значениями. Есть два варианта реализации обмена значениями:
Вводим временную переменную, которая на время придержит значение из одной переменной:
Третья переменная не вводится, обмен достигается путем сложения и вычитания:

Eating Pussy Real Good
Nude Red Headed Men
Asian In Panties
Asian Wet Pussy Pics
Super Hot Secretaries

Report Page