Saturday, 30 April 2011

Difference between concat and append function

The concat function is present in String class but the append functin is present in StringBuffer/StringBuilder class.
The concat function concats the string on which it is invoked with the string passed as parameter to this function. The result returned is a new String with both the strings concatanated.


The append function appends a String to the String represent by the StringBuffer/StringBuilder object on which the append() method is invoked. The result returned is the same StringBuffer/StringBuilder object on which this method was invoked.

Class level lock vs instance level lock

A class level lock is the lock which makes all object of a class to wait until the corresponding lock is not released.
e.g

Class A{
static synchronized void foo(){}
}


Here the method foo is synchronized and hence all the threads on all the objects of the class will wait until the object currently running the foo method completes its execution.


Similarly an instance level lock makes all the threads started using the instance of the class to wait until the lock is not released.
e.g.

Class A{
//static is missing
synchronized void bar(){}
}

Here all the threads started from the object which is currently executing the bar method will wait until the current threads completes its execution. Note that other threads of other objects can execute the bar method while another object's thread is executing the bar method.

What is the difference between yield and sleep method?

Yield:


1) It causes the high priority threads to pause execution and give the low priority threads a chance to execute.
2) The thread going into waiting queue because of yield method release any locks held by them.

Sleep:

1) It causes the thread on which it is invoked to go into waiting state for some time interval.
2) The thread going into waiting queue because of yield method doesn't release any locks held by it.

Every annotation in JDK 1.5 onwards has a corresponding class

Every annotation in JDK 1.5 onwards has a corresponding class. For example, the @override annotation which tells that a method is an overridden version of the method inherited from the super class, has a corresponding Override.class.  

Similarly we have the Deprecated.class for the @deprecated annotation. We can see the contents of the corresponding source file to check what all attributes/parameters are being supported by the @override annotation. The Override.class has the following contents:

/  (version 1.5 : 49.0, no super bit)
@java.lang.annotation.Target(value={java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.SOURCE)
public abstract @interface java.lang.Override extends java.lang.annotation.Annotation {

}


This suggests us that the annotation @Override can have two attributes viz Target and Retention. The value accepted by Target attribute is of type METHOD and of Retention is SOURCE.

The decompiled code of the Override.class is:

package java.lang;
import java.lang.annotation.Annotation;
// Referenced classes of package java.lang:
// Object

public interface Override extends Annotation {
}


This is applicable to all annotations that you may come across in various frameworks/tools. All annotations in Spring, Hibernate, JPA are backed by corresponding classes. If you decompile the code which makes use of annotations, you will not see any reference to annotation classes as the dependency with annotations is resolved at compile time only. Thus annotations are Meta-data for the compiler which it makes use of to perform common functions for developers thus easing the life of a Java application developer.

About Daemon Threads in Java

There can be two types of threads in Java viz User Thread and Daemon Thread. All the threads created by a user are user threads. A thread becomes Daemon thread when the user says so. User threads are meant for the program code.

On the other hand Daemon threads are service provider threads. They should not be used to run your program code but some system code. The run() method for a daemon thread is typically an infinite loop that waits for a service request. These threads run in parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon threads are terminated instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread : Java garbage collector. The Garbage collector runs as a low priority daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly. 

Daemon threads are typically used to perform services for your application/applet. The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution. Use daemons as the minions they are. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

To specify that a thread is a daemon thread, call the setDaemon() method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon().

Exception chaining in java

In this tutorial we’ll discuss about exception chaining, which may be new term to few java EE developers.

Note: If at any time, you feel no need for such tutorial, execute the two programs in the post and learn what exception chaining is all about.

The most important thing to remember about Exception chaining is that we need to use the constructor of the exception classes which accepts a parameter of type Throwable so that it can keep a reference to the exception which was the cause of this exception.

Definition of Exception Chaining:

The definition of chained exceptions is that when the occurrence of one exception raises another exception then the stack trace of second exception should also include the root exception in the application logs.

Few points to remember about Chained Exceptions are:

1) Java does magic in order to support Exception Chaining but it is also the responsibility of the developer to have proper exception chaining mechanism in place in any Java based application. The application needs to be coded so as to support exception chaining.

2) If the developer doesn't take any action to have chained exception in his program, the root exceptions are lost. No exception chaining code, no chained exceptions seen.

