The document contains 17 Java code snippets that provide solutions to common programming problems and examples. Some of the problems addressed include: reversing an integer, checking if two words are anagrams, palindrome checking, merging two sorted arrays, left rotation of an array, sorting an array of 0s, 1s and 2s, counting character occurrences in a string, factorial, Fibonacci series, prime number checking, bubble sort, and substring searching. The code snippets provide full programs or methods to solve each problem in 1-5 steps or lines of code each.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
A quick presentation on JAVA Puzzlers inspired by the study of Eric Lefevre-Ardant and Guillaume Tardif. A few puzzlers to understand the tricks of the language.
We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.
A quick presentation on JAVA Puzzlers inspired by the study of Eric Lefevre-Ardant and Guillaume Tardif. A few puzzlers to understand the tricks of the language.
program list:
WAP program to show constructor overloading using static member.
WAP to implement multilevel inheritance and method overriding.
WAP to implement interface class and show use of package.
WAP to implement multilevel exception handling and create your own exception.
WAP to implement 3 threads such that 1st sleeps for 200ms, 2nd for 400ms and 3rd for 600ms.
WAP to create applet of moving banner.
WAP to make a simple calculator.
Build a client server chat application.
Refer to my progress on this assignment belowIn this problem you w.pdfarishmarketing21
Refer to my progress on this assignment below
In this problem you will make it “more” object-oriented in the following ways:
-You will change its name to SortedList
-You will change the constructor that takes no arguments to be more traditional and initialize the
member fields to dummy values.
-You will add a constructor that takes in an initialized array and a size
-You will add an insert function that adds a value to the list and maintains its sorted-ness
-You will add a quicksort function check the below code.
-You will make updates as necessary to the main function so that it still runs and tests your code.
The code below seems to sort correctly but it skips over some items in the array and I am not
sure what is happening. Please help! Thanks!
import java.util.Scanner;
class SortedList
{
private static int array[];
private static int n;
public SortedList()
{
Scanner in = new Scanner(System.in);
System.out.println(\"Enter number of elements\");
n = in.nextInt();
array = new int[n];
if(n == 0) {
System.out.print(\"Since no arguments array set to: \");
} else {
System.out.print(\"Creating array size \" + n + \": \");
}
for(int i = 0; i < n; i++)
{
array[i] = 0;
}
//System.out.println(\"Enter \" + n + \" integers in ascending order\");
/*for (c = 0; c < n; c++)
array[c] = in.nextInt();*/
for(int i = 0; i < n; i++)
{
System.out.print(array[i] + \" \");
}
System.out.print(\"\ \");
}
public SortedList(int a[], int size)
{
array = a;
n = size;
}
public int binsearch(int search)
{
int first, last, middle;
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
//System.out.println(search + \" found at location \" + (middle + 1) + \".\");
return middle+1;//+1 for the non-CS people who don\'t start counting at zero.
}
else
last = middle - 1;
middle = (first + last)/2;
}
return -1;
//System.out.println(search + \" is not present in the list.\ \");
}
public static int partition(int input[], int p, int r)
{
int pivot = input[r];
while(p < r)
{
while(input[p] < pivot)
{
p++;
}
while(input[r] > pivot)
{
r--;
}
if(input[p] == input[r])
{
p++;
}
else if(p < r)
{
int tmp = input[p];
input[p] = input[r];
input[r] = tmp;
}
}
return r;
}
public static void quicksort(int input[], int p, int r)
{
if(p < r)
{
int j = partition(input, p, r);
quicksort(input, p, j-1);
quicksort(input, j+1, r);
}
}
public static void insert(int value, int cell)
{
array[cell] = value;
quicksort(array, 0, n-1);
}
public static void main(String args[])
{
int c;
Scanner in = new Scanner(System.in);
SortedList b = new SortedList();
System.out.println(\"Input numbers\");
for(int i = 0; i < n; i++)
{
c = in.nextInt();
in.nextLine();
insert(c, i);
}
in.close();
for(int j = 0; j < n; j++)
{
System.out.print(array[j] + \", \");
}
}
}
Solution
//the whole program that you wrote is correct except one line , when you call the quicksort
everytime you insert a //value dont pass n pass the i.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Hivelance Technology
Cryptocurrency trading bots are computer programs designed to automate buying, selling, and managing cryptocurrency transactions. These bots utilize advanced algorithms and machine learning techniques to analyze market data, identify trading opportunities, and execute trades on behalf of their users. By automating the decision-making process, crypto trading bots can react to market changes faster than human traders
Hivelance, a leading provider of cryptocurrency trading bot development services, stands out as the premier choice for crypto traders and developers. Hivelance boasts a team of seasoned cryptocurrency experts and software engineers who deeply understand the crypto market and the latest trends in automated trading, Hivelance leverages the latest technologies and tools in the industry, including advanced AI and machine learning algorithms, to create highly efficient and adaptable crypto trading bots
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
1. 1
1. Given an integer "532341", output should be reverse of integer.
Ans:
public classReverseNumber {
public static void main(String[] args) {
int num = 1234,reversed = 0;
while(num != 0) {
int digit= num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}
2. Given two words, check if they are anagramof each other or not.
public static void main(String[] args) throws ParseException {
String s1="anagram";
String s2="margana";
int lettersS1[] = new int[Character.MAX_VALUE];
int lettersS2[] = new int[Character.MAX_VALUE];
if(s1.length()!=s2.length())
System.out.print("No");
else {
for(inti = 0; i<s1.length() ;++i) {
lettersS1[s1.toLowerCase().charAt(i)]++;
lettersS2[s2.toLowerCase().charAt(i)]++;
}
boolean anag= true;
for(inti = 0;i<lettersS1.length&&anag;++i) {
if(lettersS1[i] != lettersS2[i]) {
anag= false;
}
}
if(anag) {
System.out.print("Anagram");
} else {
System.out.print("No anagram");
}
}
}
2. 2
3. Palindromejava
class PalindromeExample{
public static void main(String args[]){
intr,sum=0,temp;
intn=454;//It is the number variableto be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindromenumber ");
else
System.out.println("not palindrome");
Q 4 :Palindromeword
public class palindrom {
public static void main(String args[])
{
String name2 = "", name = "naman";
int i;
// char name2;
for(i=name.length()-1;i>-1;i--)
name2=name2+name.charAt(i);
System.out.println(name2);
if(name.equals(name2))
{
System.out.println("palindrome");
}
else
{
System.out.println("no");
}
}
}
5. Given two strings A = "My name is Praneta"and B = "name is", output should be a new stringthat has all words
of A that are not present in "B". Output : "My Praneta"
package examples;
class StringSubString {
public static void main(String[] args) {
String oldStr = "My Name is Archana";
String delStr = "Name is ";
String newStr;
newStr = oldStr.replace(delStr, "");
System.out.println(oldStr);
3. 3
System.out.println(newStr);
}
}
6. Given an integer number n, for multiples of three print “Fizz” for the multiples of fiveprint “Buzz”. For numbers
which are multiples of both three and fiveprint “FizzBuzz”.
public class FizzBuzz {
public static void main(String[] args) {
for (inti = 1; i < 101; i++) {
// Set this to true when one of the special conditions ismet.
boolean printed = false;
if (i % 3 == 0) {
// When i is divisibleby 3, then print"Fizz"
printed = true;
System.out.print("Fizz");
} else if (i % 5 == 0) {
// When i is not divisibleby 3 but is divisibleby 5, then print"Buzz"
printed = true;
System.out.print("Buzz");
}
}
}
}
7. binary search programin java
1. class BinarySearchExample{
2. public static void binarySearch(intarr[],intfirst,intlast,intkey){
3. int mid = (first+ last)/2;
4. while( first<= last){
5. if ( arr[mid] < key ){
6. first= mid + 1;
7. }else if ( arr[mid] == key ){
8. System.out.println("Element is found atindex: " + mid);
9. break;
10. }else{
11. last= mid - 1;
12. }
13. mid = (first+ last)/2;
14. }
15. if ( first> last){
16. System.out.println("Element is not found!");
17. }
18. }
19. public static void main(String args[]){
20. int arr[] = {10,20,30,40,50};
21. int key = 30;
22. int last=arr.length-1;
23. binarySearch(arr,0,last,key);
24. }
25. }
26. Element is found at index: 2
4. 4
8.Given a string,find the second most frequent character in it.
// Java Program to find the second
// most frequent character in each string
public class GFG
{
static final intNO_OF_CHARS = 256;
// finds the second most frequently occurring
// char
static char getSecondMostFreq(String str)
{
// count number of occurrences of every
// character.
int[] count = new int[NO_OF_CHARS];
int i;
for (i=0; i< str.length(); i++)
(count[str.charAt(i)])++;
// Traverse through the count[] and find
// second highest element.
int first= 0, second = 0;
for (i = 0; i < NO_OF_CHARS; i++)
{
/* If current element is smaller than
firstthen update both firstand second */
if (count[i] > count[first])
{
second = first;
first= i;
}
/* If count[i] is in between firstand
second then update second */
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return (char)second;
}
// Driver programto test above function
public static void main(Stringargs[])
{
String str = "geeksforgeeks";
char res = getSecondMostFreq(str);
if (res != '0')
System.out.println("Second most frequent char"+
" is " + res);
else
System.out.println("No second most frequent"+
5. 5
"character");
}
}
9.There aretwo sorted arrays.Firstoneis of sizem+n containingonly m elements. Another one is of size n and
contains n elements. Merge these two arrays into the firstarray of sizem+n such that the output is sorted.
class MergeArrays
{
/* Function to move m elements at the end of array mPlusN[] */
void moveToEnd(int mPlusN[], int size)
{
int i,j = size- 1;
for (i = size- 1; i >= 0; i--)
{
if (mPlusN[i] != -1)
{
mPlusN[j] = mPlusN[i];
j--;
}
}
}
/* Merges array N[] of sizen into array mPlusN[]
of sizem+n*/
void merge(int mPlusN[], intN[], int m, intn)
{
int i = n;
/* Current index of i/p part of mPlusN[]*/
int j = 0;
/* Current index of N[]*/
int k = 0;
while(k < (m + n))
{
if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n))
{
mPlusN[k] = mPlusN[i];
k++;
i++;
}
{
mPlusN[k] = N[j];
k++;
j++;
}
}
}
/* Utility that prints out an array on a line*/
void printArray(intarr[],intsize)
6. 6
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args)
{
MergeArrays mergearray = new MergeArrays();
/* Initializearrays */
int mPlusN[] = {2, 8, -1, -1, -1, 13, -1, 15, 20};
int N[] = {5, 7, 9, 25};
int n = N.length;
int m = mPlusN.length - n;
/*Move the m elements at the end of mPlusN*/
mergearray.moveToEnd(mPlusN, m + n);
/*Merge N[] into mPlusN[] */
mergearray.merge(mPlusN, N, m, n);
/* Printthe resultantmPlusN */
mergearray.printArray(mPlusN,m + n);
}
}
Output: 2 5 7 8 9 13 15 20 25
10. Given an array,and count n, rotate the array n times. Eg {1,2,3,4,5} and n = 2, output should be {3,4,5,1,2}
class leftrotate
{
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
{
int j, temp;
temp = arr[0];
for (j = 0; j < n - 1; j++)
arr[j] = arr[j + 1];
arr[j] = temp;
}
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
public static void main(String[] args)
{
7. 7
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
}}
Output :
3 4 5 6 7 1 2
11. Given an array of 0s,1s and 2s, arrangearray in increasingorder so that firstelements are 0s,then 1s and 2s.
// Java program to sortan array of 0, 1 and 2
import java.io.*;
class countzot{
// Sort the inputarray,the array is assumed to
// have values in {0, 1, 2}
static void sort012(inta[],intarr_size)
{
int lo = 0;
int hi = arr_size- 1;
int mid = 0,temp=0;
while(mid <= hi)
{
switch (a[mid])
{
case0:
{
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
lo++;
mid++;
break;
}
case1:
mid++;
break;
case2:
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(intarr[],intarr_size)
{
int i;
for (i = 0; i < arr_size;i++)
System.out.print(arr[i]+" ");
8. 8
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size= arr.length;
sort012(arr,arr_size);
System.out.println("Array after seggregation ");
printArray(arr,arr_size);
}
}
Output:
array after segregation 0 0 0 0 0 1 1 1 1 1 2 2
12. Programto count occurrence of a given character in a string
// JAVA programto count occurrences
// of a character
class GFG
{
// Method that return count of the given
// character in the string
public static intcount(Strings,char c)
{
int res = 0;
for (inti=0; i<s.length(); i++)
{
// checkingcharacter in string
if (s.charAt(i) == c)
res++;
}
return res;
}
// Driver method
public static void main(Stringargs[])
{
String str= "geeksforgeeks";
char c = 'e';
System.out.println(count(str, c));
}
}
Output: 4
Q 13 factorial of no.
9. 9
Ans:
1. class FactorialExample{
2. public static void main(String args[]){
3. int i,fact=1;
4. int number=5;
5. for(i=1;i<=number;i++){
6. fact=fact*i;
7. }
8. System.out.println("Factorial of "+number+" is: "+fact);
9. }
10. }
Q14 Fibonacci series
Ans:
1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Q15 Prime Number
Ans:
1. class PrimeExample{
2. public static void main(String args[]){
3. int i,m=0,flag=0;
4. int n=17;//it is the number to be checked
5. m=n/2;
10. 10
6. for(i=2;i<=m;i++){
7. if(n%i==0){
8. System.out.println("Number is not prime");
9. flag=1;
10. break;
11. }
12. }
13. if(flag==0)
14. System.out.println("Number is prime");
15. }
16. }
Q16 Bubble sort
Ans:
1. public class BubbleSortExample {
2. static void bubbleSort(int[] arr) {
3. int n = arr.length;
4. int temp = 0;
5. for(int i=0; i < n; i++){
6. for(int j=1; j < (n-i); j++){
7. if(arr[j-1] > arr[j]){
8. //swap elements
9. temp = arr[j-1];
10. arr[j-1] = arr[j];
11. arr[j] = temp;
12. }
13.
14. }
15. }
16.
17. }
18. public static void main(String[] args) {
19. int arr[] ={3,60,35,2,45,320,5};
20.
21. System.out.println("Array Before Bubble Sort");
22. for(int i=0; i < arr.length; i++){
23. System.out.print(arr[i] + " ");
24. }
25. System.out.println();
26.
27. bubbleSort(arr);//sorting array elements using bubble sort
28.
29. System.out.println("Array After Bubble Sort");
30. for(int i=0; i < arr.length; i++){
11. 11
31. System.out.print(arr[i] + " ");
32. }
33.
34. }
35. }
Q:17// Java program to illustrate to find a substring
// in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";
// Returns index of first occurrence of substring
int firstIndex = str.indexOf("Geeks");
System.out.println("First occurrence of char Geeks"+
" is found at : " + firstIndex);
// Returns index of last occurrence
int lastIndex = str.lastIndexOf("Geeks");
System.out.println("Last occurrence of char Geeks is"+
" found at : " + lastIndex);
// Index of the first occurrence
// after the specified index if found.
int first_in = str.indexOf("Geeks", 10);
System.out.println("First occurrence of char Geeks"+
" after index 10 : " + first_in);
int last_in = str.lastIndexOf("Geeks", 20);
System.out.println("Last occurrence of char Geeks " +
"after index 20 is : " + last_in);
}
}
Q 18:
Java program to illustrate how to find a substring
// in the string using contains
import java.io.*;
import java.lang.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// to be searched.
12. 12
String test = "software";
CharSequence seq = "soft";
boolean bool = test.contains(seq);
System.out.println("Found soft?: " + bool);
// it returns true substring if found.
boolean seqFound = test.contains("war");
System.out.println("Found war? " + seqFound);
// it returns true substring if found otherwise
// return false.
boolean sqFound = test.contains("wr");
System.out.println("Found wr?: " + sqFound);
}
}
Output:
Found soft?: true
Found war? true
Found wr?: false
Question: // Java program to illustrate to find a character
// in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a character
// to be searched.
String str = "GeeksforGeeks is a computer science portal";
// Returns index of first occurrence of character.
int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's'" +
" is found at : " + firstIndex);
// Returns index of last occurrence specified character.
int lastIndex = str.lastIndexOf('s');
System.out.println("Last occurrence of char 's' is" +
" found at : " + lastIndex);
// Index of the first occurrence of specified char
// after the specified index if found.
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 's'" +
" after index 10 : " + first_in);
int last_in = str.lastIndexOf('s', 20);
13. 13
System.out.println("Last occurrence of char 's'" +
" after index 20 is : " + last_in);
// gives ASCII value of character at location 20
int char_at = str.charAt(20);
System.out.println("Character at location 20: " +
char_at);
// throws StringIndexOutOfBoundsException
// char_at = str.charAt(50);
}
}
Q20 Reverse a string
Ans :
// Java program to Reverse a String by converting string to characters one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString
{
public static void main(String[] args)
{
String input = "GeeksForGeeks";
// convert String to character array
// by using toCharArray
char[] try1 = input.toCharArray();
for (int i = try1.length-1; i>=0; i--)
System.out.print(try1[i]);’’’
}
}
Output:
skeeGrofskeeG
Q21 duplicate character in string
How do you count the number of occurrencesof each character in a string?
import java.util.HashMap;
import java.util.Set;
class DuplicateCharactersInString
{
static void duplicateCharCount(String inputString)
{
14. 14
//Creating a HashMap containing char as key and it's occurrences as
value
HashMap<Character, Integer> charCountMap = new HashMap<Character,
Integer>();
//Converting given string to char array
char[] strArray = inputString.toCharArray();
//checking each char of strArray
for (char c : strArray)
{
if(charCountMap.containsKey(c))
{
//If char is present in charCountMap, incrementing it's count
by 1
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
//If char is not present in charCountMap,
//putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
//Getting a Set containing all keys of charCountMap
Set<Character> charsInString = charCountMap.keySet();
System.out.println("Duplicate Characters In "+inputString);
//Iterating through Set 'charsInString'
for (Character ch : charsInString)
{
if(charCountMap.get(ch) > 1)
{
//If any char has a count of more than 1, printing it's count
System.out.println(ch +" : "+ charCountMap.get(ch));
}
}
}
public static void main(String[] args)
{
duplicateCharCount("JavaJ2EE");
15. 15
duplicateCharCount("Fresh Fish");
duplicateCharCount("Better Butter");
}
}
22.Write a java program to remove all white spaces from a string.?
class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str = " Core Java jsp servlets jdbc struts hibernate
spring ";
//1. Using replaceAll() Method
String strWithoutSpace = str.replaceAll("s", "");
System.out.println(strWithoutSpace); //Output :
CoreJavajspservletsjdbcstrutshibernatespring
}
}
Q 23 Write a java program to check whethertwo stringsare anagram or not? USING HASHMAP
public class AnagramProgram
{
static void isAnagram(String s1, String s2)
{
//Removing white spaces from s1 and s2 and converting case to lower case
String copyOfs1 = s1.replaceAll("s", "").toLowerCase();
String copyOfs2 = s2.replaceAll("s", "").toLowerCase();
//Initially setting status as true
boolean status = true;
if(copyOfs1.length() != copyOfs2.length())
{//Setting status as false if copyOfs1 and copyOfs2 doesn't have same
length
status = false;}
else
16. 16
{
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < copyOfs1.length(); i++)
{
//Getting char from copyOfs1
char charAsKey = copyOfs1.charAt(i);
//Initializing char count to 0
int charCountAsValue = 0;
//Checking whether map contains this char
if(map.containsKey(charAsKey))
{
//If contains, retrieving it's count
charCountAsValue = map.get(charAsKey);
}
//Putting char and it's count to map with pre-incrementing
char count
map.put(charAsKey, ++charCountAsValue);
//Getting char from copyOfs2
charAsKey = copyOfs2.charAt(i);
17. 17
//Initializing char count to 0
charCountAsValue = 0;
//Checking whether map contains this char
if(map.containsKey(charAsKey))
{
//If contains, retrieving it's count
charCountAsValue = map.get(charAsKey);
}
//Putting char and it's count to map with pre-decrementing
char count
map.put(charAsKey, --charCountAsValue);
}
//Checking each character and it's count
for (int value : map.values())
{
if(value != 0)
{
//If character count is not equal to 0, then setting
status as false
status = false;
}
}
18. 18
}
//Output
if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}
public static void main(String[] args)
{
isAnagram("Mother In Law", "Hitler Woman");}
}}
Output :
Mother In Law and Hitler Woman are anagrams
24. Write a java program to reverse a given string with preserving the position of spaces?
public class MainClass
{
static void reverseString(String inputString)
{
//Converting inputString to char array 'inputStringArray'
char[] inputStringArray = inputString.toCharArray();
//Defining a new char array 'resultArray' with same size as
inputStringArray
char[] resultArray = new char[inputStringArray.length];
19. 19
//First for loop :
//For every space in the 'inputStringArray',
//we insert spaces in the 'resultArray' at the corresponding
positions
for (int i = 0; i < inputStringArray.length; i++)
{
if (inputStringArray[i] == ' ')
{
resultArray[i] = ' ';
}
}
//Initializing 'j' with length of resultArray
int j = resultArray.length-1;
//Second for loop :
//we copy every non-space character of inputStringArray
//from first to last at 'j' position of resultArray
for (int i = 0; i < inputStringArray.length; i++)
{
if (inputStringArray[i] != ' ')
{
//If resultArray already has space at index j then
decrementing 'j'
if(resultArray[j] == ' ')
{
j--;
}
resultArray[j] = inputStringArray[i];
j--;
}
}
System.out.println(inputString+" ---> "+String.valueOf(resultArray));
}
public static void main(String[] args)
{
reverseString("I Am Not String");
reverseString("JAVA JSP ANDROID");
reverseString("1 22 333 4444 55555");
}
}
20. 20
Output :
I Am Not String —> g ni rtS toNmAI
JAVA JSP ANDROID —> DIOR DNA PSJAVAJ
1 22 333 4444 55555 —> 5 55 554 4443 33221
25.How do you convert string to integer and integer to string in java?
public class StringToInteger
{
public static void main(String[] args)
{
String s = "2015";
int i = Integer.parseInt(s);
System.out.println(i); //Output : 2015
}
}
26.Write a code to prove that strings are immutable in java?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = "JAVA";
String s2 = "JAVA";
System.out.println(s1 == s2); //Output : true
s1 = s1 + "J2EE";
System.out.println(s1 == s2); //Output : false
}
}
27.is new String() also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");
System.out.println(s1); //Output : JAVA
s1.concat("J2EE");
System.out.println(s1); //Output : JAVA
21. 21
}
}
28 Write a code to checkwhether one string is a rotation of another?
public class MainClass
{
public static void main(String[] args)
{
String s1 = "JavaJ2eeStrutsHibernate";
String s2 = "StrutsHibernateJavaJ2ee";
//Step 1
if(s1.length() != s2.length())
{
System.out.println("s2 is not rotated version of s1");
}
else
{
//Step 2
String s3 = s1 + s1;
//Step 3
if(s3.contains(s2))
{
System.out.println("s2 is a rotated version of s1");
}
else
{
System.out.println("s2 is not rotated version of s1");
}
}
}
}
29.Write a java program to reverse eachword ofa givenstring?
Splitthe given inputString intowordsusingsplit() method. Thentake eachindividual word,reverse it
and appendto reverseString. FinallyprintreverseString.Below image shows code snippetof the same.
22. 22
public class ReverseEachWord
{
static void reverseEachWordOfString(String inputString)
{
String[] words = inputString.split(" ");
String reverseString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reverseString = reverseString + reverseWord + " ";
}
System.out.println(inputString);
System.out.println(reverseString);
System.out.println("-------------------------");
}
public static void main(String[] args)
{
reverseEachWordOfString("Java Concept Of The Day");
}
}
Output :
Java Concept Of The Day
avaJ tpecnoC fO ehT yaD
————————-
23. 23
// Java program to print all distint elements in a given array
import java.io.*;
class GFG {
static void printDistinct(int arr[], int n)
{
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// Check if the picked element
// is already printed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier,
// then print it
if (i == j)
System.out.print( arr[i] + " ");
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.length;
printDistinct(arr, n);
}
}
// JAVA Code for Find Second largest
// element in an array
class GFG {
/* Function to print the second largest
elements */
public static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
System.out.print(" Invalid Input ");
return;
}
first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i++)
{
/* If current element is smaller than
24. 24
first then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MIN_VALUE)
System.out.print("There is no second largest"+
" elementn");
else
System.out.print("The second largest element"+
" is "+ second);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {12, 35, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
Q: /* Function to print first smallest and second smallest
elements */
static void print2Smallest(int arr[])
{
int first, second, arr_size = arr.length;
/* There should be atleast two elements */
if (arr_size < 2)
{
System.out.println(" Invalid Input ");
return;
}
first = second = Integer.MAX_VALUE;
for (int i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] < first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second
25. 25
then update second */
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MAX_VALUE)
System.out.println("There is no second" +
"smallest element");
else
System.out.println("The smallest element is " +
first + " and second Smallest" +
" element is " + second);
}
/* Driver program to test above functions */
public static void main (String[] args)
{
int arr[] = {12, 13, 1, 10, 34, 1};
print2Smallest(arr);
}
}
Q: // Java code to find largest three elements
// in an array
class PrintLargest
{
/* Function to print three largest elements */
static void print2largest(int arr[], int arr_size)
{
int i, first, second, third;
/* There should be atleast two elements */
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than
first*/
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second)
{
third = second;
26. 26
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
System.out.println("Three largest elements are " +
first + " " + second + " " + third);
}
/* Driver program to test above function*/
public static void main (String[] args)
{
int arr[] = {12, 13, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
-------------------------Theory-----------------------------------
4. Various HTTP codes like2xx,3xx, 4xx, 5xx
i)200 OK, 201 Created, 202 Accepted ,203 Non-Authoritative Information
204 No Content, 205 Reset Content,206 Partial Content ,207 Multi-Status,208 Already Reported ,226 IM Used
ii)300 MultipleChoices,301 Moved Permanently,302 Found,303 See Other 304 Not Modified,305 Use Proxy,306
Switch Proxy,307 Temporary Redirect ,308 Permanent Redirect
iii) 400 Bad Request,401 Unauthorized (RFC 7235),
402 Payment Required,403 Forbidden,404 Not Found,405 Method Not Allowed,406 Not Acceptable,407 Proxy
Authentication Required (RFC 7235),408 Request Timeout,409 Conflict,,410 Gone
iv) 500 Internal Server Error,501 Not Implemented,502 Bad Gateway,503 Service Unavailable,504 Gateway
Timeout,505 HTTP Version Not Supported,506 VariantAlso Negotiates ,507 InsufficientStorage508 Loop Detected
,510 Not Extended ,511 Network Authentication Required
5.How to run failed test cases programmatically.UsingTestNG Selenium
-------------------JAVA Theory---------------------------------------------------------------------------------------------------------------------
1. What is class and objectin Java?
Classisa template ora blueprintthatdefinesthe state andbehaviorof the objectsitsupport.
Objectshave state andbehaviorasdescribed byitsclass. Objectisan instance of a class.
The difference betweenaclassandan objectisthat class iscreatedwhenthe program iscreatedbut
the objectsare createdat the run time.
classcName
{
consistsof variablesandmethods
}
27. 27
classc1 = newclass();
where c1 is the object
2. What is inheritance andtypesof inheritance?
A classacquiringpropertiesof anotherclassisknownasinheritance.
A classthat acquiresthe propertiesisknownassubclasswhere asa classwhose propertiesare being
acquiredisknownas superclass.
Subclasscan inheritonlyinstance membersof superclass.
There are 4 typesof inheritance.
a. Simple Inheritance :Where one classinheritsfromanotherclass.
b. MultiLevel Inheritance: Where once classis a subclassof a classand a superclassof another
class
c. Multiple Inheritance :Where aclass inheritsfrommore thanone superclass.Javadoesnot
supportMultiple Inheritance
d. Hierarchical Inheritance :A classhavingmore than one subclassisknownashierarchical
inheritance.
Eg. ClassC
{Voidtest1(){SOP(“test1”);}}
ClassD extendsC
{Voidtest2(){SOP(“test2”);}}
ClassRun
{PSVM()
{D d1=newD();
d1.test1();
d1.test2();}}
OUTPUT: test1test2
3. What is methodoverriding?
Methodoverridingmeansoverridingthe functionalityof amethodinitssubclass.If a subclasshas a
methodwithsame name andsame parametersas itssuperclassbutthe implementationis different,itis
knownas overridingthe method.
It isusedin runtime polymorphism
It isusedto change the implementationof the methodinitssubclass.
To do methodoverriding,the followingare necessary:
a. Havingan Is-A relationship
b. Methodmust have same name as itsparentclass
c. Methodmust have same parameterasits parentclass
Example :
28. 28
ClassA
{
Int a;
Voidprint()
{
System.out.println(“thisprintsaline”);
}
}
ClassB extendsA
{
Voidprint()
{
System.out.println(“thisismethod overriding”);
}
}
4. What is methodoverloading?
MethodoverloadingisaconceptinJava where twoor more methodsina classcan have same name but
the methodsignature orargumentsneedtobe different.The overloadedmethodsare bindedbythe
JVMat compile time itself.
5. Difference betweenmethodoverloadingandmethodoverriding?
a. In Methodoverloading,twoormore methodshave same name withinthe classwhile in
overriding,the subclasscanhave methodwithsame name.
b. The argumentsinoverloadinghave tobe different,where asinoverriding;the argumentsor
signature issame.
c. Methodoverloadinghappensatcompile time whereasmethodoverridinghappensatruntime.
6. What is abstract class?Explainitsfeatures.
Definingamethodwithonlymethoddeclarationisknownasabstractmethod.
The abstract methoddoesn’tspecifyabodyandit mustbe declaredusingthe ‘abstract’keyword.A
classdeclaredusing‘abstract’keywordisknownasabstract class.It can have onlyabstract methods,
only concrete methods,orbothabstract and concrete methods.
If any class hasan abstract method,itis compulsorytodefine the classasabstract.
We cannotcreate an instance of abstractclass.Hence the instance membersof abstractclasscannotbe
referred.
The subclassof abstract classalso must be abstract until andunlessitimplementsall the abstract
methodof the inheritedsuperclass.
Abstractmethodsare usedto specifymandatorybehaviorinsubclass.Subclassmustimplement
abstract methodsotherwisetheyneedtobe declaredasabstract as well.
29. 29
We can achieve generalizationbyusingabstractclass.Definingcommonbehaviorforsubclassesis
knownas generalization.
7. What is interface?Howdoesitdifferfromabstractclass?
An interface isacollectionof abstractmethods.A classimplementsaninterface therebyinheritingthe
abstract methodsof the interface.
An interface onlyhasabstractmethodswhile anabstractclasscan have abstract as well asconcrete
methods.
We cannotinstantiate aninterface,while we candoso withabstractclass.
An interface doesnothave anyconstructors.
An interface cannotbe extendedby aclass,it can onlybe implemented.
An interface canextendmultiple interfaces.
Classcan extendonlyone class;however,interfacescanimplementmultipleinterfaces.
8. What is typecastinginJava.Explaindatatype castingandclasstypecasting.
Castingone type of informationtoanothertype of informationisknownastype casting.There are two
typesof typecasting:
a. Datatype casting
b. Classtype casting
In datatype casting,we can cast data type to another. There are two typesof data type casting:
Narrowing
Widening
Whena lowerdatatype iscastedto a higherdatatype,itisknownas widening.
A compilercanimplicitlydowidening.
Ex an intcan be typecastedintodoubleimplicitlybycompiler.
Whena higherdatatye iscastedintoa lowerdatatype,itisknownasnarrowing.Itneedstobe done
explicitly.
Ex double iscastedtoint.
Castingone classtype to anotherisknownas class type casting.
A classcastingis possible onlyif the classesare havingIs-A relationship.
There are twotypesof casting:
a. Upcasting
b. Downcasting
30. 30
Castingsubclassobjecttosuperclasstype isknownasupcasting.Subclassobjectbehavesassuperclass.
It will notshowthe propertiesof subclass.
Castingsuperclasstype tosubclasstype isknownasdowncasting.Downcastingispossibleonlyif the
objectisupcasted.
Q:singletoninselenium:
public class WebDriverSingleton {
public static WebDriver driver;
public static WebDriver getInstance() {
if (driver == null) {
driver = new FirefoxWebDriver();
}
return driver;
}
}
10. What ispolymorphism?Explainhowtoachieve polymorphismwithexample.
An objectshowingdifferentbehavioratdifferentstagesof itslifecycleisknownaspolymorphism.
There are twotypesof polymorphism:
Compile time polymorphism:Whenthe methoddeclarationisbindedtomethoddefinitionbycompiler,
it isknownas compile time polymorphism.
Whenthe methoddeclarationisbindedtomethoddefinitionatthe time of objectcreationbyJVMat
runtime,itisknownas runtime polymorphism.
To achieve polymorphism,three thingsare needed:
Inheritance
MethodOverriding
Up Casting
Example :
Interface Demo
{
Voiddisp();
Voidprint();
}
ClassSample implementsdemo
{
Voiddisp()
{
Sop (“inside disp”);
}
31. 31
Voidprint()
{
Sop(“insideprint”);
}
}
PublicclassMClass
{
Psvm
{
Demod;
D = newsample();
d.disp();
d.print();
}
}
11. What isabstractionand howto achieve it?
Abstractionisthe processof hidingthe implementationof classfromitsusage.
It definesthe functionalityof the objectbutdoesnotdefineinwhichclassthe implementationisdone.
To achieve abstractionwe needtodothe following:
a. Generalize the behaviorof the classesinaninterface.
b. Implementthe behaviorinthe subclass
c. Create a ref variable of interface anduse itto create objectsof subclass
By usingabstraction,we achieve loosecouplingbetweenimplementationandusage.
Loose couplingwill have three layers:
a. ImplementationLayer - where the objectbehaviorisdefined
b. ObjectcreationLayer– where the objectIscreated
c. Objectutilization –where the behaviorof objectusedwithoutknowingthe objectcreated
12. What isencapsulation?
Encapsulationisthe processof binding the memberstoitsclassor interface.
Memberscannotbe accessedwithoutusingclassname orinterface name.The membersof aclasscan
be restrictedupto 4 levels:
a. Private
b. Package
c. Protected
d. Public
In Private level,the memberscanbe accessed withinaclass.The private membershave the lowest
visibility
32. 32
Package level memberscanbe accessedacrossany classin the package.It cannotbe accessedfrom
outside the package
Protectedlevelmembershave the visibilitytill package level howevertheycanbe accessedfromoutside
usinginheritance.
Publicmemberscanbe accessedfromanywhere.Ithasmore visibilitythananyotheraccessspecifier.
13. Can a constructor be declaredasprivate?
Yes.To protect itfrom beingsubclassed.Noclass can extenditbecause thentheycannotcall super();
Also, tohave a control oninstantiationof anobjectof the class.
14. Differencebetweenpackage level andprotectedlevelaccessspecifier?
Package level hasvisibility uptopackage and noone from outside itcanaccess it.Protectedmembers
have visibility uptopackage level butcanbe accessedfromoutside usinginheritance.
15. Explainthe featuresof Stringclassandwhatis immutable?
Newoperatorisnot requiredto create an objectof Stringclass.Whenthe stringis declaredusing
double quotesJVMcreatesanobject.
In Java,there isno datatype tostore stringsinsteaditprovidesaclassbythe name String tohandle a set
of characters
Stringclassis a memberof java.langpackage
In String,objectscanbe createdusingtwo ways:
a. Usingnewoperator
b. Usingdouble quotes(““ ) ;
Stringclassis a final class,itcannot have subclasses
It isan immutable class.Anyobjectwhose valuecannotbe changedaftercreationisknownas
immutable.
Once we assigna value toa stringobject,we cannotreassignit.If we try to reassignit,it will notmodify
the objectbut create a newone.
16. What isan array inJava? Explaintypesof array.
An array isa collectionof similartypesof elementswhereeachelementisstoredcontinuouslyinthe
memory.
Theyare referredthroughitsindex.Index rangesfrom0to length-1
There are twotypesof arrays:
a. Primitive
b. Reference
33. 33
Array of primitive type storesthe primitive datatypeswhile arrayof reference type isusedtostore
objectsof the class.An array of reference type will alwayshave addressof the objects.
If we declare anarray of objectclass,itcan holdany type of java objectinit.
It has followinglimitation:
a. Size isrestricted/limited
b. Array isusedto store onlysimilartypesof elements
c. Array lengthwill notreturnthe exactnumberof elementsstoredinarraybutwill returnthe
total memoryinitialized.
17. What iscollectionAPI?Whyisitused?
Collectionsare usedtostore anytype of data objects.The size of collectionsgrowsdynamicallyatthe
run time.
Collectionsreturnsthe exactnumberof objectsstoredinitandnot the memoryallocated.
Each elementstoredincollectionare castedintoobjecttype. Whenwe retrieve objectfromcollection,
it still isinobjecttype andwe needtodowncastit to use the features.
3 types: set,queue,list
18. Explainfeaturesof list,queue,set.
a. List : It storesanytypesof elements
a. Elementsare all indexed
b. Referselementsbyusingindex
c. Duplicate andnull elementsare allowed
b. Queue : It isalsoa type of collectionandstoresanytypesof elements
Elementsare storedwithoutindex
TheyfollowFIFO
Duplicatesare allowedbutnull isnotallowed
Java haspriorityqueue where peekmethodisusedtoretrievethe header while poll methodis
usedto retrieve andremove the headerelement
c. Set: Itstoresany typesof elements
Elementsare notindexed
Duplicatesare notallowed
Null isallowed
Elementsare retrievedusingIterator
19. What ismap? How isit differentfromothercollections?
Elementsare storedinkeyvalue pair
Keycan be any object
Value canbe anyobject
Keyshouldbe unique
Keyismappedto value andisusedas an index.
20. What isa linkedlist?Explainitsfeatures.
34. 34
The linkedlistclassimplementsthe listinterface.Ithastwoconstructorsone isthe defaultone which
buildsanemptylinkedlist.
It acts both as a listas well asqueue
LinkedList()
Secondisa linkedlistthatisinitializedwiththe elementsof collectionc
LinkedList(Collectionc)
LinkedListhasvariousmethodslike add,remove,poll,peek,getfirst,getlast,etc
21. Differencebetweensetandqueue andlist?
Null :List, Set
Duplicates:List,Queue
Index :List
In queue(),elementsare retrievedusingpeekorpoll method,whileinsetelementsare retrievedusing
iterator
22. What isiterator?Explainitsbehaviorandwhenitshouldbe used?
We needtocreate an iteratorobjectto accessset elements.
It has 3 methods:
Next() – getsthe nextelementinset
hasNext() –checksif nextelementexistsornot
remove() - removesthe currentelement
23. What isexception?Whentouse exceptioninjava?
An exceptionisanerror which occursduringruntime of program that disruptsthe normal flow of the
program.
An exceptioncanbe due to variousof reasonslike incorrectuserinput, file notfound,etc.
There are twotypesof exceptions:
a. Checkedexception:These kindsorexceptionsare checkedatcompile time bycompiler.The
compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows
keyword.
b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile
time sowe are not forcedto handle orspecifythe exception
In java,undererrorand runtime exceptions,theyare uncheckedexceptionsrestall are checked
exceptions.
24. What isspecificexceptionandgenericexceptionhandler?Whenshouldwe use both?
Base class of exceptionhierarchydoesnotprovide anyspecificinformationaboutthe error.Thatiswhy
Exceptionclasshasmanysubclasseslike IOExceptionetc.We shouldalwaysthrow specificexceptionsso
that the callerwill knowthe rootcause of the error andalsodebuggingbecomeseasy.
35. 35
Whenwe are unsure if anyexceptionsmightoccur,inthatcase we coulduse genericexceptions.
25. What ischeckedand uncheckedexception?
a. Checkedexception:Thesekindsof exceptionsare checkedatcompile time bycompiler. The
compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows
keyword.
b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile
time sowe are not forcedto handle orspecifythe exception
26. Differencebetweenthrow,throwsandthrowable.
Throwable isthe superclassforerrorsandexceptionswhile throw andthrowsare keywords.
Throwsis a postmethodmodifierwhichspecifieswhichkindof exceptionsmaybe thrownbythe
method.
Throw isusedto throwan exceptionandrequiresasingle argumentwhichisaninstance of Throwable
or its subclass.
27. What isstream?Explaintypesof stream.
Streamsrepresentaninputsource andan outputdestinationinJava.A streamcan be defined asa
sequence of data.There are two typesof streams:
a. Inputstream
b. Outputstream.
Inputstreamis usedtoread the data fromthe source while the outputstreamisusedtowrite the data
to the destination.The outputstreamwritestothe destinationat one characterat a time.
29. Differencebetweenstaticandinstance objects?
Staticmembersare not a part of object;however, instance variablesare partof object.
Staticmembershave onlysingle copyof theminthe memory,howeverinstance variablescanhave
multiple copiesof theminthe memory.
To use the instance variable,we needtocreate areference of anobject.
30. What isprimitive variable andreference variable?
In java,there are two typesof variables,namelyprimitive variable andreference variable.
Primitive variablesare usedtostore primitive dataandisdeclaredusingdatatype.
Reference variable are declaredusingclassorinterface name.Itisusedto store an objectof a class.
31. What isa constructor?Why isit required?
36. 36
Constructorsare usedtocreate an instance of the class.OR constructoris a bitof code that allowsusto
create an objectof the class.
There are twotypesof constructorsi.e.defaultconstructorandparameterizedconstructor.
Defaultconstructorsdonot have anyargumentswhile parameterizedconstructorscanhave one or
more than one argument.
If there is noconstructor definedinaclass,the compilercallsthe defaultconstructorimplicitly.
32. What isa defaultconstructorandwhen isitcreated?
In absence of the constructorsthat a programmerexplicitlycreates,the compilerimplicitlycreatesa
defaultconstructorwithzeroparametersandinitializesall the instance variablestodefaultvalues.
33. What isconstructor overloading?
Constructoroverloadingallowsustohave more than one constructorina classwithdifferent
arguments.
Once we explicitlyprovideconstructortoa class,compilerwill notadddefaultconstructortothe class.
34. What isuse of ‘this’keyword inJava?
Withinaninstance methodora constructor,thiskeywordpointstothe currentobjectbeingcalled.
OR
It isa reference variable thatpointstothe currentobject.
35. Why doesJavanot supportmultiple inheritances?
a. Subclass constructorcannot have more thanone super();
b. The objectclass memberscannotbe inheritedintothe subclassinmore thanone pathwith
differentdefinitionssince itwill create ambiguity.Itisalsoknownasdiamondproblem.
36. What isthe difference betweenthisandsuper?
Thisis usedtoreferto the current object,while superisusedtocall the constructor of superclass.
Superiscalledimplicitlyif itisnotcodedbyprogrammerwhile itisnot the case withthis().
37. What isconstructor chaining?Whenithappens?
Callinganotherconstructorof same classfrom anotherconstructoriscalledconstructorchaining.We
use this() toachieve constructorchaining.
38. Differencebetweenmethodsandconstructors?
37. 37
40. Thiskeyword
Thisis a keywordusedtoaccessnon-staticmembersof the class.
Thisis alsousedto call otherconstructorsof the same class.
Call to Thismust be the firststatementinsidethe constructor.
Eg. ClassBox
{
Int width;
Stringcolour;
Box(intw,Stringc)
{width=w;
Colour=c;}
Box(intw)
{this(w)
Colour=c}
}
Voidprint()
{
SOP(w);
SOP(c);
}
Classrun
{PSVM()
{
Box b1=new Box(4);
B1.print();
Box b2=new Box(10,”green”);
B1.print();
}
}
OUTPUT: 4 Null 10 green
--------------------------------------------------------------------------------------------------------------------------------------------------------
Q. SQL : Inner join query
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Difference between drop, truncate and delete
–> DELETE:
1. Removes Some or All rows froma table,WHERE clause can be used.Canbe rolledback
38. 38
> TRUNCATE:
1. Removes All rowsfroma table,Nowhere clause canbe used.,cannotbe rolledback
DROP
Commandremovesatable fromthe database.All the tables'rows,indexesandprivilegeswill alsobe
removed.NoDML triggerswill be fired.The operationcannotbe rolledback.
1. Create test data for checkout page of a ecommerce website. (Vlocity)
2. Create a test plan for whatsapp group (Amazon)
3. Create test data for a zomato likeapp where top 3 restaurants arelisted in the 5 km vicinity.Filters arefood
type and pincodeand GPS Coordinates (Amazon)
4. Explainingmostdifficulttestingrelated problem that occurred in your projectand how did you solveit.
(Groupon)
Q Rest assured advantages:
Rest-Assured isaJavabasedDSL (DomainSpecificLanguage) whichismostcommonlyusedtotestout
REST basedservices.Rest-Assuredpresentsagreatadvantage because itsupportsmultiple HTTP
requestsandcan validate and/orverifythe responsesof these requests.Thesemultiple requestsinclude
GET, POST,PUT, DELETE, PATCH,OPTIONSandHEAD methods.Giventhatitsupportsthese various
requests,italsoallowsforthemtobe constructedwithmultipleparameters,headers,andtheir
respective body,aswell asvalidatingresponse’sstatuscode,headers,cookiesandresponse time.
https://gorillalogic.com/blog/automation-testing-part-2-api-testing-rest-assured/
Hashmap Factorisation
Q:Types of authentication in api testing : OAuth2.0, OAuth1.0, Q:PUT vs. POST in REST We use Modify
HeaderValue (HTTPHeaders) ,tool usedModifyHeaderValue,headername iv-user,headervalue
archanasingh What isAuthenticationandHow doesAuthenticationworksinRESTWebServices
Q:Authentication
Authentication is a process to prove that you are the person who you intend to be.
http://toolsqa.com/rest-assured/authentication-authorization-rest-webservices/ Filehandling..2 file..fetch value
Q:static import in java
Static import. Static import is a feature introducedinthe Javaprogramminglanguage thatallows
members(fieldsandmethods) definedinaclassas public static to be usedin Java code;without
specifyingthe classinwhichthe fieldisdefined.Thisfeature wasintroducedintothe language inversion
5.0.
Q:What is a Wrapper class
39. 39
As we are not able to use Primitive Data Types as objects directly in Java Programming
language, we can use Wrapper Class to wrap the Primitive Data Types into objects. Hence
Wrapper Classes are used, to wrap the primitive type into an object, so that we can use the
Primitive Data Type as an object.
Wrappermethods
The solutiontothisproblemliesinusingwrappermethodsforthe standardSeleniummethods.So
insteadof doingthiseverytime Ineedtoperforma click:
?
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(By.id("loginButton")));
driver.findElement(By.id("loginButton")).click();
I have created a wrapper method click() in a MyElements class that looks like this:
?
public static void click(WebDriver driver, By by) {
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(by));
driver.findElement(by).click();
}
Of course, the 10 second timeout is arbitrary and it’s better to replace this with some constant
value. Now, every time I want to perform a click in my test I can simply call:
?
MyElements.click(driver, By.id("loginButton");
which automatically performs a WebDriverWait, resulting in much stabler, better readable and
maintainable scripts.
Ex:
Extending your wrapper methods: error handling
Using wrapper methods for Selenium calls has the additional benefit of making error handling
much more generic as well. For example, if you often encounter a
StaleElementReferenceException (which those of you writing tests for responsive and dynamic
web applications might be all too familiar with), you can simply handle this in your wrapper
method and be done with it once and for all:
40. 40
?
public static void click(WebDriver driver, By by) {
try {
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(by));
driver.findElement(by).click();
catch (StaleElementReferenceException sere) {
// simply retry finding the element in the refreshed DOM
driver.findElement(by).click();
}
}
Q: How to clonean object in java
The clone() methodof Objectclassis usedto clone an object.The java.lang.Cloneable interface mustbe
implementedbythe classwhose objectclone we wantto create.If we don'timplementCloneable
interface, clone() methodgeneratesCloneNotSupportedException.The clone()methodisdefinedinthe
Objectclass.
Q: Unboxing and Autoboxing in java
Comparable vs Comparator in Java
Java provides two interfaces to sort objects using data members of the class:
1. Comparable
2. Comparator
Using Comparable Interface
A comparable object is capable of comparing itself with another object. The class itself must
implements the java.lang.Comparable interface to compare its instances.
Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list
of Movies based on year of release. We can implement the Comparable interface with the Movie
class, and we override the method compareTo() of Comparable interface.
8.3 2015
Now, suppose we want sort movies by their rating and names also. When we make a collection
element comparable(by having it implement Comparable), we get only one chance to implement
the compareTo() method. The solution is using Comparator.
41. 41
Using Comparator
Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate
class. We create multiple separate classes (that implement Comparator) to compare by different
members.
Collections class has a second sort() method and it takes Comparator. The sort() method invokes
the compare() to sort objects.
To compare movies by Rating, we need to do 3 things :
1. Create a class thatimplementsComparator(andthusthe compare() methodthatdoesthe work
previouslydonebycompareTo()).
2. Make an instance of the Comparatorclass.
3. Call the overloadedsort() method,givingitboththe listandthe instance of the class that
implementsComparator.
Comparable ismeantfor objectswithnatural orderingwhichmeansthe objectitself mustknow
how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface
sorting is done through a separate class.
Logically, Comparable interface compares “this” reference with the object specified and
Comparator in Java compares two different class objects provided.
If any class implementsComparable interface inJavathen collectionof that objecteitherListor
Array can be sortedautomaticallybyusingCollections.sort() orArrays.sort() methodandobjects
will be sorted based on there natural order defined by CompareTo method.
To summarize, if sorting of objects needs to be based on natural order then use Comparable
whereas if you sorting needs to be done on attributes of different objects, then use Comparator
in Java.