Computer Applications
Write a program in java to input any two variables through constructor parameters and swap and print their values.
Answer
import java.util.Scanner;
public class KboatSwap {
int a;
int b;
public KboatSwap(int x, int y) {
a = x;
b = y;
}
public void swap() {
int t = a;
a = b;
b = t;
}
public void display() {
System.out.println("a=" + a);
System.out.println("b=" + b);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int p = in.nextInt();
System.out.print("Enter second number: ");
int q = in.nextInt();
KboatSwap obj = new KboatSwap(p, q);
System.out.println("Values before swap:");
obj.display();
obj.swap();
System.out.println("Values after swap:");
obj.display();
}
}
Output
Related Questions
Consider the given program and answer the questions given below:
class temp { int a; temp() { a=10; } temp(int z) { a=z; } void print() { System.out.println(a); } void main() { temp t = new temp(); temp x = new temp(30); t.print(); x.print(); } }
(a) What concept of OOPs is depicted in the above program with two constructors?
(b) What is the output of the method main()?
Fill in the blanks:
A constructor has return _________ type.
State whether the following statement is True or False :
Every class must have all types of constructors.
Fill in the blanks:
The _________ refers to the current object.