3) Chained exceptions are different from the stack trace that we see when an exception occurs which prints the method names which we were invoked before the exception was thrown (in other words, the method stack trace)

4) Exception Chaining is internally supported by Java by storing a reference to the root exception has a member field cause which was added in JDK 1.4 and looks like:

private Throwable cause = this; (inside Throwable.java class)

5) The methods which are provided by Java in order to only support exception chaining are

Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
Throwable printStackTrace();

The basic and important point to keep in mind about chained exception is that we need to write a custom exception class which can accept an argument of type Throwable in is constructor and can invoke the super class's constructor with the parameters passed to its constructor. This will become more clear with two examples:

Without any Exception Chaining mechanism in place:


package com.vaani.exception.notchained
class MyException extends Exception { //Custom Exception class
public MyException (String msg) {
super(msg);
}
}

public class Test {

static int a[] = {1,2,3};

public static void main(String[] args) {

try {
System.out.println(a[4]); //Deliberate ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException ae) {
try {
throw new MyException("Exception Occured"); //throw custom exception
} catch (MyException me) {
me.printStackTrace();
}
}
}
}

Output:
com.vaani.exception.notchained.MyException: Exception Occured
at com.example.Test.main(Test.java:20)


With Exception Chaining mechanism in place:


package com.vaani.exception.chained;

class MyException extends Exception { //Custom Exception class
public MyException (String msg, Throwable ex) {
super(msg, ex);
}
}

public class Test {

static int a[] = {1,2,3};

public static void main(String[] args) {

try {
System.out.println(a[4]); //Deliberate ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException ae) {
try {
throw new MyException("Exception Occured",ae); //throw custom exception
} catch (MyException me) {
me.printStackTrace();
}
}
}
}

Output:

com.vaani.exception.chained.MyException: Exception Occured
at com.example.Test.main(Test.java:19)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 4
at com.example.Test.main(Test.java:16)


Please note that the use of custom exception in above examples is for demonstration only. It could be any JDK exception class like IllegalArgumentException, ClassNotFoundException or IllegalStateException.

Sorting an array using selection sort (java)

