top 20 java interview programs
이 튜토리얼에서는 신입생과 경험이 많은 후보자를 위해 프로그래밍 및 코딩 인터뷰에서 요청한 실제 논리 코드 예제와 함께 기본 Java 인터뷰 프로그램의 큰 목록을 제공했습니다.
Java 및 자동화 인터뷰의 기술 라운드에서 일반적으로 요청되는 중요하고 기본적인 Java 프로그램입니다.
이것은 이제 이론적 측면에 초점을 맞추지 않고 인터뷰에서 기본적인 Java 프로그램을 묻는 면접관의 일반적인 관행이되었습니다.
이를 위해 우리는 각 프로그램에 대한 적절한 설명과 함께 몇 가지 매우 중요한 Java 프로그램을 나열하는 아이디어를 생각해 냈습니다.
또한 해당 프로그램의 작동 방식에 대한 공정한 아이디어를 제공 할 각 출력도 포함했습니다. 프로그램의 흐름과 개념은이 기사 전체에서 가능한 한 적절하게 설명됩니다.
가장 인기있는 자바 프로그래밍 인터뷰 질문
가장 인기있는 Java 프로그래밍 인터뷰 질문 및 답변 목록이 아래에 설명되어 있으며 이러한 질문은 자동화 인터뷰를 성공적으로 완료하는 데 도움이됩니다.
권장 읽기 => 우리는 핵심 자바 인터뷰 질문 여기 이전 기사에서.
Q # 1) 문자열 내장 함수를 사용하지 않고 문자열을 뒤집는 Java 프로그램을 작성하십시오.
대답: 여기서는 문자열 변수 str을 초기화하고 문자열 빌더 클래스를 사용합니다.
문자열 작성기 클래스 str2의 객체는 문자열 변수 str에 저장된 값을 추가하는 데 추가로 사용됩니다.
그 후, 우리는 문자열 작성기 (reverse ())의 내장 함수를 사용하고 str2에 새로운 반전 된 문자열을 저장합니다. 마지막으로 str2를 인쇄합니다.
다음 프로그램 코드는이를 설명합니다.
public class FinalReverseWithoutUsingStringMethods { public static void main(String() args) { // TODO Auto-generated method stub String str = 'Automation'; StringBuilder str2 = new StringBuilder(); str2.append(str); str2 = str2.reverse(); // used string builder to reverse System.out.println(str2); } }
산출:
noitamotuA
Q # 2) String inbuilt function reverse ()를 사용하지 않고 문자열을 뒤집는 Java 프로그램을 작성하십시오.
대답: 다른 문자열 내장 함수를 사용할 수있는 경우 문자열을 뒤집을 수있는 여러 가지 방법이 있습니다.
방법 1 :
이 방법에서는 주어진 문자열의 값으로 str이라는 문자열 변수를 초기화합니다. 그런 다음 toCharArray () 함수를 사용하여 해당 문자열을 문자 배열로 변환합니다. 그 후 for 루프를 사용하여 각 문자를 역순으로 반복하고 각 문자를 인쇄합니다.
public class FinalReverseWithoutUsingInbuiltFunction { public static void main(String() args) { String str = 'Saket Saurav'; char chars() = str.toCharArray(); // converted to character array and printed in reverse order for(int i= chars.length-1; i>=0; i--) { System.out.print(chars(i)); } } }
산출:
예비 재고
방법 2 :
이것은 문자열 변수 str을 선언 한 다음 Scanner 클래스를 사용하여 미리 정의 된 표준 입력 개체로 개체를 선언하는 또 다른 방법입니다.
이 프로그램은 명령 줄을 통해 문자열 값을받습니다 (실행시).
문자열의 단어 사이에 공백이있는 입력을 읽는 nextLine ()을 사용했습니다. 그 후 split () 메서드를 사용하여 문자열을 하위 문자열로 분할했습니다 (여기에는 구분 기호 없음). 마지막으로 for 루프를 사용하여 문자열을 역순으로 인쇄했습니다.
import java.util.Scanner; public class ReverseSplit { public static void main(String() args) { // TODO Auto-generated method stub String str; Scanner in = new Scanner(System.in); System.out.println('Enter your String'); str = in.nextLine(); String() token = str.split(''); //used split method to print in reverse order for(int i=token.length-1; i>=0; i--) { System.out.print(token(i) + ''); } } }
산출:
문자열 입력
소프트웨어 테스트 도움말
plehgnitseterawtfoS
방법 3 :
이것은 방법 2와 거의 비슷하지만 여기서는 split () 메서드를 사용하지 않았습니다. 입력 문자열을 읽기 위해 scanner 클래스와 nextLine ()을 사용했습니다. 그런 다음 입력 문자열의 길이를 갖는 정수 길이를 선언했습니다.
그 후 for 루프를 사용하여 문자열을 역순으로 인쇄했습니다. 그러나 특정 인덱스에서 문자를 반환하는 charAt (index) 메서드를 사용했습니다. 각 반복 후에 문자가 연결되어 문자열 변수를 반전합니다.
마지막으로 역방향 문자열 변수를 인쇄했습니다.
import java.util.Scanner; public class Reverse { public static void main(String() args) { // TODO Auto-generated method stub String original, reverse = ''; System.out.println('Enter the string to be reversed'); Scanner in = new Scanner(System.in); original = in.nextLine(); int length = original.length(); for(int i=length-1; i>=0; i--) { reverse = reverse + original.charAt(i); //used inbuilt method charAt() to reverse the string } System.out.println(reverse); } }
산출:
되돌릴 문자열을 입력하십시오.
자동화 테스트
gnitset noitamotua
애니메이션을 온라인으로 볼 수있는 최고의 장소
질문 # 3) 세 번째 변수를 사용하여 두 숫자를 교환하는 Java 프로그램을 작성하십시오.
대답: 이 예제에서는 Scanner 클래스를 사용하여 미리 정의 된 표준 입력 개체가있는 개체를 선언했습니다. 이 프로그램은 명령 줄 (실행시)을 통해 x 및 y 값을 허용합니다.
사용자로부터 정수 변수‘x’와‘y’의 값을 입력하는 nextInt ()를 사용했습니다. 임시 변수도 선언됩니다.
이제 프로그램의 논리는 다음과 같습니다. temp 또는 세 번째 변수에 x 값을 할당 한 다음 x에 y 값을 할당하고 y에 temp 값을 다시 할당합니다. 따라서 첫 번째 완전한 반복 후에 temp는 x 값을 가지며 x는 y 값을 가지며 y는 temp 값 (x)을 갖습니다.
import java.util.Scanner; public class SwapTwoNumbers { public static void main(String() args) { // TODO Auto-generated method stub int x, y, temp; System.out.println('Enter x and y'); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println('Before Swapping' + x + y); temp = x; x = y; y = temp; System.out.println('After Swapping' + x + y); } }
산출:
x와 y 입력
오분의 사
98
교체하기 전에 4598
교체 후 9845
질문 # 4) 세 번째 변수를 사용하지 않고 두 숫자를 교환하는 Java 프로그램을 작성하십시오.
대답: 휴식은 위의 프로그램과 동일합니다. 논리 만 변경됩니다. 여기에서 x에 x + y 값을 할당합니다. 이는 x가 x와 y의 합계를 가짐을 의미합니다.
그런 다음 y에 x – y 값을 할당합니다. 이는 (x + y)의 합에서 y 값을 뺀다는 의미입니다. 여기까지 x는 여전히 x와 y의 합을가집니다. 그러나 y는 x의 값을 갖습니다.
마지막으로 세 번째 단계에서 x에 x-y 값을 할당합니다. 이는 합계 (x + y)에서 y (x 값)를 뺀다는 의미입니다. 이것은 x에 y의 값을 할당하고 그 반대의 경우도 마찬가지입니다.
import java.util.Scanner; class SwapTwoNumberWithoutThirdVariable { public static void main(String args()) { int x, y; System.out.println('Enter x and y'); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println('Before Swapping
x = '+x+'
y = '+y); x = x + y; y = x - y; x = x - y; System.out.println('After Swapping without third variable
x = '+x+'
y = '+y); } }
산출:
x와 y 입력
오분의 사
98
교환 전
x = 45
y = 98
세 번째 변수없이 스와핑 후
x = 98
y = 45
질문 # 5) HashMap을 사용하여 문자열의 단어 수를 계산하는 Java 프로그램을 작성하십시오.
대답: 이것은 문자열을 저장하기 위해 HashMap을 사용한 컬렉션 클래스 프로그램입니다.
먼저 str이라는 문자열 변수를 선언했습니다. 그런 다음 단일 공백으로 구분 된 split () 함수를 사용하여 문자열에서 여러 단어를 분할 할 수 있습니다.
그 후 HashMap을 선언하고 for 루프를 사용하여 반복했습니다. for 루프 내부에는 특정 위치의지도에 키가 포함되어있는 if-else 문이 있습니다. 해당 위치에 카운터를 설정하고 객체를지도에 추가합니다.
카운터는 매번 1 씩 증가합니다. 그렇지 않으면 카운터는 1로 설정됩니다.
마지막으로 HashMap을 인쇄합니다.
노트 : 동일한 프로그램을 사용하여 문자열의 문자 수를 계산할 수 있습니다. 여러분이해야 할 일은 String ()에서 하나의 공백을 제거하는 것입니다 (split 메서드에서 구분 된 공백을 제거하는 것). split = str.split (“”);
품질 분석가 인터뷰 질문 및 답변 pdf
import java.util.HashMap; public class FinalCountWords { public static void main(String() args) { // TODO Auto-generated method stub String str = 'This this is is done by Saket Saket'; String() split = str.split(' '); HashMap map = new HashMap(); for (int i=0; i 산출:
{Saket = 2, by = 1, this = 1, This = 1, is = 2, done = 1}
문 # 6) While 및 advance for 루프를 사용하여 HashMap을 반복하는 Java 프로그램을 작성하십시오.
대답: 여기에서는 put () 함수를 사용하여 HashMap에 세 가지 요소를 삽입했습니다.
지도의 크기는 size () 메서드를 사용하여 얻을 수 있습니다. 그 후, 우리는 각 요소에 대해 하나의 키-값 쌍을 포함하는 맵을 반복하기 위해 While 루프를 사용했습니다. 키와 값은 getKey () 및 getValue ()를 통해 검색 할 수 있습니다.
마찬가지로, HashMap에 대한 'me2'객체가있는 고급 for 루프를 사용했습니다.
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIteration { public static void main(String() args) { // TODO Auto-generated method stub HashMap map = new HashMap (); map.put(2, 'Saket'); map.put(25, 'Saurav'); map.put(12, 'HashMap'); System.out.println(map.size()); System.out.println('While Loop:'); Iterator itr = map.entrySet().iterator(); while(itr.hasNext()) { Map.Entry me = (Map.Entry) itr.next(); System.out.println('Key is ' + me.getKey() + ' Value is ' + me.getValue()); } System.out.println('For Loop:'); for(Map.Entry me2: map.entrySet()) { System.out.println('Key is: ' + me2.getKey() + ' Value is: ' + me2.getValue()); } } }
산출:
삼
While 루프 :
키는 2입니다. 값은 Saket입니다.
키는 25입니다. 값은 Saurav입니다.
키는 12입니다. 값은 HashMap입니다.
For 루프 :
키 : 2 값 : Saket
키 : 25 값 : Saurav
키 : 12 값 : HashMap
문 # 7) 숫자가 소수인지 아닌지를 찾기 위해 Java 프로그램을 작성하십시오.
대답: 여기서 우리는 temp와 num 두 개의 정수를 선언했고 nextInt와 함께 Scanner 클래스를 사용했습니다.
하나의 부울 변수 isPrime이 true로 설정됩니다. 그 후, 우리는 2부터 시작하는 for 루프를 사용했는데, 숫자의 절반 미만이 입력되고 각 반복마다 1 씩 증가합니다. Temp는 모든 반복에 대해 나머지를 갖습니다. 나머지가 0이면 isPrime이 False로 설정됩니다.
isPrime 값을 기반으로 숫자가 소수인지 아닌지에 대한 결론에 도달합니다.
import java.util.Scanner; public class Prime { public static void main(String() args) { // TODO Auto-generated method stub int temp, num; boolean isPrime = true; Scanner in = new Scanner(System.in); num = in.nextInt(); in.close(); for (int i = 2; i<= num/2; i++) { temp = num%i; if (temp == 0) { isPrime = false; break; } } if(isPrime) System.out.println(num + 'number is prime'); else System.out.println(num + 'number is not a prime'); } }
산출:
445
445 숫자가 소수가 아닙니다.
질문 # 8) 문자열이나 숫자가 회문인지 아닌지를 찾는 Java 프로그램을 작성하십시오.
대답: 위에서 설명한 역 문자열 프로그램을 사용하여 숫자 또는 문자열이 회문인지 여부를 확인할 수 있습니다.
해야 할 일은 하나의 if-else 문을 포함하는 것입니다. 원래 문자열이 반전 된 문자열과 같으면 숫자는 회문이고 그렇지 않으면 그렇지 않습니다.
import java.util.Scanner; public class Palindrome { public static void main (String() args) { String original, reverse = ''; Scanner in = new Scanner(System.in); int length; System.out.println('Enter the number or String'); original = in.nextLine(); length = original.length(); for (int i =length -1; i>;=0; i--) { reverse = reverse + original.charAt(i); } System.out.println('reverse is:' +reverse); if(original.equals(reverse)) System.out.println('The number is palindrome'); else System.out.println('The number is not a palindrome'); } }
산출:
문자열 용
숫자 또는 문자열 입력
비제이
반대는 : yajiv
번호는 회문이 아닙니다
번호
숫자 또는 문자열 입력
99
반대는 : 99
번호는 회문입니다
문 # 9) 피보나치 시리즈를위한 자바 프로그램을 작성하십시오.
대답: 피보나치 수열은 처음 두 수 뒤에 나오는 모든 수가 앞의 두 수의 합인 일련의 수입니다.
예를 들어 0,1,1,2,3,5,8,13,21 ………
이 프로그램에서 우리는 nextInt와 함께 Scanner 클래스를 다시 사용했습니다 (위에서 논의). 처음에는 (명령 줄을 통해) 피보나치가 반복해야하는 횟수를 입력합니다. 정수 num을 선언하고 a, b를 0으로, c를 1로 초기화했습니다. 그런 다음 for 루프를 사용하여 반복했습니다.
논리는 a가 0 인 b의 값으로 설정되고 b는 1 인 c의 값으로 설정되는 것과 같습니다. 그런 다음 c는 a와 b의 합으로 설정됩니다.
import java.util.Scanner; public class Fibonacci { public static void main(String() args) { int num, a = 0,b=0, c =1; Scanner in = new Scanner(System.in); System.out.println('Enter the number of times'); num = in.nextInt(); System.out.println('Fibonacci Series of the number is:'); for (int i=0; i 산출:
횟수 입력
10
피보나치 수열은 다음과 같습니다.
0
하나
하나
두
삼
5
8
13
이십 일
3. 4
질문 # 10) for-loop, while-loop 및 advance for-loop를 사용하여 ArrayList를 반복하는 Java 프로그램을 작성하십시오.
대답: 이 프로그램에서는 세 개의 요소를 삽입하고 ArrayList의 크기를 인쇄했습니다.
그런 다음 반복기와 함께 While 루프를 사용했습니다. 반복기에 (다음) 요소가있을 때마다 목록의 끝에 도달 할 때까지 해당 요소를 표시합니다. 따라서 세 번 반복됩니다.
마찬가지로, 우리는 list라는 ArrayList에 대해 obj라는 객체를 생성 한 Advanced For Loop에 대해 수행했습니다. 그런 다음 개체를 인쇄했습니다.
그런 다음 반복기 i가 0 인덱스로 설정된 For 루프의 조건을 설정 한 다음 ArrayList 제한 또는 크기에 도달 할 때까지 1 씩 증가합니다. 마지막으로 For 루프의 각 반복에 대해 get (index) 메서드를 사용하여 각 요소를 인쇄했습니다.
import java.util.*; public class arrayList { public static void main(String() args) { ArrayList list = new ArrayList(); list.add('20'); list.add('30'); list.add('40'); System.out.println(list.size()); System.out.println('While Loop:'); Iterator itr = list.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } System.out.println('Advanced For Loop:'); for(Object obj : list) { System.out.println(obj); } System.out.println('For Loop:'); for(int i=0; i 산출:
삼
While 루프 :
스물
30
40
고급 For 루프 :
스물
30
40
For 루프 :
스물
30
40
문 # 11) 명시 적 대기 조건 검사를 보여주는 Java 프로그램을 작성하십시오.
대답: 대기에는 암시 적 및 명시 적 두 가지 주요 유형이 있습니다. (우리는이 프로그램에서 유창한 대기를 고려하지 않습니다)
암시 적 대기는 조건에 관계없이 실행되는 대기입니다. 아래 프로그램에서 Google Chrome 용이며 속성 설정, 창 최대화, URL 탐색 및 웹 요소 찾기를 위해 몇 가지 내장 된 방법을 사용했음을 알 수 있습니다.
WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText('Software testing - Wikipedia'))); element2.click();
위의 코드에서 WebDriverWait를 기다리는 개체를 만든 다음 element2라는 WebElement를 검색했음을 알 수 있습니다.
조건은 웹 페이지에 '소프트웨어 테스트 – Wikipedia'링크가 표시 될 때까지 웹 드라이버가 기다려야하는 방식으로 설정됩니다. 이 링크를 찾지 못하면 실행되지 않습니다. 그렇다면 해당 링크를 마우스로 클릭합니다.
package Codes; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class explicitWaitConditionCheck { public static void main(String() args) { // TODO Auto-generated method stub System.setProperty('webdriver.chrome.driver', 'C:\webdriver\chromedriver.exe'); ChromeOptions options = new ChromeOptions(); options.addArguments('--disable-arguments'); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.navigate().to('https://www.google.com'); WebElement element = driver.findElement(By.name('q')); element.sendKeys('Testing'); element.submit(); WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText('Software testing - Wikipedia'))); element2.click(); }}
문 # 12) 위로 스크롤 / 아래로 스크롤을 보여주는 Java 프로그램을 작성하십시오.
대답: 이전 예제에서 설명한 것처럼 모든 코드 줄은 쉽게 관련 될 수 있습니다.
그러나이 프로그램에는 스크롤을 수행 할 JavascriptExecutor js가 포함되어 있습니다. 코드의 마지막 줄이 보이면 window.scrollBy (arg1, arg2)를 전달한 것입니다.
위로 스크롤하려면 arg1에 값을 전달하고 아래로 스크롤하려면 arg2에 값을 전달하십시오.
package Codes; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ScrollDown { public static void main(String() args) { // TODO Auto-generated method stub System.setProperty('webdriver.chrome.driver', 'C:\webdriver\chromedriver.exe'); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get('https://www.google.com'); WebElement element = driver.findElement(By.name('q')); element.sendKeys('SoftwareTestingHelp'); element.sendKeys(Keys.ENTER); js.executeScript('window.scrollBy(0,1000)'); } }
문 # 13) gmail.com의 모든 링크를 여는 Java 프로그램을 작성하십시오.
대답: 이전 프로그램에서 본 고급 for 루프의 전형적인 예입니다.
get () 또는 navigate (). to ()를 사용하여 Gmail과 같은 웹 사이트를 열면 tagName 로케이터를 사용하여 모든 태그를 반환 할 웹 사이트의 태그 이름을 찾을 수 있습니다.
우리는 링크 (이미 모든 태그를 찾은)에 대한 새로운 WebElement link2를 생성 한 for 루프를 발전 시켰고, getAttribute ( 'href')를 통해 모든 링크를 얻고 getText ()를 통해 모든 텍스트를 얻었습니다.
package Codes; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class openAllLinks { public static void main(String() args) { // TODO Auto-generated method stub System.setProperty('webdriver.chrome.drive', 'C:\webdriver\chromedriver.exe'); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get('https://www.gmail.com/'); java.util.List link = driver.findElements(By.tagName('a')); System.out.println(link.size()); for (WebElement link2: link) { //print the links i.e. http://google.com or https://www.gmail.com System.out.println(link2.getAttribute('href')); //print the links text System.out.println(link2.getText()); } } }
산출:
포트 16163에서 ChromeDriver 2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed) 시작
로컬 연결 만 허용됩니다.
4
https://support.google.com/chrome/answer/6130773?hl=en-GB
더 알아보기
https://support.google.com/accounts?hl=en-GB
도움
https://accounts.google.com/TOS?loc=IN&hl=en-GB&privacy=true
은둔
https://accounts.google.com/TOS?loc=IN&hl=en-GB
자귀
문 # 14) Selenium 코드를 작성하여 이전 탭으로 전환하십시오.
대답: 우리는 Robot 클래스의 사용을 시연했습니다. 바로 가기 키를 알고 있으면 브라우저와 해당 탭 내에서 다른 탐색을 수행 할 수 있으므로이를 중요한 타사로 간주합니다.
예를 들면 , 크롬에 세 개의 탭이 열려 있고 중간 탭으로 이동하려면 키보드에서 Ctrl + 2를 눌러야합니다. 코드를 통해서도 동일한 결과를 얻을 수 있습니다.
다음 코드를 관찰하십시오 (Robot 클래스의 인스턴스화를 본 직후). 두 개의 내장 메소드 keyPress (KeyEvenet.VK_ *) 및 keyRelease (KeyEvenet.VK_ *)와 함께 로봇이라는 Robot 클래스 객체를 사용했습니다.
package Codes; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class PreviousTab { public static void main(String() args) throws AWTException { // TODO Auto-generated method stub System.setProperty('webdriver.chrome.driver', 'C:\webdriver\chromedriver.exe'); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get('https://www.google.com'); WebElement element1 = driver.findElement(By.name('q')); element1.sendKeys('software testing help'); element1.sendKeys(Keys.ENTER); String a = Keys.chord(Keys.CONTROL,Keys.RETURN); driver.findElement(By.partialLinkText('Software Testing Help - A Must Visit Software Testing Portal')).sendKeys(a); Robot robot = new Robot(); // instantiated robot class robot.keyPress(KeyEvent.VK_CONTROL); // with robot class you can easily achieve anything if you know the shortcut keys robot.keyPress(KeyEvent.VK_2); // here, we have just pressed ctrl+2 robot.keyRelease(KeyEvent.VK_CONTROL); // once we press and release ctrl+2, it will go to the second tab. robot.keyRelease(KeyEvent.VK_2); //if you again want to go back to first tab press and release vk_1 } }
문 # 15) Java 프로그램을 작성하여 문자열에서 중복 문자를 찾으십시오.
대답: 이 프로그램에서 우리는 문자열 변수 str을 만들고 정수 카운트를 0으로 초기화했습니다.
그런 다음 문자열 변수를 문자로 변환하는 문자 배열을 만들었습니다. for 루프를 사용하여 서로 다른 인덱스에서 서로 다른 문자를 비교합니다.
연속 인덱스의 두 문자가 일치하면 해당 문자를 인쇄하고 카운터는 각 반복 후 1 씩 증가합니다.
public class DuplicateCharacters { public static void main(String() args) { // TODO Auto-generated method stub String str = new String('Sakkett'); int count = 0; char() chars = str.toCharArray(); System.out.println('Duplicate characters are:'); for (int i=0; i 산출:
중복 문자는 다음과 같습니다.
...에
티
문 # 16) 배열에서 두 번째로 높은 숫자를 찾기 위해 Java 프로그램을 작성하십시오.
대답: 이 프로그램에서 우리는 두 번째로 높은 숫자를 찾을 10 개의 무작위 요소로 배열을 초기화했습니다. 여기에는 가장 큰 정수와 두 번째로 큰 정수가 있습니다. 둘 다 요소의 첫 번째 색인으로 설정됩니다. 그런 다음 for 루프를 사용하여 모든 요소를 인쇄했습니다.
이제 논리는 0 번째 인덱스의 요소가 가장 큰 요소보다 큰 경우 arr (0)을 가장 큰 요소에 할당하고 secondLargest를 가장 큰 요소에 할당하는 것입니다. 다시 말하지만, 0 번째 인덱스의 요소가 secondLargest보다 크면 secondLargest를 arr (0)에 할당합니다.
이것은 각 반복에 대해 반복되며 궁극적으로 배열 길이까지 반복을 비교하거나 완료 한 후 secondLargest 요소를 제공합니다.
package codes; public class SecondHighestNumberInArray { public static void main(String() args) { int arr() = { 100,14, 46, 47, 94, 94, 52, 86, 36, 94, 89 }; int largest = 0; int secondLargest = 0; System.out.println('The given array is:'); for (int i = 0; i secondLargest) { secondLargest = arr(i); } } System.out.println('
Second largest number is:' + secondLargest); System.out.println('Largest Number is: ' +largest); } }
산출:
주어진 배열은 다음과 같습니다.
100 14 46 47 94 94 52 86 36 94 89
두 번째로 큰 숫자 : 94
가장 큰 숫자 : 100
문 # 17) 암스트롱 번호를 확인하는 Java 프로그램을 작성하십시오.
대답: 먼저 암스트롱 넘버가 무엇인지 이해해야합니다. 암스트롱 번호는 모든 단위의 입방체를 합한 숫자로, 세 자리 숫자의 경우 수백 자리입니다.
153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 = 1 + 125 + 27 = 153
네 자리 숫자가 있다면
1634 = 1 * 1 * 1 * 1 + 6 * 6 * 6 * 6 + 3 * 3 * 3 * 3 + 4 * 4 * 4 * 4 = 1 + 1296 + 81 + 256 = 1634
이제이 프로그램에서 우리는 임시와 정수를 선언했습니다. c를 값 0으로 초기화했습니다. 그런 다음 Armstrong을 검사 할 정수 값을 할당해야합니다 (이 경우 153이라고 가정). 그런 다음 확인하려는 번호로 임시 변수를 할당했습니다.
그 후 나머지는 a에 할당하고 숫자를 10으로 나누어 n에 할당하는 조건부 검사를 사용했습니다. 이제 처음에 0으로 설정된 c 변수는 c + (a * a * a)로 할당됩니다. 4 자리 숫자를 평가하고 c에 c + (a * a * a * a)를 할당해야한다고 가정합니다.
마지막으로, c에 포함 된 값을 temp (이 시점에 저장된 실제 숫자가 있음)와 비교 한 조건부 검사를위한 if-else 문을 넣었습니다. 일치하면 암스트롱이됩니다.
class Armstrong{ public static void main(String() args) { int c=0,a,temp; int n=153;//It is the number to check Armstrong temp=n; while(n>0) { a=n%10; n=n/10; c=c+(a*a*a); } if(temp==c) System.out.println('armstrong number'); else System.out.println('Not armstrong number'); } }
산출:
암스트롱 번호
문 # 18) replace ()를 사용하여 문자열에서 모든 공백을 제거하는 Java 프로그램을 작성하십시오.
대답: 이것은 문자열 변수 str1이있는 간단한 프로그램입니다.
또 다른 문자열 변수 str2는 n 개의 공백을 제거하는 내장 메소드 인 replaceAll 옵션으로 초기화됩니다. 궁극적으로 공백이없는 str2를 인쇄했습니다.
class RemoveWhiteSpaces { public static void main(String() args) { String str1 = 'Saket Saurav is a QualityAna list'; //1. Using replaceAll() Method String str2 = str1.replaceAll('\s', ''); System.out.println(str2); } } }
산출:
SaketSauravisaQualityAnalist
문 # 19) replace ()를 사용하지 않고 문자열에서 모든 공백을 제거하는 Java 프로그램을 작성하십시오.
대답: 이것은 모든 공백을 제거하는 또 다른 방법입니다. 다시 말하지만, 값이있는 문자열 변수 str1이 하나 있습니다. 그런 다음 toCharArray ()를 사용하여 해당 문자열을 문자 배열로 변환했습니다.
그런 다음 for 루프와 if 조건을 포함시킨 후 chars (i) 인덱스에 저장된 값을 추가하는 데 사용되는 StringBuffer 객체 sb가 하나 있습니다.
조건이 설정된 경우 문자 배열의 i 인덱스에있는 요소는 공백 또는 탭과 같지 않아야합니다. 마지막으로 StringBuffer 객체 sb를 인쇄했습니다.
class RemoveWhiteSpaces { public static void main(String() args) { String str1 = 'Saket Saurav is an Autom ation Engi ne er'; char() chars = str1.toCharArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i 산출:
SaketSauravisanAutomationEngineer
문 # 20) Excel을 읽으려면 Java 프로그램을 작성하십시오.
대답: 이러한 유형의 프로그램은 일반적으로 Selenium 프레임 워크에서 사용됩니다. 프로그램을 더 쉽게 이해할 수 있도록 모든 단계에 대한 자세한 설명을 추가했습니다.
논리는 데이터가 저장된 시트를로드 한 후에 시작됩니다. 이메일과 비밀번호를 가져 오려고합니다. 이를 위해 getRow () 및 getCell () 메서드를 사용하여 셀을 검색합니다. 첫 번째와 두 번째 셀에 이메일과 비밀번호가 있다고 가정 해 보겠습니다.
테스트 시나리오와 테스트 케이스의 차이점
그런 다음 셀 유형을 문자열로 설정합니다. 그 후 우리는 이러한 요소를 식별하는 'email'및 'password'와 같은 고유 한 로케이터 값을 전달하는 일반적인 웹 요소 로케이터 작업 (By.id)을 수행합니다.
마지막으로 cell.getStringCellValue ()가 키인 element.sendKeys를 사용하여 키를 보냅니다. 그러면 셀 번호 1과 2에 각각 저장된 값이 반환됩니다.
@Test public void ReadData() throws IOException { // Import excel sheet from a webdriver directory which is inside c drive. //DataSource is the name of the excel File src=new File('C:\webdriver\DataSource.xls'); //This step is for loading the file. We have used FileInputStream as //we are reading the excel. In case you want to write into the file, //you need to use FileOutputStream. The path of the file is passed as an argument to FileInputStream FileInputStream finput = new FileInputStream(src); //This step is to load the workbook of the excel which is done by global HSSFWorkbook in which we have //passed finput as an argument. workbook = new HSSFWorkbook(finput); //This step is to load the sheet in which data is stored. sheet= workbook.getSheetAt(0); for(int i=1; i<=sheet.getLastRowNum(); i++) { // Import data for Email. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id('email')).sendKeys(cell.getStringCellValue()); // Import data for the password. cell = sheet.getRow(i).getCell(2); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id('password')).sendKeys(cell.getStringCellValue()); } }
결론
이 기사에서는 Java 프로그래밍 인터뷰에서 요청되는 코드 예제와 함께 모든 중요한 기본 Java 인터뷰 프로그램에 대해 논의했습니다.
우리는 문자열, 정수 및 문자의 기본 조작, 셀레늄 코드, 파일에서 데이터 읽기, 코드를 통한 수학 시리즈와 같은 모든 Java 트릭을 배웠으며 이제 Java 인터뷰를 진행하는 방법에 대한 충분한 아이디어를 얻었습니다.
또한 읽기 => Java OOP 인터뷰 질문 및 답변
행운을 빕니다 :)
추천 도서