Java Interview Question

Q1.Write a Program to swap two numbers in Java

Write a Program to swap two numbers in Java using a third variable

JavaInterview-Question Q1.Write a Program to swap two numbers in Java

Example :

Let’s Swap: Numbers 1 and 2  
Let x= 1, y= 2  
Swapping Logic:  
take a temp variable =temp
temp=x=1;
x=y=2;
y=temp=1
After swapping:  
x= 2, y = 1

Java Coda

import java.util.*;
public class SwapWith3number {
	public static void main(String[] args) {
		int x,y,temp;
		System.out.println("Enter value of x and y");
		Scanner in=new Scanner(System.in);
		x=in.nextInt();
		y=in.nextInt();
		System.out.println("Before Swapping\n x= "+ x);
		System.out.println(" y= "+ y);
		temp=x;
		x=y;
		y=temp;
		System.out.println("After  Swapping\n x= "+ x);
		System.out.println(" y= "+ y);
	}
}

Algorithm

STEP 1: START
STEP 2: DEFINE x, y, temp
STEP 3: ENTER x, y
STEP 4: PRINT x, y
STEP 5: temp= x
STEP 6: x= y
STEP 7: y= temp
STEP 8: PRINT x, y
STEP 9: END

maxresdefault Q1.Write a Program to swap two numbers in Java

Q2.Write a Program to swap two numbers Without the Third number in Java

Example :

Let’s Swap: Numbers 1 and 2  
Let x= 1, y= 2  
Swapping Logic:  
x=x+y;
y=x-y;
x=x-y;
After swapping:  
x= 2, y = 1

Java Coda

import java.util.*;
public class SwapWith3number {

	public static void main(String[] args) {
		int x,y;
		System.out.println("Enter value of x and y");
		Scanner in=new Scanner(System.in);
		x=in.nextInt();
		y=in.nextInt();
		System.out.println("Before Swapping\n x= "+ x);
		System.out.println(" y= "+ y);
        x=x+y;
        y=x-y;
        x=x-y;
		System.out.println("After  Swapping\n x= "+ x);
		System.out.println(" y= "+ y);
	}
	
}

Algorithm

STEP 1: START
STEP 2: DEFINE x, y
STEP 3: ENTER x, y
STEP 4: PRINT x, y
STEP 5: x=x+y;
STEP 6: y=x-y;
STEP 7: x=x-y;
STEP 8: PRINT x, y
STEP 9: END


What is Java? 

In 1982, James Gosling created the high-level programming language known as Java. It may be used to create complex programs and is based on the ideas of object-oriented programming.

All of the frequently asked Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, Collections interview questions, and some frequently asked Java coding interview questions will all be covered in the ensuing article.

See also  How to build an AI System Step-By-Step Guide [ Create an Ai ]

To improve your chances of succeeding in the interviews, go over all the questions. The questions will center on the principles of Java at the basic, core, and advanced levels.

Post Comment