public static void main (String [] args) {
int n;
Scanner sc = new Scanner (System.in);
System.out.print ("Enter how many elements");
n = sc.nextInt();
int [] a = new int [n];

//input array
for (int i=0; i<n; i++){
System.out.print("Enter element " +(i+1) + " ");
a[i] = sc.nextInt();
}

//sorting
for (int i=0; i<n-1; i++) {
for (int j=i+1; j<n; i++) {
if(a[i]>a[j]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}

//output
for (int i=0; i<n; i++){
System.out.println(a[i]);
}

}

Finding smallest and largest number in an array (java)

public static void main(String[] args) {

int[] numbers = new int[10];
int x = 0;
int max,min ;
while (x < numbers.length) {
int random = (int) (Math.random() * 10);
numbers[x] = random;
x = x + 1;
}
x = 0;
while (x <numbers.length) {
System.out.println("Value of numbers[" +x+ "] is " +numbers[x]);
x = x + 1;
}

max = numbers[0];
min = numbers[0];
for (x=0;x<numbers.length;x++){
if(numbers[x]>max){
max=numbers[x];
}
else if(numbers[x]<min){
min=numbers[x];
}

}
System.out.println("Largest number is " +max);
System.out.println("Smallest number is " +min);


}

Factorial in java

Factorial of number using iteration

public int factorial(int var) {
if ((var) > 1) {
fact = var * factorial(var - 1);
return fact;
}

else {
return 1;
}
}


 

Factorial of number using recursion


public int factorial(int var) {
if ((var) > 1) {
fact = var * factorial(var - 1);
return fact;
}

else {
return 1;
}

Multiplying 2 matrices in java

See following code:

//Input number rows and columns in 2 matrices
Scanner sc = new Scanner (System.in);
int r1,c1;
System.out.print("Enter how many rows");
r1 = sc.nextInt();
System.out.print("Enter how many cols");
c1 = sc.nextInt();
int r2,c2;
System.out.print("Enter how many rows");
r2 = sc.nextInt();
System.out.print("Enter how many cols");
c2 = sc.nextInt();
if(c1 != r2){
System.out.println("Can't mult");
System.exit(1);
}
int m1[][] = new int[r1][c1];

//input m1
for (int i=0; i<r1; i++){
for (int j=0; j<c1; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m1[i][j] = sc.nextInt();
}
}

int m2[][] = new int[r2][c2];

//input m2
for (int i=0; i<r2; i++){
for (int j=0; j<c2; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m2[i][j] = sc.nextInt();
}
}

int m3[][] = new int[r2][c2];

//Matrix multiplication
for (int i=0; i<r1; i++){
for (int j=0; j<c2; j++){
for (int k=0; k<c1; k++){
m3[i][j]+=m1[i][k]*m2[k][j];
}
}
}

//Output m3
for (int p=0; p<r1; p++){
for (int j=0; j<c2; j++){
System.out.print(m3[p][j]+"\t");
}
System.out.println();

}

How to convert a String array to ArrayList?

Method 1:

String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);


Method 2:


List<String> list = new ArrayList<String>(words.length);
for (String s : words) {
list.add(s);
}



Method 3 :


Collections.addAll(myList, myStringArray);


Note: In the method no 1 Arrays.asList() is efficient because it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array - a wrapper that makes the array look like a list. When you change an element in the list, the element in the original array is also changed. Note that the list is fixed size - if you try to add elements to the list, you'll get an exception.



If you only need read access to the array as if it is a List and you don't want to add or remove elements from the list, then only use method no 1.

Immutable Objects / Wrapper Class Caching

Since Java 5, wrapper class caching was introduced.
The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10; or Integer myNumber = Integer.valueOf(10);

256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:
private static class IntegerCache 
{
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static
{
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}

public static Integer valueOf(int i)
{
final int offset = 128;
if (i >= -128 && i <= 127) // must cache
{
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}


So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:

Integer i = 100;
Integer p = 100;
if (i == p)
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");
if(i.equals(p))
System.out.println("i and p contain the same value.");

The output is:
i and p are the same.
i and p contain the same value.


So this result is similar to the result as shown here for strings.

It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching. So consider the following example:

Integer i = new Integer (100);
Integer p = new Integer(100);
if(i==p)
System.out.println(“i and p are the same object”);
if(i.equals(p))
System.out.println(“ i and p contain the same value”);


In this circumstance, the output is only: i and p contain the same value

The other wrapper classes (Byte, Short, Long, Character) also contain this caching mechanism OR constant pooling mechanism. The Byte, Short and Long all contain the same caching principle to the Integer object. The Character class caches from 0 to 127. The negative cache is not created for the Character wrapper as these values do not represent a corresponding character. There is no caching for the Float object.

BigDecimal also uses caching but uses a different mechanism. While the other objects contain a inner class to deal with caching this is not true for BigDecimal, the caching is pre-defined in a static array and only covers 11 numbers, 0 to 10:

 
// Cache of common small BigDecimal values.
private static final BigDecimal zeroThroughTen[] = {
new BigDecimal(BigInteger.ZERO, 0, 0),
new BigDecimal(BigInteger.ONE, 1, 0),
new BigDecimal(BigInteger.valueOf(2), 2, 0),
new BigDecimal(BigInteger.valueOf(3), 3, 0),
new BigDecimal(BigInteger.valueOf(4), 4, 0),
new BigDecimal(BigInteger.valueOf(5), 5, 0),
new BigDecimal(BigInteger.valueOf(6), 6, 0),
new BigDecimal(BigInteger.valueOf(7), 7, 0),
new BigDecimal(BigInteger.valueOf(8), 8, 0),
new BigDecimal(BigInteger.valueOf(9), 9, 0),
new BigDecimal(BigInteger.TEN, 10, 0),
};


As per Java Language Specification(JLS) the values discussed above are stored as immutable wrapper objects. This caching has been created because it is assumed these values / objects are used more frequently.

String equality and interning in java

Strings in Java are objects, but resemble primitives (such as ints or chars) in that Java source code may contain String literals, and Strings may be concatenated using the “+” operator. These are convenient features, but the similarity of Strings to primitives sometimes causes confusion when Strings are compared.

As we saw here, how java deals with string comparisons. Lets understand the case 2, where == operator returns true for 2 different references having same values.
To save memory (and speed up testing for equality), Java supports “interning” of Strings. When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. Otherwise, the String is added to the table and a reference to it is returned. The result is that after interning, all Strings with the same content will point to the same object. This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.

Confusion can arise because Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values. Code written based on this assumption will fail in a potentially non-obvious way when the == operator is used to compare Strings with equal content but contained in different String instances.
Following test cases show how interning can be performed by java:
Consider following string i.e “A String":
 
String aString = "A String"; 



Case 1: Concatenated string


String aConcatentatedString = "A" + " " + "String";


aString == aConcatentatedString       : true
aString.equals(aConcatentatedString) : true

Case 2: Runtime string




String aRuntimeString = new String("A String");


aString == aConcatentatedString       : false
aString.equals(aConcatentatedString) : true


Case 3: Interned string


String anInternedString = aRuntimeString.intern();

aString == aConcatentatedString : true
aString.equals(aConcatentatedString) : true



Case 4: External strings , eg. 1st argument of main method


String firstArg = args[0];


aString == aConcatentatedString : false
aString.equals(aConcatentatedString) : true


Case 5: Using intern on external strings


String firstArgInterned = firstArg.intern();

aString == aConcatentatedString : true
aString.equals(aConcatentatedString) : true




So we can see that explicitly invoking intern() returns a reference to the interned String.

Similar to string, there is a pool of integers, bytes, etc and other value based classes like bigdecimal. See here for more on this.

== vs equals method in case of String and primitive types

Object equality is tested using == operator. Here it is checked whether 2 references are pointing to same object or not.
While value equality is tested using the .equals(Object) method.
So consider following code snippet:
String one = new String("abc");
String two = new String("abc");


So here

one==two is false

one.equals(two) is true

one==two, because we are creating 2 new objects as specified by new keywords. But as their values are same one.equals(two) returns true because values are same.

Now if we say:

String three = one;



Now both one==two as well one.equals(two) returns true.

Using new keyword vs not using it to create 2 strings


Now consider 2 cases, when we create 2 strings with same value, but first using new keyword and then not using new keyword:

Case1 : Using new keyword:

String data = new String("123");
String moreData = new String("123");



Here data==moreData is false.

Case 2 : Not using new keyword:

String letters = "abc";
String moreLetters = "abc";


Here data==moreData is true.

Why?

Explaining the case 1 is very simple. Because it falls inline with our earlier explanation of == and != operators. But how can we explain case 2, where string comparison using == operator, returns true.

This is due to the compiler and runtime efficiency. In the compiled class file only one set of data "abc" is stored, not two. In this situation only one object is created, therefore the equality is true between these object. Read here for more on this. Not only strings , compiler also support this type of constant pooling for integers, bytes and other value types. See here for this.


Note:

Even though one set of data "123" is stored in the class, this is still treated differently at runtime. An explicit instantiation is used to create the String objects. Therefore, in this case, two objects have been created, so the equality is false. It is important to note that "==" is always used for object equality and does not ever refer to the values in an object. Always use .equals when checking looking for a "meaningful" comparison.

Value objects or VOs in java

//to be written soon

equals() for String, StringBuilder and StringBuffer

Rule of equality in java:

Equals method should be used for checking the logical equality of objects of a class but it does not mean that every class is a candidate for overridden equals method

So if you go and see the source code of StringBuffer/StringBuilder classes in Java, you will find that equals() method is not overridden but it is overridden in the String class.

public class Test{

public static void main (String args[]) {
String str1 = "abcd";
String str2 = "abcd";
System.out.println(str1.equals(str2));

StringBuffer sb1 = new StringBuffer(str1);
StringBuffer sb2 = new StringBuffer(str1);
System.out.println(sb1.equals(sb2));
}
}

Output:

true
false


For String objects, the logical equality would mean the contents of the string should be same.

For StringBuffer and StringBuilder we have following facts:
  • Logical equality means that both objects were configured and assembled using the same String instance and not whether the contents of those String objects is same.
  • The intended use of StringBuffer and StringBuilder is for maintaining a buffer of characters which may change with time.
Both the above statements contradict with each other because the String object being used for building a StringBuffer/StringBuilder object can change very frequently and it does not make any sense to compare the StringBuffer/StringBuilder objects.

This is the reason that the equals() method is not overridden in StringBuffer/StringBuilder classes.

It should be noted that there a misconception that is going around the developer community regarding the above reason which says that then why an ArrayList/Date overrides the equals() method as it too can change with time. Here are a few reasons to clear that thought which in fact is natural:
  • StringBuffer/StringBuilder classes are intended to be used as temporary buffer and change more frequently than classes like ArrayList and Date
  • While one may like to perform various operations like serialization, making clones, being used as keys in collections or stored in database but one is very unlikely to perform similar operations with StringBuffer/StringBuilder classes.
Also String may be treated as value object, where value equality means, object equality. Read here for more on value objects.


Online java compilers

What is common between Innovation.ch, youjavait.com, ideone.comcompilr.com and browxy.com?

If you are sitting on a machine on which Java is not installed and you can not even download Java because of some reason but you have internet connectivity then there is no one stopping you from compiling and testing your source code. There are many online compilers available on the internet which can be used to see the output of the code you have written.

Some of them are powerful and some are not. Here are some of them reviewed.

1) Innovation.ch:

Positives:
a) You can specify source files using the browse button
b) You can also specify the Jar files which are required for the compilation to complete
c) You can doenload the compiled .class files individually or download a zip/gz file containing all the classes.
d) The compiler interface can be extended by creating your own HTML page and calling the JXXX compiler's cgi APIs.
e) The website can run the applets for you.
f) Supports JDK 1.5 and JDK 1.6
g) The source files can have packages.
h) There are multiple options availale to pass to the javac command.
i) Works with IE as well as Firefox.

