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
Write a program in Java to find the roots of a quadratic equation ax2+bx+c=0 with the following specifications:
Class name — Quad
Data Members — float a,b,c,d (a,b,c are the co-efficients & d is the discriminant), r1 and r2 are the roots of the equation.
Member Methods:
- quad(int x,int y,int z) — to initialize a=x, b=y, c=z, d=0
- void calculate() — Find d=b2-4ac
If d < 0 then print "Roots not possible" otherwise find and print:
r1 = (-b + √d) / 2a
r2 = (-b - √d) / 2aConsider 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()?
What is meant by a constructor?
Fill in the blanks:
A _________ constructor creates objects by passing value to it.