Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
Now Reading
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Swapping of two numbers in Java is one of the first programs taught to beginners when they start out learning Java programming. It is a program where the values inside two variables are swapped with each other. It is important to learn how values can be swapped, as this concept is used in many algorithms and programs.
This tutorial aims to provide a detailed guide on swapping two numbers in Java. We will discuss the various ways in which two numbers can be swapped in Java through examples. Studying these examples will provide a better understanding of this concept.
We can follow a general algorithm that we can use to write a program in any programming language for swapping two numbers. The specific implementation may vary based on the programming language syntax and conventions.
Algorithm:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 10;
int num2 = 20;
printf("Before swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
swap(&num1, &num2);
printf("After swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
return 0;
}
The above C program defines a swap function that takes two integer pointers as parameters and swaps their values using a temporary variable. Inside the main function, two integer variables num1 and num2 are declared and initialized with values 10 and 20, respectively.
The program prints the values of num1 and num2 before swapping.
Then, the swap function is called, passing the addresses of num1 and num2 as arguments.
After the swapping operation, the program prints the values of num1 and num2 to verify the swapping. The program finally returns 0, indicating successful execution.
def swap_numbers(a, b):
a, b = b, a
return a, b
num1 = 10
num2 = 20
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
This Python program defines a function swap_numbers that takes two parameters, a and b, and swaps their values using tuple assignment. Two variables num1 and num2 are declared and assigned values 10 and 20 respectively. The program prints the values of num1 and num2 before swapping.
Then, the swap_numbers function is called, passing num1 and num2 as arguments, and the returned values are assigned back to num1 and num2. After the swapping operation, the program prints the values of num1 and num2 to verify the swapping.
<?php
function swapNumbers(&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}
$num1 = 10;
$num2 = 20;
echo "Before swapping:\n";
echo "num1 = " . $num1 . "\n";
echo "num2 = " . $num2 . "\n";
swapNumbers($num1, $num2);
echo "After swapping:\n";
echo "num1 = " . $num1 . "\n";
echo "num2 = " . $num2 . "\n";
?>
The PHP program defines a function swapNumbers that takes two variables by reference (&$a and &$b) and swaps their values using a temporary variable. Two variables $num1 and $num2 are declared and assigned values 10 and 20 respectively.
The program echoes the values of $num1 and $num2 before swapping. Finally, the swapNumbers function is called, passing $num1 and $num2 as arguments, and the values are swapped in place. After the swapping operation, the program echoes the values of $num1 and $num2 to verify the swapping.
using System;
class Program
{
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int num1 = 10;
int num2 = 20;
Console.WriteLine("Before swapping:");
Console.WriteLine("num1 = " + num1);
Console.WriteLine("num2 = " + num2);
Swap(ref num1, ref num2);
Console.WriteLine("After swapping:");
Console.WriteLine("num1 = " + num1);
Console.WriteLine("num2 = " + num2);
}
}
The C# program defines a Swap method that takes two integer parameters using the ref keyword and swaps their values using a temporary variable. Inside the Main method, two integer variables, num1 and num2, are declared and initialized with values 10 and 20, respectively.
The program writes the values of num1 and num2 before swapping using Console.WriteLine.
The Swap method is called, passing num1 and num2 as ref arguments. After the swapping operation, the program writes the values of num1 and num2 again to verify the swapping using Console.WriteLine.
The different methods in which string inputs can be swapped in Java are:
In this method, a third variable is added to temporarily hold the value of any one variable while the values of the two variables are switched. The variables can be switched out successfully by sequentially assigning values.
You can switch numbers without a temporary variable by using the XOR (^) operator. The bits are switched by using the XOR operator to combine two variables, which causes their values to change.
public class upGradTutorials {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swapping logic using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
This program demonstrates how to swap the values of two numbers in Java using a temporary variable. Initially, we have two variables, num1, and num2, with values of 10 and 20, respectively. We print the values of num1 and num2 before the swapping operation.
To swap the values, we introduce a third variable called temp. We store the value of num1 in temp to preserve it. Then, we assign the value of num2 to num1. Finally, we assign the value stored in temp (the original value of num1) to num2.
public class upGradTutorials {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
Like the previous example, this Java program initializes two integer variables, num1, and num2, with values 10 and 20, respectively. Before swapping, the program prints the values of num1 and num2 using System.out.println.
To swap the values without using a temporary variable, the program performs the following steps:
After the swapping operation, the program prints the values of num1 and num2 again to verify the swapping. The program outputs the final swapped values of num1 and num2.
public class ArraySwapExample {
public static void main(String[] args) {
int[] numbers = {10, 20};
System.out.println("Before swapping:");
System.out.println("numbers[0] = " + numbers[0]);
System.out.println("numbers[1] = " + numbers[1]);
swap(numbers, 0, 1);
System.out.println("After swapping:");
System.out.println("numbers[0] = " + numbers[0]);
System.out.println("numbers[1] = " + numbers[1]);
}
public static void swap(int[] arr, int index1, int index2) {
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
}
The above program initializes an array named numbers with two elements: 10 and 20. Before swapping, the program prints the values at index 0 and index 1 of the numbers array using System.out.println. The swap method is called passing the numbers array along with the indices of the elements to swap (0 and 1).
Inside the swap method, a temporary variable temp is used to store the value at index1.
The value at index2 is assigned to index1, effectively swapping the values. Finally, the value stored in temp is assigned to index2, completing the swap operation. After the swapping operation, the program prints the updated values at index 0 and index 1 of the numbers array to verify the swapping.
Swapping numbers in Java frequently comes up in interviews and discussions programming. It entails converting the values of two variables or array members. Using a temporary variable is the simplest method, although bitwise operators can swap values without needing a second variable. Alternating the indices of the numbers in an array also allows for number switching.
When performing swaps, it is crucial to consider the extent of the variables and their possible influence on performance, especially when many swaps are involved. You can check out courses from upGrad to master concepts like swapping of two numbers in Java.
Yes, the scanner class can swap two numbers in Java. In this case, the input for the number is taken from the users, after which the normal swapping methods are applied, as discussed in this tutorial.
Yes, by switching the indices of two numbers stored in an array, you can change the values of the numbers.
Using a temporary variable or bitwise operator to swap two numbers in Java is typically effective and has little effect on performance. It's crucial to remember that frequent Using a temporary variable or bitwise operator to swap two numbers in Java is typically effective and has little effect on performance. It's crucial to remember that frequent swapping within a loop or extensive swapping operations may significantly affect performance.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...