JavaNo Comments

default thumbnail

Given two variables first one is str and second is str1 swapping these variables without third variable.

In using the substring method of String and user enter input using Scanner.

String swapping without third variable in java

import java.util.Scanner;
class str
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println(” Enter first word “);
String str=sc.nextLine();
System.out.println(” Enter Second word “);
String str1=sc.nextLine();
str=str+str1;
str1 =str.substring(0,str.length()-str1.length());
str=str.substring(str1.length(),str.length());
System.out.println(str + ” ” + str1);
}
}

Be the first to post a comment.

Add a comment