Binary Addition
String input0 = "1";
String input1 = "1";
int number0 = Integer.parseInt(input0, 2);
int number1 = Integer.parseInt(input1, 2);
int sum = number0 + number1;
System.out.println(Integer.toBinaryString(sum));
import java.util.concurrent.atomic.AtomicInteger;
public class PassByReference {
public static void changeAtomicInteger(AtomicInteger n) {
System.out.println("In changeAtomicInteger method");
System.out.println("\tBefore change: n = " +
n + // prints 5
" hash code = " +
n.hashCode());
n.set(n.get() + 10); // at this point, we are clearly working with reference data type
System.out.println("\tAfter change: n = " +
n + // prints 15
" hash code = " +
n.hashCode());
}
public static void main(String[] args) {
AtomicInteger n = new AtomicInteger(5); // unlike conventional wrapper class, this requires new
System.out.println("Main method before changeAtomicInteger(n): n = " +
n + // prints 5
" hash code = " +
n.hashCode());
changeAtomicInteger(n);
System.out.println("Main method after changeAtomicInteger(n): n = " +
n + // now prints 15
" hash code = " +
n.hashCode());
}
}
PassByReference.main(null);
public class IntByReference {
private int value;
public IntByReference(Integer value) {
this.value = value;
}
public String toString() {
return (String.format("%d", this.value));
}
public void swapToLowHighOrder(IntByReference i) {
if (this.value > i.value) {
int tmp = this.value;
this.value = i.value;
i.value = tmp;
}
}
public static void swapper(int n0, int n1) {
IntByReference a = new IntByReference(n0);
IntByReference b = new IntByReference(n1);
System.out.println("Before: " + a + " " + b);
a.swapToLowHighOrder(b); // conditionally build swap method to change values of a, b
System.out.println("After: " + a + " " + b);
System.out.println();
}
public static void main(String[] ags) {
IntByReference.swapper(21, 16);
IntByReference.swapper(16, 21);
IntByReference.swapper(16, -1);
}
}
IntByReference.main(null);