2.interview Prep - JAVA
2.interview Prep - JAVA
What are primitives and wrapper classes? Implicit and explicit casting?
● Primitive: It is simply just a container to keep/store data. Boolean, byte, char, int, float,
double, long, short.
● Wrapper Class: Every primitive has a wrapper class. A Wrapper class is a class whose
object wraps or contains primitive data types. When we create an object to a wrapper
class, it contains a field and in this field, we can store primitive data types. In other words,
we can wrap a primitive value into a wrapper class object.
● Java Type Casting is classified into two types.
○ Widening Casting (Implicit) – Automatic Type Conversion
○ Narrowing Casting (Explicit) – Need Explicit Conversion
In my project:
● Driver Class: In my project I have a Driver class where I define the constructor
private since I don’t want anyone to create any object out of it.
Pass-by-Value vs Pass-by-Reference
● Java is a “pass-by-value” language. This means that a copy of the variable is made and the
method receives that copy. Assignments made in the method do not affect the caller.
public static void main(String [] args) {
int num =4;
newNumber(num);
System.out.println(num); // 4 }
static void newNumber(int num) {
Num =7; }
● Finalize(): this is a method coming from Object class inherited to every class.
○ Used by the garbage collector to perform some final operations or clean up
operations on an object before it is removed from the memory.
● Overriding:
○ Happens in the child class. It is called dynamic binding.
○ Same method name and same parameters (same method signature).
○ Must have the same or sub return type.
○ We cannot override static methods, we can only hide them.
○ Access modifiers can only be the same or more visible.
○ Private methods cannot be overridden since they are not inherited.
○ Final methods cannot be overridden since they are final, cannot be changed.
○ In my project: I override .toString(), .equals(), and .hashCode() methods.
● Overloading:
○ Happens in the class nesting the method or in the inherited methods. It is called
static binding.
○ Same method name but different parameters.
○ Return type can be different.
○ We can overload static methods.
○ Access modifiers can be different.
○ Final methods can be overloaded in the same class.
○ In my project:
In the BrowserUtils, I have methods like:
public static WebElement waitForVisibility(WebElement element, int timeToWaitInSec) {
WebDriverWait wait = new WebDriverWait(Driver.get(), timeToWaitInSec);
return wait.until(ExpectedConditions.visibilityOf(element)); }
○ Random access: We can get any data located at any index position.
● Disadvantage of Java Array:
○ Size Limit: It is not dynamic so it is not resizable.
○ TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order.
○ It is substantially slower than HashSet.
3. QUEUE - Interface:
A Queue is designed in such a way so that the elements added to it are placed at the end of Queue
and removed from the beginning of Queue. The concept here is similar to the queue we see in our
daily life, for example, when a new iPhone launches we stand in a queue outside the apple store,
whoever is added to the queue has to stand at the end of it and persons are served on the basis of
FIFO (First In First Out), The one who gets the iPhone is removed from the beginning of the
queue. The Queue interface in Java collections has two implementations: LinkedList and
PriorityQueue, these two classes implement Queue interface.
MAP Interface: A Map is an object that maps keys to values. A map cannot contain duplicate keys.
Both key and value do not support primitives. There are three main implementations of Map
interfaces: HashMap, TreeMap, and LinkedHashMap.
● HashMap: - class
○ It is NOT an ordered collection which means it does not return the keys and values
in the same order in which they have been inserted into the HashMap.
○ It does NOT sort the stored keys and Values.
○ Accepts only one null key but any number of null values.
● LinkedHashMap: - class
○ maintains the insertion order as it is doubly linked. It has a faster iteration.
○ put() & remove() are faster than hashmap // modifying the data.
○ get() is slower than hashmap // retrieving the data.
● HashTable: - class
○ It is synchronized. It ensures that no more than one thread can access the
Hashtable at a given moment of time.
○ It doesn’t allow null keys and null values. NO nulls at all.
● TreeMap: - class implements SortedMap Interface
○ It is sorted in the ascending order of its keys.
● MAP Methods:
○ .put(key, value): inserts key and value objects to the map.
Java :: 11
TreeSet vs TreeMap
● TreeSet: can contain only unique values - is sorted in ascending order
● TreeMap: can contain only unique keys. - keys are sorted in ascending order
How to remove names which contain a specific letter “e” from a collection type?
String[] namesArray = {"Ali", "Veli", "Semavi", "Sami", "Hayati", "Memati", "Canan"};
Set<String> namesSet = new LinkedHashSet<>();
namesSet.addAll(Arrays.asList(namesArray));
Iterator<String> namesSetIterator = namesSet.iterator(); // returns an Array of “namesSet”
while (namesSetIterator.hasNext()){
String str = namesSetIterator.next();
if(str.toLowerCase().contains("e")){
namesSetIterator.remove(); }
} System.out.println(namesSet);
Java :: 13
Exceptions in Java
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. The good thing about exceptions is that they
can be handled in Java. By handling the exceptions we can provide a meaningful message to the
user about the issue rather than a system generated message, which may not be understandable
to a user.
Types of exceptions
● Checked exceptions:
○ All exceptions other than Runtime Exceptions are known as Checked exceptions as
the compiler checks them during compilation to see whether the programmer has
handled them or not.
○ If these exceptions are not handled/declared in the program, you will get
compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
● Unchecked Exceptions:
○ Runtime Exceptions are also known as Unchecked Exceptions. These exceptions
are not checked at compile-time so the compiler does not check whether the
programmer has handled them or not.
○ It’s the responsibility of the programmer to handle these exceptions and provide a
safe exit. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Exception Handling
● Try & Catch Block: to handle the exception
try {
System.out.println(new int[] {1,2,3}[100]); // out of bound exception occurs here
} catch (Exception e){
System.out.println("Out of Bound Exception caught here");
} finally {
System.out.println("Finally will be executed here regardless of any exception
occurs or not"); }
● Throws keyword: to pass it to the caller’s responsibility to handle it. “throws” keyword
indicates that this method throws an exception.
public static void method1 () throws Exception{
Thread.sleep(2000); }
What Is System.gc()?
● A request to JVM to run Garbage collector to free up memory but it is not a command so it
may not be executed.
● It is up to the garbage collector to honor this request.
if(print.isEmpty()){
System.out.println(i);
} else {
System.out.println(print);
}
}
Write a program that will count how many times “java” is found in any given String:
Approach One:
String givenStr = "Kac defa java geceiyok ki java sayisini javada say";
int counter = 0;
for (int i = 0; i<givenStr.length()-3; i++){
if(givenStr.substring(i, i+4).equalsIgnoreCase("java"))
counter++; }
System.out.println(counter);
Approach Two:
String str = "burada java yazdik ki Java kacta gesiyor bul ve java sayisini yazdir";
int javaCounter=0;
str = str.toLowerCase(); //to be make the str case insensitive
while(str.contains("java")){
javaCounter++;
str = str.replaceFirst("java","");
//this will replace java with an empty string and return the remaining str.
} System.out.println(javaCounter);
Given any String determine if it is Palindrome. Print “Palindrome” if it is and “Not Palindrome” if
it is not:
Approach One:
String text = "amalama";
boolean check = true;
check=false;
break; }
}
System.out.println(check ? "Palindrome" : "Not Palindrome");
Approach Two:
String str1 = "deneme";
String str2 ="";
if (str1.equalsIgnoreCase(str2))
System.out.println(str1 + " is a palindrome" + " Here is the reversed = " + str2);
else
System.out.println(str1 + " is NOT a palindrome!"+ " Here is the reversed = " + str2);
Approach Three:
String str1 = "deneme";
String str2 = new StringBuffer(str1).reverse().toString();
System.out.println(str2);
Given any String print out how many times each character is found in the String
String str0 = "CyberTek";
int letterCounter =0;
str0 = str0.toLowerCase();
String usedLetters="";
if(Character.isDigit(str.charAt(i))) {
num += str.charAt(i);
Given two Strings determine if they are Anagrams -> Are built of the same characters:
Approach One:
String str1 = "listen";
String str2 = "silent";
for (int i = 0; i <str1.length() ; i++) {
str2 = str2.replaceFirst("" + str1.charAt(i), ""); }
System.out.println(str2.isEmpty() ? "Anagram" : "NOT Anagram"); }
Approach Two:
String str1 = "listen";
String str2 = "silent";
Approach Three:
public static boolean Same(String str1, String str2) {
str1 = new TreeSet<String>(Arrays.asList( str1.split("") ) ).toString( );
str2 = new TreeSet<String>(Arrays.asList( str2.split("") ) ).toString( );
return str1.equals(str2); }
Java :: 19
Password Validation
1. Password MUST be at least 8 characters
2. Password should at least contain one uppercase letter
3. Password should at least contain one lowercase letter
4. Password should at least contain one special characters
5. Password should at least contain a digit
if all requirements above are met, the password is valid, if not all are met it is invalid
Approach One:
String password = "a?G6jdsaja";
boolean valid = length && lower && upper && number && special;
if(valid) {
System.out.println("Password is valid");
} else {
System.out.println("Not a valid password");
}
Approach Two:
String password = "a?Gj6dsaja";
if(!length) {
System.out.println("Invalid length");
} else if(!lower) {
System.out.println("Missing lowercase letter");
} else if(!upper) {
System.out.println("Missing uppercase letter");
} else if(!number) {
System.out.println("Missing number");
} else if(!special) {
System.out.println("Missing special character");
} else {
Java :: 20
System.out.println("Valid password");
}
Approach One:
String str = "AAABBKKACCDDDWWWBDD";
String expected ="";
int num=0;
Approach Two:
Write a return method that can remove the duplicate values from String
Ex: removeDup("AAABBBCCC") ==> ABC
Approach One:
String str="AAABBBCCC";
String result ="";
Approach Two:
String str="AAABBBCCC";
String result = "";
System.out.println(result);
Write a return method that can find the unique characters from the String
Java :: 21
Approach One:
String str="AAABBBCCCDEF";
String result = "";
Approach Two:
String str="AAABBBCCCDEF";
String result ="";
Write a method that can find the maximum number from an int Array
Approach One:
int [] nums = {1,4,7,9,3,56,3};
int max=0;
Approach Two:
public static int maxValue( int[] n ) {
Approach Three:
int [] arr = {9,4,23,6,78,4};
Arrays.sort(arr);
int max = arr[arr.length-1];
System.out.println(max);
Write a method that can find the minimum number from an int Array
Approach One:
int [] arr = {9,4,23,6,78,4};
int min = arr[0];
Approach Two:
int [] arr = {9,4,23,6,78,4};
Arrays.sort(arr);
int min = arr[0];
System.out.println(min);
Write a return method that can sort an int array in Ascending order without using the sort
method of the Arrays class:
int temp=0;
if (arr[i]<arr[j]){ // if I change ‘<’ to ‘>’ it will sort from bigger to smaller
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp; } } }
System.out.println(Arrays.toString(arr));
Java :: 23
Create a method that will accept a number and print all the prime numbers from 2 to that given
number:
Create a method that will accept a number and check if the number is an Armstrong number. If
the number is an Armstrong number return true otherwise return false.
Approach One:
public static boolean isArmstrongNum(int num) {
return sum==num;
}
Approach Two:
public static boolean isArmstrongNum(int num) {
String numo = String.valueOf(num);
int length =numo.length();
int number = num;
int temp=0;
int sum=0;
while (number!=0){
temp=number%10;
sum+=Math.pow(temp,length);
number/=10;
}
return sum==num;
}
Approach Three:
String numStr=String.valueOf(num);
int power=numStr.length();
System.out.println(numStr);
Create a method that will accept a number (long) and determine if the number is palindrome or
not.
Approach One:
public static boolean isDigitPalindrome1(long number){
Approach Two:
public static boolean isDigitPalindrome2(long number){
return reverseLong==number;
}
Approach Three:
public static boolean isDigitPalindrome3(long number){
long temp=number;
long reverseLong =0;
long lastDigit;
while (temp!=0){
lastDigit = temp%10;
reverseLong=reverseLong*10+lastDigit;
temp/=10;
Java :: 25
}
return reverseLong==number;
}
a = a+b; // a = 30
b = a-b; // b = 10
a = a-b; // a = 20
Write a program that can print the numbers between 1 ~ 100 that can be divisible by 3, 5, and
15.
➔ if the number can be divisible by 3, 5 and 15, then it should only be displayed in
DivisibelBy15 section
➔ if the number can be divisible by 3 but cannot be divisible by 15, then it should only be
displayed in DivisibelBy3 section
➔ if the number can be divisible by 5 but cannot be divisible by 15, then it should only be
displayed in DivisibelBy5 section
ex:
OutPut:
Divisible By 15 15 30 45 60 75 90
Divisible By 5 5 10 20 25 35 40 50 55 65 70 80 85 95 100
Divisible By 3 3 6 9 12 18 21 24 27 33 36 39 42 48 51 54 57 63 66 69 72 78 81 84 87 93
96 99