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
2 Likes
Related Questions
Consider the following Java class and answer the questions given below:
class Rectangle { int length, breadth; Rectangle() { length = 5; breadth = 3; } Rectangle(int l, int b) { length = l; breadth = b; } void area() { System.out.println("Area: " + (length * breadth)); } public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(8, 4); r1.area(); r2.area(); } }
(a) Name the type of constructors used in the above class.
(b) What is the output of the method main()?
Assertion (A): The default constructor initializes object fields to zero or null depending on their data type.
Reason (R): Java constructors are inherently tied to the initialization of an object and therefore do not specify a return type.
Fill in the blanks:
A _________ constructor creates objects by passing value to it.
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()?