[go: up one dir, main page]

0% found this document useful (0 votes)
30 views35 pages

MiU Technical Interview Prep

The document contains technical interview notes with various programming problems and their solutions in Java. It includes examples of code snippets demonstrating concepts such as loops, methods, classes, and data structures like linked lists and queues. Additionally, it covers topics like leader numbers, lucky sums, and object-oriented programming principles with customer and employee classes.

Uploaded by

Andualem Sebsbe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views35 pages

MiU Technical Interview Prep

The document contains technical interview notes with various programming problems and their solutions in Java. It includes examples of code snippets demonstrating concepts such as loops, methods, classes, and data structures like linked lists and queues. Additionally, it covers topics like leader numbers, lucky sums, and object-oriented programming principles with customer and employee classes.

Uploaded by

Andualem Sebsbe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 35

-------------------MIU Technical Interview Note-------------

---------------------Output questions ----------------------

public static void main(String[] args) {


int size = 1;

int[] data = new int[3];

data[0] = 0;
data[1] = 7;
data[--size] = 9;
System.out.println("The value of size is: " + size); //Output: 0
System.out.println("The content of data is: " + Arrays.toString(data));
//Output: [9, 7, 0]
}

-------------------------------------------------------

public static void main(String[] args) {

System.out.println("Value 1 is: " + getValue1()); //Output: 6


}

private static int getValue1() {


int j = 6;
return j++;
}
-------------------------------------

public static void main(String[] args) {

System.out.println("Value 1 is: " + getValue1()); //Output: 5


}

private static int getValue1() {


int j = 6;
return --j;
}
-----------------------------------

int size = 0;
for (int i = 0; i <= size; ++i) {
size--;
}
System.out.println(size);// Output: -1

---------------------------------------------
int size = 0;
for (int i = 0; i <= size; ++i) {
size++;
}
System.out.println(size);// Output: Infinite loop

----------------------------------------------
static void outputSize(){
int size =4;
for (int i=0;i<=size;i++){

size =size-2;

}
System.out.println(size);//Output: 0

}
---------------------------------------

static void outputY(){


int y =0;
for (int i=0;i<3;i++){

y+=i;

}
System.out.println(y);//Output: 0+1+2=3

-----------------------------------------------
static void outputDo(){
int a=3;
do {
a=a+1;
}
while (a<5);
System.out.println(a);//Output: 5
}
---------------------------------------------------------
for (int i = 0; i < 3; i++) {

for (int j = 0; j < i; j++) {


System.out.print(i + " " + j + ", ");

}
}
//output: 1 0, 2 0, 2 1
-----------------------------------

outer: for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {


inner: if (i == j) {
continue outer;
}
System.out.print(i + " " + j + ", "); //Output: 1 0, 2 0, 2 1

}
}

