1. How to create repository in GIT?
$ git init
2. How to clone a repo?
Clone the test repo into a new directory called TEST:
$ git clone https://github.com/<username>/test.git TEST
3. How to switch branch?
git switch branchname
4. How to unstage changes or restore files?
Maybe you accidentally staged some files that you don't want to commit.
$ git restore test.js
$ git restore .
5. How to undo commits?
The following command will undo your most recent commit and put those changes back into staging, so you don't lose any work:
$ git reset --soft HEAD~1
The next one will completely delete the commit and throw away any changes. Be absolutely sure this is what you want:
$ git reset --hard HEAD~1
6. How to undo last push?
Some would say this is bad practice. Once you push something you shouldn't overwrite those changes. Instead, you're supposed to create a new commit that reverts the changes in the last one. So, technically, you shouldn't do this, but... you can?
$ git reset --hard HEAD~1 && git push -f origin master
7. How to fetch changes from both origin and upstream?
$ git fetch --multiple origin upstream
8. How to delete a local branch?
$ git branch -d <local_branch>
Use the -D option flag to force it.
9. How to stash ur chnages?
$ git stash
10. How to push changes?
git add -all
git commit -m "message"
git push remote_server branch_Name
11. Difference between rebase and merge?
git merge apply all unique commits from branch A into branch B in one commit
git rebase gets all unique commits from both branches and applies them one by one.
git rebase rewrites commit history but doesn't create extra commit for merging.
Wednesday, 28 September 2022
SQL Interview Questions
As SQL is quite vast so I will post interview questions on SQL query in three sets, below is the set-10:
1. Write An SQL Query To Print Details Of The EMPLOYEEs Whose FIRST_NAME Ends With ‘A’.
Select * from EMPLOYEE where FIRST_NAME like '%a';
2. Write An SQL Query To Print Details Of The EMPLOYEEs Whose FIRST_NAME Ends With ‘H’ And Contains Six Alphabets.
Select * from EMPLOYEE where FIRST_NAME like '_____h';
3. Write An SQL Query To Print Details Of The EMPLOYEEs Whose SALARY Lies Between 100000 And 500000.
Select * from EMPLOYEE where SALARY between 100000 and 500000;
4. Write An SQL Query To Print Details Of The EMPLOYEEs Who Have Joined In Feb’2014.
Select * from EMPLOYEE where year(JOINING_DATE) = 2014 and month(JOINING_DATE) = 2
5. Write An SQL Query To Fetch EMPLOYEE Names With Salaries >= 50000 And <= 100000.
Select FIRST_NAME, SALARY from EMPLOYEE where SALARY between 50000 And 100000.
6. Write An SQL Query To Fetch The No. Of EMPLOYEEs For Each Department In The Descending Order.
SELECT DEPARTMENT, count(EMPLOYEE_ID) No_Of_EMPLOYEEs
FROM EMPLOYEE
GROUP BY DEPARTMENT
ORDER BY No_Of_EMPLOYEEs DESC;
7. Write An SQL Query To Print Details Of The EMPLOYEEs Who Are Also Managers.
SELECT EMPLOYEE.EMPLOYEE_ID,EMPLOYEE.DEPARTMENT,EMPLOYEE.FIRST_NAME ,Title.EMPLOYEE_TITLE Title from EMPLOYEE Inner Join Title
on EMPLOYEE.EMPLOYEE_ID=Title.EMPLOYEE_Ref_ID where Title.EMPLOYEE_TITLE='Manager' order by EMPLOYEE_ID
8. Write An SQL Query To Fetch Duplicate Records Having Matching Data In Some Fields Of A Table.
SELECT EMPLOYEE_TITLE, AFFECTED_FROM, COUNT(*)
FROM Title
GROUP BY EMPLOYEE_TITLE, AFFECTED_FROM
HAVING COUNT(*) > 1;
9. Write An SQL Query To Show Only Odd Rows From A Table.
SELECT * FROM Emplyee WHERE MOD (EMPLOYEE_ID, 2) <> 0;
10. Write An SQL Query To Show Only Even Rows From A Table.
SELECT * FROM EMPLOYEE WHERE MOD (EMPLOYEE_ID, 2) = 0;
11. Write An SQL Query To Determine The Nth (Say N=5) Highest Salary From A Table.
SELECT Salary FROM EMPLOYEE ORDER BY Salary DESC LIMIT n-1,1;
Test NG Tricky Questions
Below is the list of most important attributes for TestNG annotations, in terms of day to day work and interview preparation
1. Description - The description of the method
@Test(Description="Login to Application")
2. Enabled - Whether methods/class are enabled
@Test(Description="Login to Application", enabled=false)
3. AlwayRun - If set to True, this method will always be run even if it depends on a method failed
@Test(Description="Login to Application", alwaysRun=false)
4. priority - Priority of this method . Lower priority methods will be scheduled First
@Test(Description="Login to Application", priority=1)
5. Can priority negative or zero values?
Yes, we can
6. groups - the list of groups this method belongs to?
@Test(Description="Login to Application", groups={"Smoke","Regression"})
7.
OOPS Concepts in Selenium
Below are the different Java OOPs concepts and the ways how it is used in Selenium Automation Framework:
1) DATA ABSTRACTION
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
In Selenium, WebDriver itself acts as an interface. Consider the below statement:
WebDriver driver = new ChromeDriver();
We initialize the Chrome Browser using Selenium Webdriver. It means we are creating a reference variable (driver) of the interface (WebDriver) and creating an Object. Here WebDriver is an Interface and ChromeDriver is a class.
We can apply Data Abstraction in a Selenium framework by using the Page Object Model design pattern. We define all our locators and their methods in the page class. We can use these locators in our tests but we cannot see the implementation of their underlying methods. So we only show the locators in the tests but hide the implementation. This is a simple example of how we can use Data Abstraction in our Automation Framework.
2) ENCAPSULATION
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
All the classes in an Automation Framework are an example of Encapsulation. In Page Object Model classes, we declare the data members using @FindBy and initialization of data members will be done using Constructor to utilize those in methods.
3) INHERITANCE
Inheritance is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.
We can apply Inheritance in our Automation Framework by creating a Base Class to initialize the WebDriver interface, browsers, waits, reports, logging,etc. and then we can extend this Base Class and its methods in other classes like Tests or Utilities. This is a simple example of how we can apply Inheritance in our framework.
4) POLYMORPHISM
The word polymorphism means having many forms. Polymorphism allows us to perform a single action in different ways. In Java polymorphism can be achieved by two ways:
– Method Overloading: When there are multiple methods with same name but different parameters then these methods are said to be overloaded. Methods can be overloaded by change in number of arguments or/and change in type of arguments.
In Selenium Automation, Implicit wait is an example of Method Overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc.
Some more examples of Method Overloading in Selenium are present in methods of Actions Class and Assert class in TestNG as shown below:
– Method Overriding: It occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
In Selenium Automation, Method Overriding can be achieved by overriding any WebDriver method. For example, we can override the findElement method as shown below:
public static WebElement findElement(By Locator){
WebElement element = fluentWait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(Locator);
}
});
return element;
}
Selenium Interview Questions
1.How to perform back,forward and refresh action in selenium?
driver.navigate().back()
driver.navigate().forward()
driver.navigate().refresh()
2. What is the return type of findelements?
List of elements with similar property
3. What will happen if no webelement is found for findelements?
It will return an empty list
4. What will happen if no webelement is found for findelement?
It will give error as :NoSuchElementException
5. How to select value from dropdown in selenium?
Using select class as below
Select technology = new Select(driver.findElement(By.xpath("//select[@id='effectTypes']")));
technology.selectByVisibleText("Drop");
6. What are the methods provided in selenium to select from dropdown?
selectByVisibleText()
selectByValue()
selectByIndex()
7. How to fetch text from UI in selenium?
gettext()
getAttribute("propertyname")
8. How to get current url,title and page source?
driver.getCurrentUrl();
driver.getTitle();
driver.getPageSource();
9. How to clear text using selenium?
clear() — method is used to clear text from the text area
driver.findElement(By.xpath(“//input[@placeholder=’Username’]”)).clear();
10. How to do Browser Initialization for all types of browser?
• Firefox
WebDriver driver = new FirefoxDriver();
• Chrome
WebDriver driver = new ChromeDriver();
• Internet Explorer
WebDriver driver = new InternetExplorerDriver();
• Safari Driver
WebDriver driver = new SafariDriver();
11. How to handle alerts and popups in selenium?• driver.switchTO().alert.accept() — to accept the alert box
• driver.switchTO().alert.dismiss() — to cancel the alert box
12. How to retrive alert pop up message in selenium?
• driver.switchTO().alert.getText() — to retrieve the alert message
13. How to send data to alert box in Selenium?
• driver.switchTO().alert.sendKeys(“Text”) — to send data to the alert box
14. How to switch frames in selenium?
• driver.switchTo.frame(int frameNumber) — mentioning the frame index number, the Driver will switch to that specific frame
• driver.switchTo.frame(string frameNameOrID) — mentioning the frame element or ID, the Driver will switch to that specific frame
• driver.switchTo.frame(WebElement frameElement) — mentioning the frame web element, the Driver will switch to that specific frame
15. How to switch back to main window in frames?
• driver.switchTo().defaultContent() — Switching back to the main window
16. How to handle multiple windows and tabs in Selenium?
• getWindowHandle() — used to retrieve the handle of the current page (a unique identifier)
• getWindowHandles() — used to retrieve a set of handles of the all the pages available
17. How to switch between windows and tabs?
• driver.switchTo().window(“windowName/handle”) — switch to a window
18. How to close the cureent browser window?
• driver.close() — closes the current browser window
19. How to handle Implicit wait?
Used to wait for a certain amount of time before throwing an exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
20. How to handle Explicit wait?
Used to wait until a certain condition occurs before executing the code.
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("login")));
21. What are the element validation methods in selenium?
• isEnabled() — determines if an element is enabled or not, returns a boolean.
• isSelected() — determines if an element is selected or not, returns a boolean.
• isDisplayed() — determines if an element is displayed or not, returns a boolean.
22. How to handle proxy in selenium for chrome?
ChromeOptions options = new ChromeOptions();// Create object Proxy class - Approach 1
Proxy proxy = new Proxy();
proxy.setHttpProxy("username:password.myhttpproxy:3337");
options.setCapability("proxy", proxy);
ChromeDriver driver = new ChromeDriver(options);
23. How to set the size of the window in selenium?
driver.manage().window().setSize(new Dimension(1024, 768));
24. How to fetch the size of window in Selenium?
Dimension size = driver.manage().window().getSize();
int width = size.getWidth();
int height = size.getHeight();
25. How to maximize the window in selenium?
driver.manage().window().maximize();
26. How to drag and drop from source to destination?
WebElement source = driver.findElement(By.xpath("//div[@id='draggable']"));
WebElement destination = driver.findElement(By.xpath("//div[@id='droppable']"));
Actions builder = new Actions(driver);
builder.dragAndDrop(source,destination);
27. How to perform keyboard actions in selenium?
By using Robot class as below:
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_ENTER);
28. How to get all cookies and with name of the cookie?
driver.manage().getCookies();
driver.manage().getCookieNamed("APISID");
29. How to delete all cookies and with name of the cookie?
driver.manage().deleteCookieNamed("APISID");
driver.manage().deleteAllCookies();
30. How to add a cookie?
Cookie cookie1 = new Cookie("test2", "cookie2");
driver.manage().addCookie(cookie1);
31. How to rerun failed test cases in Selenium using TestNG?
Click here to answer
32. What approach to take if clear() method is not working on a textbox?
sendKeys(Keys.chord(Keys.CONTROL,"a",Keys.DELETE));
33. How to run test case in parallel for multiple browsers?
<suite name="Automation Test Suite " parallel="tests" thread-count="2">
<test name="Automation Test CasesChrome">
<classes>
<class name="com.task.automation.testtwo.testone"/>
</classes>
</test>
<test name="Automation Test Casesfirefox">
<classes>
<class name="com.task.automation.testtwo.testfirefox"/>
</classes>
</test>
</suite>
34. Create a common method for Explicit wait to check element is visible or not?
public void waitForElementVisible(WebElement element, long timeout) {
try {
new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOf(element));
} catch (ElementNotVisibleException e) {
Reporter.log(element.toString() + "is not visible");
Reporter.log(e.getStackTrace().toString());
}
}
Top API Interview Question 11-20
35. How to prepare automation test estimation ?
Click here for answer
36. How to launch batch file from Selenium WebDriver?
Process batch = Runtime.getRuntime.exec("path of the batch file");
37. How to run selenium test from command line?
java -classpath ".;selenium-server-standalone-2.33.0.jar" SampleClass
38. What is the name of the super interface of the Webdriver?
Ans: SearchContext.
39. Explain some of the strategy you have followed while using xpath?
Click here for answer
40. How to execute the testng test suite from the command line?
Ans: java -cp “C:\AutomationReinvented\testng \lib\*;C:\AutomationReinvented\testng\bin” org.testng.TestNG testng.xml
41. What’s the difference between soft and hard asserts?
A soft assert will run the test and not throw an exception if the assert failed, while a hard assert will throw the exception immediately, and then continue with the testing process.
@Test
public void softAssertion(){
SoftAssert softAssertion= new SoftAssert();
System.out.println("softAssert");
softAssertion.assertTrue(false);
softAssertion.assertAll();
}
@Test
public void hardAssertion(){
System.out.println("hardAssert");
Assert.assertTrue(false);
System.out.println("hardAssert");
}
Soft Assertions are the type of assertions that do not throw an exception when an assertion fails and continue with the next step after the assert statement. This is used when the test requires multiple assertions to be executed and we want all of the assertions/codes to be executed before failing/skipping the tests.
Hard Assert is a type of TestNG assetion which throws Exception Immediately if the assert statement fails and move to the next testcase and if there is any code in the current test case after assert statement it will not execute that statement.
42. How would you upload a file via Selenium Webdriver? Know About Kubernetes
Let we have a button as "Choose File", so first need to identify this element as below
@FindBy(xpath="//span[contains(text(),'Activate')]")
public WebElement chooseFile;
Use sendkeys with the file path that you want to upload:
chooseFile.sendKeys("C:\\filetoupload")
43. What are the parameters do you have to meet for Selenium to pass a test?
There are four conditions (parameters) for Selenium to pass a test, as below:
URL, host, browser and port number.
44. Have you worked on invocation count/thread count or any advanced TestNG annotation, if Yes then can you explain?
alwaysRun
If set to true, this test method will always be run even if it depends on a method that failed.
dependsOnMethods
The list of methods this method depends on.
@test:
Marks a class or a method as part of the test.
Description:
The description for this method. It is important to give a small information about the test case.
Enabled:
Whether methods on this class/method are enabled.
invocationCount
The number of times this method should get invoked.
threadPoolSize
The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.
Note: this attribute is ignored if invocationCount is not specified
timeOut
The maximum number of milliseconds this test should take.
expectedExceptions
The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.
45. Tell me two things that you can't automate using Selenium?
Captcha and Barcodes
46. Explain some of the keywords that has been used in your project for BDD approach?
Scenario outline:
The Scenario Outline keyword can be used to run the same Scenario multiple times, with different combinations of values.
Background:
Sometimes you’ll find yourself repeating the same Given steps in all of the scenarios in a feature.
Since it is repeated in every scenario, this is an indication that those steps are not essential to describe the scenarios. You can literally move such Given steps to the background, by grouping them under a Background section.
Monochrome:
Display console output in readable way
Glue:
it helps Cucumber to locate theStep Definition file.Whenever Cucumber encounters a Step, it looks for a Step Definition inside all the files present in the folder mentioned in Glue Option.
Feature:
The purpose of the Feature keyword is to provide a high-level description of a software feature, and to group related scenarios.The first primary keyword in a Gherkin document must always be Feature, followed by a : and a short text that describes the feature.
plugin:
plugin Option is used to specify different formatting options for the output reports.
Format:
It will define the format of the reports. Options are pretty,html,json,junit.
Note – Format option is deprecated . Use Plugin in place of that.
RunWith:
This is a JUnit annotation that specifies which runner it has to use to execute this class
CucumberOptions:
This annotation provides some important information which will be used to run your cucumber feature file.
Given:
It is for pre condition
When:
Test action that will get executed
Then:
It defines the expected result.
Add:
Add conditions to step
But:
It is used to add negative type comments
Strict:
with true as opted value, It will fail execution if any undefined or pending steps found.
dryRun: Check if all steps have step definition tag:
The tags can be used when specifying what tests to run through any of the running mechanism.
@RunWith(Cucumber.class)
@CucumberOptions(
features = “src/test/“,
tags ={“@Web“},... )
Cucumber can exclude scenarios with a particular tag by inserting the tilde character before the tag.
For the following command will run all Scenarios without the UI tag.
@RunWith(Cucumber.class)
@CucumberOptions(
features = “src/test/features“,
tags ={“~@UI“},... )
47. What will happen if you run this command. driver.get(“www.google.com”) ?
As the given URL doesn’t contain http or https prefix so it will throw an exception.
So, it is required to pass HTTP or HTTPS protocol within driver.get() method.
driver.get(“https://www.google.com”);
48. What is Recovery Scenario in Selenium WebDriver?
Recovery Scenarios is done by using “Try Catch” block within Selenium WebDriver :.
try{
driver.get(“https://www.google.com“);
}
catch (Exception e){
e.printStackTrace();
}
49. Which Source code management tool you have used and tell me some of the basic commands that you have used?
Git
50. Have you worked on database side for fetching data to validate in selenium tests, if Yes then can you tell me some of the basic queries that you have used in day to day work?
SQL Queries
71. What is default time for implicit and explicit wait?
Implicit wait default time is zero.
Explicit wait default time is 500 ms
72. What is remote WebDriver client?
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("browserVersion", "67");
chromeOptions.setCapability("platformName", "Windows XP");
WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), chromeOptions);
driver.get("http://www.google.com");
driver.quit();
73. What is the use of Driver in Selenium?
Responsible for controlling the actual browser. Most drivers are created by the browser vendors themselves. Drivers are generally executable modules that run on the system with the browser itself, not on the system executing the test suite.
74.What are the new features in Selenium 4? VERY IMP
Click Here For Detail Answer
75. Explain some of the strategy to handle CAPTCHA?
There are two primary strategies to get around CAPTCHA checks:Disable CAPTCHAs in your test environment
Add a hook to allow tests to bypass the CAPTCHA
76. What is page load strategy in Selenium?
Click Here For Answer
77. What is Relative Locators?
Selenium 4 brings Relative Locators which are previously called as Friendly Locators. This functionality was added to help you locate elements that are nearby other elements. The Available Relative Locators are:above
below
toLeftOf
toRightOf
near
78. What is the use of withTagName()?
indElement method now accepts a new method withTagName() which returns a RelativeLocator.
79. How to perform parallel test with cross browser using docker?
Click Here For Answer With Code
80.How to create a custom profile ?
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
driver = new RemoteWebDriver(options);
BONUS.How do you achieve synchronization in WebDriver?
We can achieve synchronization either by using Static Wait or Dynamic Wait.
Static wait : Thread.sleep(): not good practice to use static wait
Dynamic wait: This can be achieved by using Implicit wait, Explicit Wait, Fluent Wait
Thursday, 13 January 2022
Java Interview Programs for Selenium tester
///---Java Programs---///
1. Write a Program to swap two numbers without using temp variable?
public class SwapTwoNumber {
public static void main(String[] args) {
int a=10;
int b=20;
System.out.println("Before Swapping numbers are: A="+a +" B="+b);
/*//Method 1
a=a^b;
b=a^b;
a=a^b;*/
/*//Method2
a=a*b;
b=a/b;
a=a/b;*/
/*//Method 3
a=a+b;
b=a-b;
a=a-b;*/
//Method 4
b=a+b -(a=b);
System.out.println("After Swapping numbers are: A="+a +" B="+b);
}
}
2. Polindrom:
public class MyClass {
public static void main(String args[]) {
String strr="hserus";
String rev="";
for (int i=strr.length()-1;i>=0;i--) {
rev=rev+strr.charAt(i);
}
System.out.println("Polindrom " + rev);
}
}
3. Reverse Number/Polindrom
public class MyClass {
public static void main(String args[]) {
int num, revnum=0;
num=4321;
while(num !=0){
revnum= revnum * 10 + num % 10;
num /= 10;
}
// Using StringBuffer
//StringBuffer sb= new StringBuffer(String.valueOf(num));
// StringBuffer revnum= sb.reverse();
System.out.println("number is " + revnum);
}
}
4. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String str= "hseruS";
String rev="";
int len=str.length(); //4
for(int i=len-1;i>=0;i--){
rev=rev+str.charAt(i);
}
//Using Character Array
//char a[]=str.toCharArray();
// int len=a.length;
//for(int i=len-1;i>=0;i--){
// rev=rev+a[i];
// }
System.out.println("Reverse string is " + rev);
}
}
5. Count Number of digits in a number
public class CountNumber {
public static void main(String[] args) {
int num= 43243341, count=0;
while(num>0){
num=num/10;
count++;
}
System.out.println("NUmber of digits are " + count);
}
}
6. Even and Odd Count
public class EvenorOdd {
public static void main(String[] args) {
int num= 4324, Even=0, odd=0,rem=0;
while(num>0){
rem=num%10;
if(rem%2==0){
Even++;
}
else{
odd++;
}
num=num/10;
}
System.out.println("Even Numbers are " + Even);
System.out.println("Odd Number are " + odd);
}
}
7. Sum of Numbers
public class FindSumofDigits {
public static void main(String[] args) {
int num= 4324, sum=0, odd=0,rem=0;
while(num>0){
sum=sum+ num%10;
num=num/10;
}
System.out.println("Sum of Numbers are " + sum);
}
}
8.Swap Two Strings without using third variable
class SwapTwoStrings
{
public static void main(String args[])
{
String a = "Hello";
String b = "World";
System.out.println("Strings before swap: a = " +
a + " and b = "+b);
a = a + b;
b = a.substring(0,a.length()-b.length());
a = a.substring(b.length());
System.out.println("Strings after swap: a = " +
a + " and b = " + b);
}
}
9. Reverse a string only in given string not numbers and position
public class reverseOnlyString {
public static void main(String[] args) {
String str="123abc1234abcde";
String reverse="";
String re="";
String res="";
int j;
for(j=0;j<str.length();j++) {
char dig= str.charAt(j);
if(Character.isDigit(dig)) {
reverse= reverse + dig;
}
else {
for(int i=j;i<str.length();i++) {
char rev= str.charAt(i);
if(Character.isDigit(rev)) {
for(int k=re.length()-1;k>=0;k--) {
res=res + re.charAt(k);
}
reverse=reverse+res;
j--;
re="";
res="";
break;}
else {
re= re + rev;
j++;
}
}
}
}
for(int k=re.length()-1;k>=0;k--) {
res=res + re.charAt(k);
}
reverse=reverse+res;
System.out.println("Reverse String is : "+ reverse );
}
}
9. To count repeated words in a string using HashMap
public class countRepeatedwords {
public static void main(String[] args) {
String str="Hi this is repeated words count is this repeated";
String[] words = str.split(" ");
HashMap<String, Integer> map= new HashMap<String, Integer>();
for(int i=0;i<words.length;i++) {
if(map.containsKey(words[i])) {
int count= map.get(words[i]);
map.put(words[i], count+1);}
else {
map.put(words[i], 1);
}
}
System.out.println(map);
}
}
10. Duplicate char in a string
public class duplicateCharaters {
public static void main(String are[])
{
String str="Suresh Meti";
int len=str.length();
System.out.println("Repeated words are: ");
char[] ch=str.toLowerCase().toCharArray();
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(ch[i]==ch[j])
{
System.out.println(ch[j]);
break;
}
}
}
}
}
11. Armstrong number (Armstrong number is the number which is the sum of the cubes of all its unit 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153)
public class armstrongnumber {
public static void main(String areg[])
{
int n=153,a,c=0;
int temp=n;
while(n>0)
{
a=n%10;
c=c+(a*a*a);
n=n/10;
}
if(temp==c)
{
System.out.println("Given "+temp+" number is Armstrang number ");
}
else
{
System.out.println("Given "+temp+" number is not Armstrang number ");
}
}
}
12. Write the Java code to Sort the words by Ascending order? (Cat, God, Ant, Bell)
public class sortStringbyAsc {
public static void main(String arg[])
{
String[] str= {"Suresh","Meti","Apple","Dog","Ball"};
String temp;
for(int i=0;i<str.length;i++)
{
for(int j=i+1;j<str.length;j++)
{
if(str[i].compareTo(str[j])>0)
{
temp= str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
System.out.println("The names in alphabetical order are: ");
for(int i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}
13.Removing duplicate values in arrays
public class duplicatevaluesremoved {
public static void main(String args[]) {
int a[] = { 1, 3, 3, 4, 2, 1, 4, 6, 7, 7, 10, 10 };
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length-1;i++) {
if(a[i]!=a[i+1]) {
a[j]=a[i];
j++;
}
}
a[j]=a[a.length-1];
for (int i = 0; i <= j; i++) {
System.out.println(a[i]);
}
}
}
14. First Non Repeat Character
String str="abc ade bcd efg ghi";
For(char i: str.toCharArray()) {
if(str.indexOf(i)==str.lastIndexof(i)) {
System.out.println("First non Repeat character is : "+i);
break;
}
}
15. Reverse only string not numbers using string buffer
public class Reverseonlystring {
public static void main(String[] args) {
String input = "123CBA456ZYX789";
String[] parts = input.split("(?=\\d)");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
if (part.matches("\\d+")) {
sb.append(part);
}
else {
StringBuilder num = new StringBuilder(part);
sb.append(num.reverse());
}
}
System.out.println(sb.toString());
}
}
16. Reverse string only without special character
public class Reverseonlycharnotspecialcharachers {
public static void main(String[] args) {
String str1 = "a!!!b.c.d,e'f,ghi";
char[] str = str1.toCharArray();
int j = str.length - 1, i = 0;
String rev="";
while (i < j)
{
if (!Character.isAlphabetic(str[i]))
i++;
else if(!Character.isAlphabetic(str[j]))
j--;
else
{
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
i++;
j--;
}
}
for(char a : str) {
rev= rev+a;
}
System.out.println("Output string: " + rev);
}
}
17. Write a program to find missing number in array using c#
Public class MissingArray()
{
int[] arr={4,5,1,4,9,1};
for(int i=0;i<arr.Length;i++)
{
if(Array.Indexof(arr,i+1) <0)
{
Console.WriteLine("Missing Number is : "+ (i+1));
}
}
}
Output: Missing Number is : 2
Output: Missing Number is : 3
Output: Missing Number is : 6
18. Write a program to find missing number in array and duplicate values.
Public class MissingAndDuplicateArray()
{
int[] arr={4,5,1,4,9,1};
for(int i=0;i<arr.Length;i++)
{
if(Array.Indexof(arr,i+1) <0)
{
Console.WriteLine("Missing Number is : "+ (i+1));
}
}
Console.WriteLine("=========");
//Duplicate values in array
for(int i=0;i<arr.Length;i++)
{
for(int j=i+1;j<arr.Length;j++)
{
if(arr[i]==arr[j])
{
Console.WriteLine("Duplicate number is :"+ arr[j]);
break;
}
}
}
}
Output: Missing Number is : 2
Output: Missing Number is : 3
Output: Missing Number is : 6
===========
Duplicate number : 4
Duplicate number : 1
////--- Oracle ----////
1. Explain About Oops Concepts in terms of Framework?
2. What would be answer the if we have different type of return type
ex. Sum(int x, int y)
{ return int;}
Sum(int x, int y)
{ return double;}
3. Can we access public method
Super Class--> Private Sum(int x, int y)
Subclass --> Public Sum(int x, int y)
4.
5.Can i
Subscribe to:
Comments (Atom)