Java Programs Interview Questions
Java Programs Interview Questions
Q. How do you swap two numbers without using a third variable in Java?
public static void main(String[] args) {
int a = 10;
int b = 20;
[Link]("a is " + a + " and b is " + b);
a = a + b;
b = a - b;
a = a - b;
for(int i=low;i<=high;i++)
{
if(isprime(i))
[Link](i);
}
}
public static boolean isprime(int num)
{
if(num==0 || num==1)
{
return false;
}
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
}
else
{
arr[i]=0;
}
for(int j=i+temp;j<[Link];j=j+temp)
{
arr[j]=0;
}
}
}
}
public static boolean myfunction(int a)
{
for(int i=2;i<a/2;i++)
{
if(a%i==0)
{
return false;
}
}
return true;
}
[Link] HYPERLINK
"[Link]
interview-questions" a Java program to print a Fibonacci sequence using
recursion.
A Fibonacci sequence is one in which each number is the sum of the two previous numbers
for(int i=1;i<=num;i++)
{
[Link](a+" ");
a=b;
b=c;
c=a+b;
}
}
OR
public static void printFibonacciSequence(int count) {
int a = 0;
int b = 1;
int c = 1;
a = b;
b = c;
c = a + b;
}
}
[Link] HYPERLINK
"[Link]
interview-questions" do you check if a list of integers contains only odd
numbers in Java?
[Link] HYPERLINK
"[Link]
interview-questions" can you find the factorial of an integer in Java?
Arrays:
Q. Write Java program that checks if two arrays contain the same elements.
Integer[] a1 = {1,2,3,2,1};
Integer[] a2 = {1,2,3};
Integer[] a3 = {1,2,3,4};
[Link](sameElements(a1, a2));
[Link](sameElements(a1, a3));
}
[Link] HYPERLINK
"[Link]
interview-questions" do you get the sum of all elements in an integer array
in Java?
for(int i : arr)
{
sum=sum+i;
}
[Link](sum);
}
[Link] HYPERLINK
"[Link]
interview-questions" do you find the second largest number in an array in
Java?
for(int i : arr)
{
if(i>highest) {
SecondHighest = highest;
highest = i;
}
else if (i>SecondHighest) SecondHighest = i;
}
}
[Link] HYPERLINK
"[Link]
interview-questions" do you sort an array in Java?
for(int i=[Link]-1;i<[Link];i--)
{
if(i<0) return;
[Link](arr[i]);
}
Strings:
StringBuffer Methods: append(str)
insert(1,char or str)
delete(start,end)
deleteCharAt(index)
length()
reverse()
toString()
String methods:
charAt() - Returns the character at the specified index (position)
[Link](); [Link]();
[Link]();
[Link](); [Link](); [Link]();
[Link](); [Link](); [Link]();
str=[Link]();
String words[] = [Link](" ");
for(int i=0;i<[Link];i++)
{
count =1;
for(int j=i+1;j<[Link];j++)
{
if(words[i].equals(words[j]))
{
count++;
[Link](words[j]);
// Set words[j] to 0 to avoid printing visited word
words[j]="0";
}
}
if(count>1 && words[i]!="0")
{
[Link](words[i]);
}
}
}
[Link] to find out the length of the string without using length function
}
OR
public static void main(String a[])
{
String st= "WelcomeztozInfosys";
char[] arr = [Link]().toCharArray();
OR
if(StartIndex!=-1)
{
int endIndex=StartIndex+[Link]();
StringBuffer sb=new
StringBuffer([Link](StartIndex,endIndex));
[Link]();
Q. Program to Get the number of letters , alphabets and others in you gmail
account?
public static void main(String[] args) throws Exception {
char[] arr=[Link]();
[Link]([Link]());
if([Link](regexp)) [Link]("Success");
else [Link]("Failed");
}
----OR-----
public static void main(String[] args) {
[Link]("Hello, World!");
String password="Alisayed@578";
String regexp="^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$%^&+=])(?
=\\S+$).{8,12}$";
Pattern pattern=[Link](regexp,Pattern.CASE_INSENSITIVE);
Matcher matcher=[Link](password);
if([Link]()) [Link]("Success");
else [Link]("Failed");
}
if([Link](regexp)) [Link]("Success");
else [Link]("Failed");
}
str=[Link]("\\s", "");
[Link]("After Removing thespaces: "+str);
}
Q. Program to get only characters or digits or special characters from a String?
String letters=[Link]("[^a-zA-Z]","");
[Link](letters+" size is "+[Link]());
String digits=[Link]("[^0-9]","");
[Link](digits+" size is "+[Link]());
String space=[Link]("[^\\s]","");
[Link](space+" size is "+[Link]());
String specialChars=[Link]("[^@#$%&*_-]","");
[Link](specialChars+" size is "+[Link]());
[Link] HYPERLINK "[Link]
programming-interview-questions" do you remove leading and trailing spaces
from a string in Java?
[Link](str1); // bcdABCDbcdABCD
}
while([Link]())
{
String line = [Link]();
if([Link](str))
{
[Link]();
return true
}
}
[Link]();
return false;
}
Collections:
Q. What datatype can be added to a List?
Collections : Collections is a class that provides the static methods which can be used
for varies operations on a Collection.
Collection Methods:
[Link]() [Link](array,[Link]());
[Link](List)
[Link](List)
[Link](List,from,To);
Collections Class will be used to sort and synchronize the collection elements.
Insertion Random Null
DataStructure extends impliments Duplicates Order Access Synchronized Values
Abstract List
ArrayList Class List Allow Yes Yes No Yes
Abstract List
LinkedList Class List Allow Yes Yes No Yes
One Null
HashSet AbstractSet Set No No No No Value
One Null
LinkedHashSet HashSet Set No Yes No No Value
Not Keys, Only one Null
HashMap AbstractMap Map values No No No Key
Not Keys, Only one Null
LinkedHashMap HashMap Map values Yes No No Key
ArrayList:
Its inherited from Abstract List class and implements List Interface.
Follows Insertion Order
Its allows us to access the list randomly
Size of the list will be increased as the collection grows
It is not Synchronized.
[Link]("IPA");
[Link]("STI");
[Link]("STO");
intercept [Link]("DEP");
if ([Link] (scanMenu))
Methods:
Add(str) : Appends the specified element to the end of this list
Add(index,str) : Inserts the specified element at the specified position in this list
Clear() : Removes all of the elements from this list (optional operation).
The list will be empty after this call returns.
Contains(Object) : Returns true if this list contains the specified element
Get(index) : Returns the element at the specified position in this list.
indexOf(Object) : Returns the index of the first occurrence of the specified element
in this list Returns the index of the first occurrence of the specified element in this list
iterator() : Returns an iterator over the elements in this list in proper
sequence.
equals(Object 0) : Compares the specified object with this list for equality.
Remove(index) : Removes the element at the specified position in this list
Remove(Object) :Removes the first occurrence of the specified element from this
list
removeAll(list) : Removes from this list all of its elements that are contained in the
specified collection
set(index,str) : Replaces the element at the specified position in this list with the
specified element
size() : Returns the number of elements in this list.
subList(frmIndex,ToIndex) : Returns a view of the portion of this list between
the specified fromIndex, inclusive, and toIndex.
HashMap:
Hashmap is implemented form the Map interface
Hashmap does not allows duplicate Keys but allows duplicate values
Hashmap allows one null key but it allows many null values
Hashmap is not an ordered collection
Methods:
Clear():Removes all of the mappings from this map
ContainsValue(object)
entrySet(): Returns set of Keys
equals(Object): Compares the specified object with this map for equality. Returns true
if the given object is also a map and the two maps represent the same mappings.
Get(Object Key): Returns the value to which the specified key is mapped
keyset():Returns a Set view of the keys contained in this map
put(key,value): Associates the specified value with the specified key in this map
remove(key)
remove(key,value):
replace(key,value):
size();
toString();Returns a string representation of the object.
Set Examples:
public static void main(String a[])
{
WebDriver driver = new ChromeDriver();
Set<String> ids= [Link]();
Iterator<String> itr =[Link]();
String parentID=[Link]();
String chidID = [Link]();
[Link]().window(chidID);
[Link]([Link]());
[Link]().window(parentID);
}
Q.A particular list of buttons are there?Write the xpath for it?
[Link]([Link]("String"));
[Link](1);
[Link](2);
[Link](3);
LinkedList<Integer> rev= new LinkedList<Integer>();
for(int i=[Link]()-1; i>=0;i--)
{
[Link]([Link](i));
}
}
[Link] HYPERLINK
"[Link]
interview-questions" do you merge two lists in Java?
[Link](list2);
[Link](list1);
}
Q. Converting Set to List without changing the order?
int n = [Link]();
List<String> aList = new ArrayList<String>(n);
for (String x : s)
[Link](x);
[Link] HYPERLINK
"[Link]
interview-questions" a Java program that sorts HashMap by value.
[Link]("David", 95);
[Link]("Jane", 80);
[Link]("Mary", 97);
[Link]("Lisa", 78);
[Link]("Dino", 65);
[Link](scores);
scores = sortByValue(scores);
[Link](scores);
}
[Link] HYPERLINK
"[Link]
interview-questions" do you compile and run a Java class from the
command line?
$ javac [Link]
$ java Test
[Link]("[Link]", "localhost");
[Link]("[Link]", "mkyong");
[Link]("[Link]", "password");
[Link](fos, null);
[Link]([Link]("[Link]"));
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
}
Q. program for reading a excel file
Shortcuts:
FileInputStream(path)
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = [Link](0);
Row =[Link](1);
Cell = [Link](1);
[Link](cell);
[Link]([Link](3));
[Link]([Link]());
Calendar cal=[Link]();
SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");
//Incrementing the Date
String currentDate=[Link]([Link]());
}
}
Regular Expressions:
Meta characters
. : Matches any single character, except newline characters.
^ : Asserts the start of a line.
$ : Asserts the end of a line.
| : Acts as a logical OR operator.
Character Classes
[abc] : Matches any one of the characters a, b, or c.
[^abc] : Negates the set; matches any character except a, b, or c.
[a-zA-Z]: Specifies a range, matching any letter from a to z or A to Z.
Predefined Character Classes
\\d : Matches any digit, equivalent to [0-9].
\\D : Matches any non-digit.
\\s : Matches any whitespace character.
\\S : Matches any non-whitespace character.
\\w : Matches any word character (alphanumeric & underscore).
\\W : Matches any non-word character.
Quantifiers
`` :Zero or more times.
+: :One or more times.
?: :Zero or one time; also used to denote a non-greedy quantifier.
{n}: :Exactly n times.
{n,} :n or more times.
{n,m} :Between n and m times, inclusive.
Special Constructs
(abc) : A capturing group that matches the sequence abc.
(?:abc): A non-capturing group.
(?i)abc: An inline flag for case-insensitive matching of abc.
\\\\b : A word boundary.
\\\\B : A non-word boundary.
Backreferences
\\\\1, \\\\2, ... : Matches the same text as previously matched by a capturing
group.
Boundary Matchers
^ : Matches the beginning of a line.
$ : Matches the end of a line.
\\\\b : Matches a word boundary.
\\\\B : Matches a non-word boundary.
Flags
(?i) : Enables case-insensitive matching.
(?s) : Enables dot-all mode, where . matches any character, including newline
characters.
Anchors
\\\\A : Matches the beginning of the input.
\\\\Z : Matches the end of the input, or before a newline at the end.
\\\\z : Matches the end of the input.
Logical Operators
(?=...) : Positive lookahead assertion.
(?!...) : Negative lookahead assertion.
(?<=...): Positive lookbehind assertion.
(?<!...) : Negative lookbehind assertion.