public static void main(String[] args) {

System.out.println("MOON" + 10 + 20); //Output: MOON1020;


System.out.println(10 + 20 +"MOON"); //Output: 30MOON;
}
public static void main(String[] args) {

String s1 = "MOON";
String s2 = new String("MOON");
System.out.println(s1==s2); //Output: False;

//if you try to change the final values in java it will print the compilation
error;

public static void main(String[] args) {


int x = 1;
System.out.println(x--); //Output: 1;

}
public static void main(String[] args) {
int x = 1;
System.out.println(--x--); //Output: error;

}
// -----------------------Leader Number-----------------------

Leader number if it is greater than all number right to it


so find all leader numbers and return all sum.

static int leaderNumber(int[] a){


int sum = 0;
for(int i=0; i<a.length; i++){
int j;
for(j = i+1; j<a.length; j++){
if(a[i]<=a[j]){
break;
}
}
if(j == a.length){

System.out.print(a[i] +" ");

sum += a[i];

}
}
//System.out.println("Sum: "+ sum);
return sum;
}

// ------------------------Lucky Sum----------------------

Write a method called luckySum. a lucky number is a number whose


preceding elements are strictly less than it.Write a method that
returns sum of these luckNumbers.

static int luckySum(int[]a){


int sum = 0;
for(int i =0; i<a.length-1; i++){
if(a[i] >= a[i+1]){
return -1;
}else{
sum += a[i];
}
}
return sum;
}
// ------------------------My Method----------------------

Write a method called myMethod that takes in two integer arrays and
returns the index of the smallest number. The smallest number should only
be present in the first array and not in the second.

static int myMethod(int[] a, int[] b){


int min = Integer.MAX_VALUE;
int index=0;
for(int i =0; i<a.length; i++){
if(a[i] < min){
min = a[i];
index = i;
boolean flag = false;
for(int j = 0; j<b.length; j++){
if(min == b[j]){// min>=a[j] chacking if there is min
in b[j]
flag = true;
break;
}
}
if(flag) return -1;
}

}
return index;
}
//---------------------My Array--------------------

an array to return 1 it must be


1.first and last elements must be odd
2.for every odd element except the last element
must be followed by exactly two even element.
example{7,4,6,3,6,8,11} will return 1
but{{7,4,6.3,6,8,12,11}return 0
{7,4,3,6,8,11}return 0,{6,3,4,8,9}return 0.

static int myArr(int[] a){


if(a[0]%2 ==0 || a[a.length -1]%2==0) return 0;
int evenCount = 0;
for(int i=0; i<a.length-1; i++){
if(a[i]%2!=0){
evenCount = 0;
for(int j =i+1; j<a.length; j++){
if(a[j]%2==0){
evenCount++;
}else{
break;
}
}
if(evenCount!=2) return 0;
}
}
return 1;
}

//--------------------------My Answer --------------------

write an array called myAnswer which return 1 if


{2,3,5,11} 2<3 ,2+3<5 ,2+3+5<11 is true other wise it returns 0.
in this case the above example return 0.
while {2,3,6,12} return 1.

static int myAnswer(int[] a){


int sum = 0;
for(int i = 0; i<a.length-1; i++){

sum += a[i];

if(sum>=a[i+1]){

return 0;
}
}
return 1;

----------------------------------OOP Problems-----------------

------------------------------Customer class------------------

Write customer class which prints name + units consumed and amount paid.
(if units consumed >= 100 amount paid = 25 if units consumed < 100 amount paid =
units consumed * 0.25)
Customer customer1 = new Customer('John Doe', 20)
use oop best practices(any no. of classes, constructors, set and get methods)

class Customer{

private String name;


private int unitConsumed;

//Property methods

public String getName(){


return name;
}
public int getUnitConsumed(){
return unitConsumed;
}
public void setUnitConsumed(int unitConsumed){
this.unitConsumed = unitConsumed;
}

//Constractor mathods

public Customer(String name){


this.name = name;
unitConsumed = 0;
}

public Customer(String name, int unitConsumed){


this.name = name;
setUnitConsumed(unitConsumed);
}

public double calculateFee(){


double amountPaid;
if(unitConsumed <100){
amountPaid = unitConsumed*0.25;
}else if(unitConsumed > 100){
amountPaid = 25;
}else{
amountPaid = 0;
}
//System.out.println(amountPaid);
return amountPaid;
}
public void detail(){
System.out.print("Name: "+name+", "+"Unit Consumed: "+ unitConsumed+",
"+"Total Fee: "+ calculateFee());
}
}
public class CustomerTest {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Customer c = new Customer("Wege");
c.detail();
}

--------------------------------Employee class-----------------------

create a java class that have three fields name, id, fee with constractors, getter,
setter and other class
setting feilds and display value and calculate total fee using methods.

public class Employee {


private String name;
private String id;
private double fee;

public Employee(String name, String id){


this.name = name;
this.id = id;
fee = 0;
}

public Employee(String name, String id, double fee){


this.name = name;
this.id = id;
this.fee = fee;
}
public String getName(){
return name;
}
public String getId(){
return id;
}
public double getFee(){
return fee;
}
public void setFee(double fee){
this.fee = fee;
}
public double feeCalculator(){
double totalFee = getFee()*15;
return totalFee;
}
public void display(){
System.out.println(name +", "+ id+ ", "+ fee+", "+ feeCalculator());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Employee e = new Employee("name", "id", 20);


e.setFee(10);
//System.out.println( e.feeCalculator());
e.display();

Customer cus = new Customer(123,"google","good",date);

---------------------------Shape
Interface-----------------------------------------------------------

EXERCISE: Create a Shape interface having methods area () and perimeter (). Create
2 subclasses,
Circle and Rectangle that implement the Shape interface. Create a class Sample with
main method and
demonstrate the area and perimeters of both the shape classes. You need to handle
the values of length, breath, and radius in respective classes to calculate their
area and perimeter.

SOLUTION:
interface Shape {
double area();
double perimeter();
}

class Rectangle implements Shape {

private double length;


private double breadth;

public Rectangle(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}

@Override
public double area() {

return length * breadth;


}

@Override
public double perimeter() {

return 2 * (length + breadth);


}
}

class Circle implements Shape {

private double radius;

public Circle(double radius) {


this.radius = radius;

@Override
public double area() {

return Math.PI * radius * radius;


}

@Override
public double perimeter() {

return 2 * Math.PI * radius;


}
}

public class Sample {

public static void main(String[] args) {


// Rectangle area and parameter
double length = 2.0;
double breadth = 3.0;
Rectangle r = new Rectangle(length, breadth);

System.out.println("Rectangle - Area: " + r.area());


System.out.println("Rectangle - perimeter: " + r.perimeter());

// Circle area and parameter


double radius = 2.0;
Circle c = new Circle(radius);
System.out.println("Circle - Area: " + c.area());
System.out.println("Circle - perimeter: " + c.perimeter());

}
}

Rectangle - Area: 6.0


Rectangle - perimeter: 10.0
Circle - Area: 12.566370614359172
Circle - perimeter: 12.566370614359172

---------------------------------Implementations-----------------

---------------------------------Linked List------------------
class Node{
int value;
Node next;

public Node(int value){


this.value = value;
}
}

class LinkedList{
private Node head;
private Node tail;
private int size;

public LinkedList(int value){


Node node = new Node(value);
head = node;
tail = node;
size = 1;
}

//print method
public void printll(){
Node temp = head;
while(temp!=null){
System.out.print(" "+ temp.value);
temp = temp.next;
}
}

public void gethead(){


System.out.println("Head ValueL: "+ head.value);
}

public void gettail(){


System.out.println("Tail Value: "+ tail.value);
}

public void getsize(){


System.out.println("Size: "+ size);

//append method
public void append(int value){
Node node = new Node(value);
if(size == 0){
head = node;
tail = node;

}else{
tail.next = node;
tail = node;
}
size++;
}
//Remove last

public Node removeLast(){


if(size == 0) return null;
Node temp = head;
Node pre = head;

while(temp.next != null){
pre = temp;
temp = temp.next;
}
tail = pre;
tail.next = null;
size--;
if(size == 0){
head = null;
tail = null;
}
return temp;
}
public void prepend(int value){
Node node = new Node(value);
if(size == 0){
head = node;
tail= node;
}else{
node.next = head;
head = node;
}
size++;
}
public Node removeFirst(){
if(size == 0) return null;

Node temp = head;


head = head.next;
temp.next = null;
size--;
if(size == 0){
tail= null;
}
System.out.println(temp.value+" is removed successfully!");
return temp;
}
public Node get(int index){
if(index< 0 || index>=size) return null;
Node temp = head;
for (int i = 0; i<index; i++){
temp = temp.next;
}
System.out.println(temp.value + " is the the value of the index!");
return temp;
}

public boolean set(int index, int value){


Node temp = get(index);
if(temp !=null){
temp.value = value;
System.out.println("The value is changed to "+ value);
}
return false;
}

public boolean insert(int index, int value){


if(index<0 || index>size) return false;
if(index == 0){
prepend(value);
return true;
}
if(index == size){
append(value);
return true;
}
Node node = new Node(value);
Node temp = get(index-1);
node.next = temp.next;
temp.next = node;
size++;
System.out.println(value+" is inserted!");
return true;
}
public Node remove(int index){
if(index<0 || index>=size) return null;
if(index == 0) return removeFirst();
if(index == size-1) return removeLast();

Node pre = get(index-1);


Node temp = pre.next;
pre.next = temp.next;
temp.next = null;
size--;
System.out.println(temp.value+" is removed!");
return temp;
}
public void reverse(){
Node temp = head;
head = tail;
tail = temp;
Node before = null;
Node after = temp.next;
for(int i=0; i<size; i++){
after = temp.next;
temp.next = before;
before = temp;
temp = after;
}

}
}

------------------------------------------------ Queue Using linked


list------------------------
// Queue implementation using linked list
// isEmpty, enQueue, deQueue, peek, delete

public class Node{


int value;
Node next;

public Node(int value){


this.value = valuel;
}

public class Queue{


private Node front;
private Node rear;
private int length;

public Queue(int value){


Node node = new Node(value);
front = node;
rear = node;
length = 1;
System.out.println("The queue is created with the value of "+ value);
}
public boolean isEmpty(){
if(front == null){
return true;
}else{
return false;
}
}
public void enQueue(int value){
Node node = new Node(value);
if(isEmpty()){
front = node;
rear = node;
}else{
rear.next = node;
rear = node;
}
System.out.println(value+" is added to the queue");
length++;
}
public int deQueue(){
if(isEmpty()){
return -1;
}else{
Node temp = front;
front = front.next;
temp.next = null;
length --;
System.out.println(temp.value+" is removed from the queue");
if(length == 0){
front = null;
rear = null;
}
return temp.value;
}
}
public int peek(){
if(isEmpty()){
return -1;
}else{
Node temp = front;
return temp.value;
}
}
public void delete(){
front = null;
rear = null;
System.out.println("The queue is deleted successfully!");

}
public void printQueue(){
Node temp = front;
while(temp!=null){
System.out.print(" < "+temp.value+" > ");
temp = temp.next;
}
System.out.println("");
}
}

--------------------------------------------------Queue Using
Array-----------------------------

/* //Queue implementation using array

public class Queue{


int[] arr;
int front;
int rear;

public Queue(int size){


this.arr = new int[size];
this.front = -1;
this.rear = -1;
System.out.println("The queue is created with the size of "+ size);
}

//Creation, isEmpty, isFull, enQueue, deQueue, peek and delete


public boolean isEmpty(){
if(front == -1 || rear == -1){
//System.out.println("The queue is empty");
return true;
}else{
return false;
}
}
public boolean isFull(){
if(rear == arr.length - 1){
return true;
}else{
return false;
}
}
public void enQueue(int value){
if(isFull()){
System.out.println("The queue is full");
}else{
if(isEmpty()){
front = 0;
rear++;
arr[rear] = value;

}else{
rear++;
arr[rear]= value;
}
System.out.println(value+ " is added to the queue");
}
}
public int deQueue(){
if(isEmpty()){
System.out.println("The queue is empty");
return -1;
}else{
int result = arr[front];
front++;
System.out.println(result+" is removed from the queue");
if(front>rear){
front = rear = -1;
}
return result;
}
}
public int peek(){
if(!isEmpty()){
int result = arr[front];
System.out.println(result+" is peeked without removing from the queue");
return result;
}else{
return -1;
}
}
public void delete(){
arr = null;
System.out.println("The queue is deleted successfully!");
}
}
// main method
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enQueue(1);
queue.enQueue(2);
queue.enQueue(3);
queue.enQueue(4);
queue.enQueue(5);
// System.out.println(queue.deQueue());
System.out.println(queue.peek());
queue.delete();
System.out.println(queue.peek());

System.out.println("isEmpty? : "+ queue.isEmpty());


System.out.println("isFull? : "+ queue.isFull());
}

*/

-------------------------------Stack Implementation using linked


list-------------------------

class Solution {
public static void main(String[] args) {
class Stack{
private Node topOfStack;
private int size;

public Stack(int value){


Node node = new Node(value);
topOfStack = node;
size = 1;

System.out.println("Stack is created with the value of: "+ value);


}

class Node {
int value;
Node next;

public Node(int value){


this.value = value;
}
}
public boolean isEmpty(){
if(size ==0 || topOfStack == null){
System.out.println("The stack is empty!");
return true;
}else{
return false;
}
}

public void push(int value){


Node node = new Node(value);
if(isEmpty()){
topOfStack = node;

}else {
node.next = topOfStack;
topOfStack = node;
}
size++;
System.out.println(value+ " is pushed ");
}
public Node pop(){

if(isEmpty()) return null;


Node temp = topOfStack;
topOfStack = topOfStack.next;
temp.next = null;
size --;

if(siz == 0){
topOfStack = null;
}
System.out.println(temp.value+ " is poped");
return temp;

}
public Node peek(){
if(isEmpty()) return null;
else{
Node temp = topOfStack;
System.out.println(temp.value+" is peeked");
return temp;
}
}
public void delete(){
topOfStack = null;
System.out.println("The stack is deleted!");
}
public void printStack(){
Node temp = topOfStack;
while(temp != null){
System.out.println(temp.value);
temp = temp.next;
}

}
}

Stack stack = new Stack(1);


stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
stack.printStack();
stack.peek();
System.out.println(stack.isEmpty());
stack.delete();
System.out.println(stack.isEmpty());
stack.printStack();
}
}
----------------------------------------- Stack Using
Array----------------------------------

public class Stack{


int[] arr;
int top = -1;

public Stack(int size) {


this.arr = new int[size];
this.top = -1;
System.out.println("The stack is created successfully!");
}
// isEmpty, isFull, push, pop, peek, delete

public boolean isEmpty(){


if(top == -1){
//System.out.println("The stack is empty!")
return true;
}else{
return false;
}
}
public boolean isFull(){
if(top == arr.length-1){
//System.out.println("The stack is full!")
return true;
}else{
return false;
}
}
public void push(int value){
if(isFull()){
System.out.println("The stack is full!");
}else{
arr[top+1] = value;
top++;
System.out.println(value + " is pushed to the stack.");
}
}
public int pop(){
if(isEmpty()){
System.out.println("The stack is empty!");
return -1;
}else{
int result = arr[top];
top--;
return result;
}
}
public int peek(){
if(isEmpty()){
System.out.println("The stack is empty!");
return -1;
}else{
return arr[top];
}
}
public void delete(){
arr = null;
System.out.println("The stack is deleted successfully!");
}
}

------------------------------------Tree
----------------------------------------------
// Binarysearchtree Node class;

public static class Node {


public int value;
public Node left;
public Node right;

private Node(int value) {


this.value = value;
}
}

public class BinarySearchTree {

public Node root;

//No constractor for binary search tree class;

Binary Search Tree is a node-based binary tree data structure which has the
following properties:

-The left subtree of a node contains only nodes with keys lesser than the node’s
key.
-The right subtree of a node contains only nodes with keys greater than the node’s
key.
-The left and right subtree each must also be a binary search tree.

------------------------------Array problems-----------------------------

// sumArray

static int sumArray(int[] arr){

int sum = 0;
for(int i=0; i<arr.length; i++){
sum += arr[i];
}
System.out.println(sum);
return sum;
}

//GridArray

static void gridArray(){

for(int i=0; i<10; i++){

for(int j=0; j<10; j++){


System.out.print("-");
}
System.out.println(" ");
}
}
// AvgValueArray

static double avgValueArray(int[] arr){

int sum = 0;
for (int i=0; i<arr.length; i++){
sum += arr[i];
}
System.out.println(sum/arr.length);
return (sum/arr.length);
}

//Lenear Search
static int linearSearch1(int[] arr, int value){

for (int i=0; i<arr.length; i++){


if(arr[i] == value){
System.out.println("The value is found @ index: "+i);
return 1;
}
}
System.out.println("The value is not found!");
return -1;
}

public static void main(String[] args) {


int[] arr = {10, 13, 4, 2, 6, 5, 2, 3, 5, 6, 7, 1};

//Find the second min

public class Main


{
int[] a = {-1, 4, 0, 2, 7, -3};
System.out.println("Original numeric array : "+Arrays.toString(my_array));
int min = Integer.MAX_VALUE;
int second_min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if(a[i]==min){
second_min=min;
} else if (a[i] < min) {
second_min = min;
min = a[i];
} else if (a[i] < second_min) {
second_min = a[i];
}

}
System.out.println("Second lowest number is : " + second_min);
}

//check duplicate

//To check the duplicate element

int[] arr = {10, 13, 4, 2, 6, 5, 2, 3, 5, 6, 7, 1};


for (int i = 0; i < arr.length-1; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if ((arr[i] == arr[j]) && (i != j))
{
System.out.println("Duplicate Element : "+arr[j]);
}
}
}

------------------------------------Searching-----------------------

public class Searching {

public static int linearSearch(int arr[], int value) {


for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
System.out.println("The element is found at the index: " + i);
return i;
}
}
System.out.println("The element " + value+ " not found.");
return -1;
}

// Binary Search

public static int binarySearch(int arr[], int value) {


int start = 0;
int end = arr.length-1;
int middle = (start+end)/2;
while (arr[middle] != value && start <= end) {
if (value < arr[middle]) {
end = middle -1;
} else {
start = middle + 1;
}
middle = (start+end)/2;
}
if (arr[middle] == value) {
System.out.println("The element is found at the index: " + middle);
return middle;
} else {
System.out.println("The element " + value+ " not found.");
return -1;
}

}
---------------------------Using recursive binary search----------------

public static int BSA(int arr[], int start, int end, int value)
{
if (start<=end) {
int mid = (start + end) / 2;
if (arr[mid] == value)
return mid;
if (value < arr[mid])
return BSA(arr, start, mid - 1, value);
return BSA(arr, mid + 1, end, value);
}
return -1;
}

-----------------------------Revers an Array-----------------

static void reverseArray(a[], int size)


{
int i, temp;
for (i = 0; i < size / 2; i++) {
temp = a[i];
a[i] = a[size - i - 1];
a[size - i - 1] = temp;
}

/*print the reversed array*/


System.out.println("Reversed Array: \n" + Arrays.toString(a));
}

public static void main(String[] args)


{
int [] a = {11,22,33,44,55,66,77,88,99};

//print the original array


System.out.println("Original Array: \n" + Arrays.toString(a));
//function call to reverse the array
reverseArray(a, a.length);
}
------------------------Count character in a String-------------------

public int countChar(String str, char c)


{
int count = 0;

for(int i=0; i < str.length(); i++)


{ if(str.charAt(i) == c)
count++;
}

return count;
}

--------------------------Power claculation without


Math.Pow()---------------------------

static int power(int base, int exponent){


int pow =1;

for(int i=0; i<exponent; i++){

pow *= base;
}

return pow;
}

-------------------------Min and max in Array---------------------------

static void minMax (int[] a){


int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

for(int i=0; i<a.lenght; i++){

if(a[i] < min){


min = a[i];
}
if(a[i] > max){
max = a[i];
}
}
System.out.println("The maximum value is: "+max+" and the Minimum value is:
"+min);
}

---------------------Leader Number(Number must be greater than the numbers to its


right)--------------------

public class Main


{
public static void main(String[] args)
{
int arr[] = {10, 9, 14, 23, 15, 0, 9};
int size = arr.length;
for (int i = 0; i < size; i++)
{
int j;
for (j = i + 1; j < size; j++)
{
if (arr[i] <= arr[j])
break;
}
if (j == size)
System.out.print(arr[i] + " ");
}
}
}

---------------------common elements between two arrays of


integers--------------------
public static void main(String[] args)
{
int[] array1 = {1, 2, 5, 5, 8, 9, 7, 10};
int[] array2 = {1, 0, 6, 15, 6, 4, 7, 0};

for (int i = 0; i < array1.length; i++)


{
for (int j = 0; j < array2.length; j++)
{
if(array1[i] == (array2[j]))
{

System.out.println("Common element is : "+(array1[i]));


}
}
}

------------------common elements between two arrays (string


values)---------------------------

public static void main(String[] args)


{
String[] a1 = {"Python", "JAVA", "PHP", "C#", "C++", "SQL"};

String[] a2 = {"MySQL", "SQL", "SQLite", "Oracle", "PostgreSQL", "DB2",


"JAVA"};

HashSet<String> set = new HashSet<String>();

for (int i = 0; i < a1.length; i++)


{
for (int j = 0; j < a2.length; j++)
{
if(a1[i].equals(a2[j]))
{
set.add(a1[i]);
}
}
}
System.out.println("Common element : "+(set)); //OUTPUT : [THREE, FOUR,
FIVE]
}

-----------------------------------Find duplicate integer value------------------

public static void main(String[] args)


{
int[] a = {1, 2, 5, 5, 6, 6, 7, 2};

for (int i = 0; i < a.length-1; i++)


{
for (int j = i+1; j < a.length; j++)
{
if ((a[i] == a[j]) && (i != j))
{
System.out.println("Duplicate Element : "+a[j]);
}
}
}
}

-----------------------------------Find duplicate String value------------------

public static void main(String[] args)


{
String[] a = {"bcd", "abd", "jude", "bcd", "oiu", "gzw", "oiu"};

for (int i = 0; i < a.length-1; i++)


{
for (int j = i+1; j < a.length; j++)
{
if( (ay[i].equals(a[j])) && (i != j) )
{
System.out.println("Duplicate Element is : "+a[j]);
}
}
}
}

-----------------------------Second largest element using


Arrays.sort()------------------------

public static void main(String[] args) {


int[] a = {
10789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
System.out.println("Original numeric array : "+Arrays.toString(a));
Arrays.sort(a);

int index = a.length-1;


while(a[index]==a[a.length-1]){
index--;
}
System.out.println("Second largest value: " + a[index]);
}

--------------------------- SEcond Smallest value --------------------


public static void main(String[] args) {

int[] a = {-1, 4, 0, 2, 7, -3};


System.out.println("Original numeric array : "+Arrays.toString(a));
int min = Integer.MAX_VALUE;
int second_min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if(a[i]==min){
second_min=min;
} else if (a[i] < min) {
second_min = min;
min = a[i];
} else if (a[i] < second_min) {
second_min = a[i];
}

}
System.out.println("Second lowest number is : " + second_min);
}

---------------------------------------Rotate an Array --------------------------

static void rotate_array(int[] a)


{
int temp = a[a.length-1];
int i;

for (i = a.length-1; i > 0; i--)


a[i] = a[i-1];
a[0] = temp;
}

-----------------------------------Separate Even and ood elements------------

static int [] separate_odd_even(int arr[])


{
int left = 0;
int right = arr.length - 1;

while (left < right)


{
while (arr[left]%2 == 0 && left < right)
left++;

while (arr[right]%2 == 1 && left < right)


right--;

if (left < right)


{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
return arr;
}

------------------------------Segregate all 0s and 1ns on left and


right------------

public static void main (String[] args)


{
int a[] = {0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1};
int i, nums_size = nums.length;
int left = 0, right = nums_size - 1;

System.out.println("Original Array : "+Arrays.toString(nums));

while (left < right)


{
/* While 0 at left increment left index */
while (a[left] == 0 && left < right)
left++;

/* While we see 1 at right decrement right index*/


while (a[right] == 1 && left < right)
right--;

if (left < right)


{
a[left] = 0;
a[right] = 1;
left++;
right--;
}
}

System.out.println("Array after segregation is : "+Arrays.toString(a));


}

-------------------------Separate 0 and 1 related with segregate best method


-----------------------

static int [] separate_0_1(int arr[], int n)


{
int count = 0;

for (int i = 0; i < n; i++) {


if (arr[i] == 0)
count++;
}

for (int i = 0; i < count; i++)


arr[i] = 0;

for (int i = count; i < n; i++)


arr[i] = 1;

return arr;
}

---------------------------Another Sorthing 0 and 1---------------

public static void sort_binary_nums(int[] a)


{
int index = 0;

for (int i = 0; i < a.length; i++)


{
if (a[i] == 0) {
a[index++] = 0;
}
}

for (int i = index; i < a.length; i++) {


a[index++] = 1;
}
}

Java HashMap
- is data structure wich store items in "key/value" pairs
e.g

HashMap<String, String> c= new HashMap<String, String>();

c.put("b", "c")- add items to it


c.get(key) - access the value in hashmap (refere to its key)
c.remove(key) - remove an item (refere to its key)
c.clear() - remove all items

Java HashSet
A HashSet is a collection of items where every item is unique

==-----------------------------------------------------
e.g

public static void main(String[] args) {


HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
}

-To check whether an item exists in a HashSet, use the contains() method:
Example
cars.contains("Mazda");

-To remove an item, use the remove() method:

Example
cars.remove("Volvo");`

-To remove all items, use the clear() method:

Example
cars.clear();

-----------------------------------------SQL NOTE------------------------

-------------------- Select table--------------


SELECT * FROM table_name;

SELECT DISTINCT column1, column2, ...


FROM table_name;

SELECT column1, column2, ...


FROM table_name
WHERE condition;

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
-----------------Insertion----------------------------
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

-------------------- Update table--------------


UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

-------------------- Delete table--------------

DELETE FROM table_name


WHERE condition;
SELECT MIN(column_name)
FROM table_name
WHERE condition;

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;

SELECT * FROM Customers


WHERE City LIKE 'ber%';

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

SELECT column_name AS alias_name


FROM table_name;

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

Coalesece() function returns the first non-null value in a list

CREATE PROCEDURE SelectAllCustomers


AS
SELECT * FROM Customers
GO;

-----sql comment----
--Select all:
SELECT * FROM Customers;

---------------------------Database create, delete, backup---------------------

CREATE DATABASE databasename;

DROP DATABASE databasename;

BACKUP DATABASE databasename


TO DISK = 'filepath';

-----------------------Creating table-----------------

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
);
-----------------Delete, update table-------------------

DROP TABLE table_name;

ALTER TABLE table_name


ADD column_name datatype;

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

SELECT * FROM Users WHERE UserId = 105 OR 1=1;

------------------------------------Verbally asked questions


-----------------------

1. What is polymorphism

-poly means many morphism means forms = many forms;


- Excuting a single operation in different ways.
- it allow to perform a single action in different ways.

2. What are static and dynamic polymorphism

-Static polymorphism is polymorphism that occurs at compile time,(Method


overloading) and
-dynamic polymorphism is polymorphism that occurs at runtime (during
application execution) (method overriding)

3. What is Queue explain

- is a data structure that store items in FIFO manner.


4. What is linked list explain

-it is a sequencial collection and it doesn't have to be in order.

Additional Verbally asked questions

1. What is polymorphism?

- Excuting a single operation in different ways.

2. Method overloading and overriding?

-Method Overloading: is when methods have the same name with different
parameter.
-Method Overriding: is re-defining of methods of super class into sub class.

3. How is binary search done?

-Binary Search Tree is a node-based binary tree data structure.

which has the following properties:

-The left subtree of a node contains only nodes with values lesser than the
node’s value.
-The right subtree of a node contains only nodes with values greater than the
node’s key.

-The left and right subtree each must also be a binary search tree.

4. What is the difference between binary search tree and binary search algorithm?
-Binary Search Tree is a node-based binary tree data structure.
-Binary search algorithm is an algorithem used to search values in a sorted
arry using devide and concur method.

-Binary Search is a searching algorithm used in a sorted array by repeatedly


dividing the search interval in half.

5. Difference between stack and queue?

- Queue is a data structure that store items in FIFO (First in First out)
manner.
- Stack is a data structure that store items in LIFO(Last in First out)
manner.

----------------------------------OOP Note-------------------------------

Class:
- is a template for creating objects. or
- is a blueprint for creating objects.

Object:
-is an instance of a class.
Constractor:
-is a special method of a class that used to initialize object. or
- is a method of a class and it is called when the object is created.

Method/Function:
-is a block of code w/c only runs w/n it is called.

Method Overloading:

- is when methods have the same name with different parameter.

Method Overriding:

- is re-defining of methods of super class into sub class.

Getter and Setter Methods:


----------------------------

Getter Method: Getter returns the value (accessors)


Setter Method: Setter sets or updates the value (mutators).

Abstraction: Getter and Setter are methods used to protect your data and make your
code more secure.
- is hiding internal details and showing only the required
things/information.

Encapsulation:
- is the process of grouping data in a single section
- is puting everything in a single box.
Inheritance:
-is re-using the properties of the existing class and object.
(Specialization)
- is reusing the code from previous class and adding extra features.

polymorphism:

- Excuting a single operation in different ways. (Gemeralization)

Runtime Polymorphism:
- When the super class reference holding the object of sub class and the
overriden method is called.
- it achived by method Overriding.
- it also called Dynamic method dispatch.
- Calling method dynamically b/c the program make the decission at runtime
for w/ch object to call

Compile time Ploymorphism:


- achived by method overloading.
- At compile-time, java knows which method to call by checking the method
signatures.

Abstract Class:
- cannot create object but can be used as a reference.
- if sub class inherites from abstract class it should override all abstract
methods.

Interface:
- cannot be used to creat objects.
-interface methods have no body.
-used to achive polymorphysm
-methods are by default abstract and public.
-attributes are by default public, static, final.
-multiple inheritance can be achieved using interface.

this: -is areference for current object.


-it also avoid name confilict.

super: -is a refeence to super class object.


-the most common use is to avoid name confilict.

Static Methods: can be accessed without creating object.


Public Methods: can be accessed by creating objects.

Access Modifieres
----------------
Final:(class): cannot be inherited.
Abstract: (class): cannot be used to create object.

Final:(Methods): cannot be overridden.


Abstract: (Method): the method doesn't have body.

Private:(Method) the code is accessible with in the class.


Public: (Method) the code is accessible for all classes.
Protected: (Method) the code is accessible in the same package and sub classes.
Default: accessible in the same package.

------------------Java Date and Time------------------------

Date dob = new Date(1990, 10, 03); //deprecated

LocalDate date = LocalDate.of(2017,Month.FEBRUARY,3); // Java time

------------------------------Good Luck!-------------------------

You might also like