Negatives:
a) A maximum of 5 source and 5 jar files can be specified in one go.
b) The source files should have ASCII text only.
c) You can not browse a folder to compile all the source files under the folder.

2) youjavait.com:

Positives:
a) You can specify the program to use the server JDK or local JDK (JAVA_HOME needs to be set).
b) You can maintain multiple projects.
c) You can create multiple source files with built in syntax highlighter and then you can refer these source files as they are in the same package.
d) You can use Google/OpenID account for this website and store projects for later reference.
e) Compiles and runs the program and then displays the output.

Negatives:
a) Seems to run only on IE and not Firefox
b) There is only one default package named com and you can not create more packages.
c) You can not get the compiles .class files.

3) ideone.com:

Positives:
a) Works in Firefox also.
b) It has options for multiple programming languages.
c) You can run the code to view the output.
d) You have a built in syntax highlighter.

Negatives:
a) Though the source code is available for later viewing purpose, you can not get the .class files generated by the compiler.
b) Supports only JDK 1.6

4) browxy.com:

Seems to be not working in neither Firefox and nor IE. You can try your luck with this online Java compiler and Runner.

You can see these observations, but may be some changes they must have dist, after this blog.

Programming hells you can think off

Every approach has its pros and cons but when something becomes too difficult to handle and that to frequently, it becomes a hell for us.

