Computer Applications
Write a program in java to input any two variables through constructor parameters and swap and print their values.
Java
Java Constructors
1 Like
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
![BlueJ output of Write a program in java to input any two variables through constructor parameters and swap and print their values. BlueJ output of Write a program in java to input any two variables through constructor parameters and swap and print their values.](https://cdn1.knowledgeboat.com/img/java-programs/KboatSwap-p1-1.jpg)
Answered By
1 Like
Related Questions
State whether the following statement is True or False :
Every class must have all types of constructors.
What is meant by a constructor?
Fill in the blanks:
The _________ refers to the current object.
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()?