So a hell is nothing but a problem that comes back to you without any fault from writing the code but because of using some methodology or standard.

The problems with various approaches become more painful when the application scales.

Here are some common hells. Probably you may like to add more to the list.
1) DLL Hell:
A kind of dependency hell where Windows can't locate a DLL when you start or use an application


http://en.wikipedia.org/wiki/DLL_hell


2) XML Hell:
You keep on adding XML's and at a later stage find it very difficult to maintain (Reason why annotations in EJB3 came up)
http://java.dzone.com/news/draft-spring-xml-hell

http://aspnetresources.com/blog/welcome_to_xml_hell


3) Jar Hell:
After all the classloader have run, the required dependent class in a particular jar has not been loaded.

Or

There are so many versions of Jar files released which confuses you about the right version of jar to use.



4) Meta Data Hell:
All those who have used annotations for hard coding various kind of stuff have felt this hell.


5) Redirect Hell:
This relates to extra processing by various websites before being actually shown the page being sought. Google, Yahoo, MSFT, Facebook, Twitter- all do such things and sometimes frustrate us.


6) Dependency Hell:
Have you ever installed a game and found that the version of DirectX you have is not compatible with the game. You need to download and install the proper version.

Inner Class Nested Levels In Java

How frequently does one see inner classes being used in an application leave aside inner classes at nested levels.
Yes one can have as many nested level of inner classes . The code below proves it.

However, the usability of this code is debatable.

public class Test{
    class a1{
        class a2{
            class a3{
                class a4{
                }
            }
        }
    }
   public static void main(String[] args) {
       Test.a1.a2.a3.a4 abc = new Test().new a1().new a3().new a4().new a6();
    }
}

Passing by reference doesn't swaps in java

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
Take the badSwap() method for example:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
public void badSwap2(Point arg1,Point arg2)
{
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}

The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.



Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.

But still it is not impossible to write swap. See here for this.

Writing a swap function in java

Method 1 : Changing the data underneath
public class Swapper<T> {
     
public Swapper(T obj) {
             data_
= obj;
     
}
     
public T get() { return data_; }
     
public void set(T value) { data_ = value; }
     
public void swap(Swapper<T> o) {
           T tmp
= o.data_;
           o
.data_ = data_;
           data_
= tmp;
     
}
     
private T data_ = null;
 
}

 
// .. Now you can do:
 
Swapper<String> a = new Swapper("Hello");
 
Swapper<String> b = new Swapper("World");
 
// a.get().equals("Hello")
  a
.swap(b); // now a.get().equals("World")


But we can write function which uses the above idea:
public void Swap(RefObject<Integer> p, RefObject<Integer> q)
{
   
int temp;
   temp
= p.argvalue;
   p
.argvalue = q.argvalue;
   q
.argvalue = temp;
}
public final class RefObject<T>
{
   
public T argvalue;
   
public RefObject(T refarg)
   
{
        argvalue
= refarg;
   
}
}


Method 2 : Using Atomic reference
Example for integers:

public void swap(AtomicInteger a, AtomicInteger b){
   
  a.set(b.getAndSet(a.get()));
}
  

Above method can be written in more verbose way like this:

import java.util.concurrent.atomic.AtomicInteger;
public class TestAtomicInteger{
   
private static void swap(AtomicInteger a, AtomicInteger b) {
       
int val = a.get();
        a
.set(b.get());
        b
.set(val);
   
}

   
public static void main(String[] args) {
       
AtomicInteger a = new AtomicInteger(1);
       
AtomicInteger b = new AtomicInteger(2);

        swap
(a, b);

       
System.out.println("a: " + a + " b: " + b);
   
}
}

Example for strings:
public void swap(AtomicReference a, AtomicReference b){
        a.set(b.getAndSet(a.get()));
}


Of course this not very satisfactory, as you hardly ever develop against AtomicReferences. But basically you need to use some kind of container as shown above, because you can't just swap the references. So you can e.g. swap the elements of a two-element array or list, but you just can't swap two strings without having access to the original variables (so you can't do it in a helper function).

Case when data is in list:
If your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int).
In above function following are the function and parameters:

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged
.)
Parameters:
    list
- The list in which to swap elements.
    i
- the index of one element to be swapped.
    j
- the index of the other element to be swapped.

Case when swap is required in sorting:
apparently the real objective is to sort an array of ints. That's a one-liner with Arrays.sort(int[]):

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

To check the output:
   System.out.println(Arrays.toString(arr));
   // [1, 2, 3, 19, 25, 378]

And here is a simple helper function to swap two positions in an array of ints:

public static void swap(final int[] arr, final int pos1, final int pos2){
   final int temp = arr[pos1];
   arr[pos1] = arr[pos2];
   arr[pos2] = temp;
}

Best Way to Swap Values in Java

Though not all Java applications require variables to be swapped, but those which do require are not given proper thoughts about correct and optimized implementation.


Method-1: Using temporary Variable

The most common way to swap two values is by using a temporary variable as shown below:

int a=10,b=5,c;
c=a; (c=10,a=10,b=5)
a=b; (c=10,a=5,b=5)
b=c; (c=10,a=5,b=10)

If the use of temporary variable c is not allowed, then we have the following two options:

Method-2.1 : Using the addition and subtraction operations
int a=10,b=5;
a=a+b;
b=a-b;
a=a-b

The problem with the above solution is that the addition and subtraction can cause overflows. An overflow is a condition when the value of a variable is increased/decreased beyond the maximum/minimum value of that variable. Though the output of such a program may show that the variables have been swapped but it is not guaranteed as per Specification of various programming languages including Java.

package com.vaani.swap.subtraction;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a + b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a - b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = a - b;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}

Output:
After operation 1, a =  -394967298 b = 1899999999
After operation 2, a =  -394967298 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

Method-3: Using the XOR operator

The XOR operator can also be used swap two variables using the logic shown below:

int a=10,b=5;
a=a^b;
b=a^b;
a=a^b

Thank you