Beruflich Dokumente
Kultur Dokumente
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global
access point for outer world to get the instance of the singleton class.
public class MySingleTon {
private static MySingleTon myObj;
private MySingleTon(){}
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
public void getSomeThing(){
// do something here
System.out.println("I am here....");
}
private DoubletonDemo()
{
// private constructor so the object cann't create from outside the class.
}
public static DoubletonDemo getDoubletonDemo()
{
if(doubletonDemo1==null)
{
doubletonDemo1=new DoubletonDemo();
return doubletonDemo1;
}
else if(doubletonDemo2==null)
{
doubletonDemo2=new DoubletonDemo();
return doubletonDemo2;
}
else
{
if(Math.random() < 0.5)
{ return doubletonDemo1;} /* we will get the DoubletonDemo object
randomly by some rounding order */
else
{return doubletonDemo2;}
}
}
public static void main(String[] args)
{
DoubletonDemo d1=getDoubletonDemo();
DoubletonDemo d2=getDoubletonDemo(); // output: 274415197
DoubletonDemo d3=getDoubletonDemo(); // 1448825870
DoubletonDemo d4=getDoubletonDemo(); // 274415197
DoubletonDemo d5=getDoubletonDemo(); // 1448825870
System.out.println(d1.hashCode()); // 274415197
System.out.println(d2.hashCode());
System.out.println(d3.hashCode());
System.out.println(d4.hashCode());
System.out.println(d5.hashCode());
}
}
===================================================================================
======================================================
public class RevString
{
public static void main(String []args)
{
String name="java of data";
char value[]=name.toCharArray();
for(int i=value.length-1;i>=0;i--)
{
System.out.print(value[i]);
}
}
}
---------------------------------
int in = name.length();
for(int i = in-1; i>=0;i--)
{
System.out.print(name.charAt(i));
}
------------
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.io.*;
import java.util.*;
public class DuplicateWordSearcher {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
while(Number > 0) {
Reminder = Number % 10;
Sum = Sum+ Reminder;
Number = Number / 10;
}
System.out.format("Sum of the digits of Given Number = %d", Sum);
===================================================================================
======================================================
public class LoopMap {
// initial a Map
Map<String, String> map = new HashMap<>();
map.put("1", "Jan");
map.put("2", "Feb");
map.put("3", "Mar");
map.put("4", "Apr");
map.put("5", "May");
map.put("6", "Jun");
// Map -> Set -> Iterator -> Map.Entry -> troublesome, don't use, just for
fun
System.out.println("\nExample 3...");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("Key : " + entry.getKey() + " Value :" +
entry.getValue());
}
===================================================================================
======================================================
15. How a HashMap works internally? [Hint: Read about Bucket, HashCode(),
Hashfunction etc]
24. How to create custom exception?
25. How to throw an error in catch block?
29. What is serialization? Why do we need it in Java? Write a serializaion
program in Java.
33. Write a logic to sort an array in Java. [Hint: may use Binary search
algorithm]
34. Write logic/program to merge two sorted arrays (int[]) to make one array.
35. Concurrent hashmap (3 types of hashmaps. check if this question is valid)
37. Write your own custom arraylist without extending Arraylist. [write your own
add method]
38. Write a program to print two different threads with alternate numbers like
Thread t1 - 1, Thread t2 - 2, Thread t1 - 3, Thread t2 - 4 and so on
===================================================================================
======================================================
import java.util.Map;
import java.util.HashMap;
class IterationDemo
{
public static void main(String[] arg)
{
Map<String,String> gfg = new HashMap<String,String>();
while(itr.hasNext())
{
Map.Entry<String, String> entry = itr.next();
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
===================================================================================
======================================================
class TestCustomException1{
===================================================================================
======================================================
public class StringTokenizerExample
{
public static void main(String[] args)
{
String reverseMessage="";
String message ="Reverse String in Java using String Tokenizer";
/*We have passed message to our st object,
* which splits the String based on spaces(default delimiter)
*/
StringTokenizer st = new StringTokenizer(message);
/*hasMoreTokens methods returns a boolean which is used to
* check if there exist a next token
*/
while(st.hasMoreTokens())
{
reverseMessage = st.nextToken()+" "+reverseMessage;
}
System.out.println("Original String is :"+message);
System.out.println("Reversed String is :"+reverseMessage);
}
}
===================================================================================
======================================================
+---------+------+------------+
| Method | Safe | Idempotent |
+---------+------+------------+
| CONNECT | no | no |
| DELETE | no | yes |
| GET | yes | yes |
| HEAD | yes | yes |
| OPTIONS | yes | yes |
| POST | no | no |
| PUT | no | yes |
| TRACE | yes | yes |
+---------+------+------------+
The PUT and DELETE methods are defined to be idempotent.
GET, HEAD, OPTIONS and TRACE methods are defined as safe, meaning they are only
intended for retrieving data.
===================================================================================
======================================================
Class Duplicate
{
public static void main(String []args)
{
int[] arr={1,2,3,1,1,3,5,5,6,8};
Arrays.sort(arr);
for(int i=1;i<arr.length;i++)
{
if(arr[i]==arr[i-1])
{
System.out.println("Duplicate = " + arr);
}
}
}}
===================================================================================
======================================================
for (i = 0; i < Size; i++)
{
for (j = i + 1; j < Size; j++)
{
if(a[i] > a[j])
{
Temp = a[i];
a[i] = a[j];
a[j] = Temp;
}
}
}
===================================================================================
======================================================
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
int count;
for (int j = 0; j < arr.length;) {
count = 1;
for (int i = j + 1; i < arr.length; i++) {
if (arr[i] == arr[j]) {
count++;
} else
break;
}
System.out.println(arr[j] + " is : " + count);
j += count;
}
}
===================================================================================
======================================================
public class NoJavaSplit {
public LinkedListStack() {
head = null;
}
// Remove value from the beginning of the list for demonstrating behaviour of
stack
public int pop() throws LinkedListEmptyException {
if (head == null) {
throw new LinkedListEmptyException();
}
int value = head.value;
head = head.next;
return value;
}
/**
*
* Exception to indicate that LinkedList is empty.
*/
class Employee {
private String id;
private String name;
/**
* Employee constructor
*/
public Employee(String id, String name) { // constructor
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "] ";
}
/**
*Exception to indicate that Stack is full.
*/
class StackFullException extends RuntimeException {
public StackFullException(){
super();
}
/**
*Exception to indicate that Stack is empty.
*/
class StackEmptyException extends RuntimeException {
public StackEmptyException(){
super();
}
public StackEmptyException(String message){
super(message);
}
/**
* Stack class(generic type)
*/
class Stack<T> {
private int size;
private T[] stackAr;
private int top; // top of stack
/**
* Constructor for initializing Array.
*/
@SuppressWarnings("unchecked")
public Stack(int size) {
this.size = size;
stackAr = (T[])new Object[size]; //Creation of Generic Stack Array
top = -1; // initialize Stack to with -1
}
/**
* Push items in stack, it will put items on top of Stack.
*/
public void push(T value){
if(isFull()){
throw new StackFullException("Cannot push "+value+", Stack is
full");
}
stackAr[++top] = value;
}
/**
* Pop items in stack, it will remove items from top of Stack.
*/
public T pop() {
if(isEmpty()){
throw new StackEmptyException("Stack is empty");
}
return stackAr[top--]; // remove item and decrement top as well.
}
/**
* @return true if Stack is empty
*/
public boolean isEmpty(){
return (top == -1);
}
/**
* @return true if stack is full
*/
public boolean isFull(){
return (top == size - 1);
}
/** OUTPUT
*/
class LinkedListEmptyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public LinkedListEmptyException() {
super();
}
/*Output
Before Sorting...
1 - Deepak - Maddy
3 - Shyam - Mishra
5 - Manish - Singh
4 - Santosh - Pidugu
2 - Thakur - Munda
Id 3 VS 1
Id 5 VS 3
Id 4 VS 5
Id 4 VS 3
Id 4 VS 5
Id 2 VS 4
Id 2 VS 3
Id 2 VS 1
After Sorting...
1 - Deepak - Maddy
2 - Thakur - Munda
3 - Shyam - Mishra
4 - Santosh - Pidugu
5 - Manish - Singh
*/
-------------------------------------------------------------------------
===================================================================================
======================================================
Write a java program to find a missing number in an integer array?
import java.util.Arrays;
return sum;
}
return sum;
}
[Description]
Array To ArrayList :
import java.util.ArrayList;
import java.util.Arrays;
System.out.println(list);
}
}
ArrayList To Array :
import java.util.ArrayList;
list.add("JAVA");
list.add("JSP");
list.add("ANDROID");
list.add("STRUTS");
list.add("HADOOP");
list.add("JSF");
list.toArray(array);
import java.util.Arrays;
import java.util.HashMap;
elementCountMap.put(i, elementCountMap.get(i)+1);
}
else
{
//If element is not present in elementCountMap,
//adding this element to elementCountMap with 1 as it's value
elementCountMap.put(i, 1);
}
}
System.out.println("=======================================");
}
String str = "HI RAHUL I AM FINE RAHUL"; // String with a duplicate word.
for(int j = i+1; j < words.length; j++){ //iterating same array inside another for
loop
if (words[i].equals(words[j])){ // Using equal method i am verifying which word is
repeating . System.out.println( words[i]); // here it will print duplicate .
}}}
===================================================================================
======================================================
int myArr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
System.out.print(myArr[i]+"\t");
secondLargest = largest;
largest = myArr[i];
}}
}
===================================================================================
======================================================
Remove Dublicate Element from array
public class HelloWorld{
for(int j=i+1;j<size;j++)
{
if(a[i]==a[j])
{
while(j<(size)-1)
{
a[j]=a[j+1];
j++;
}
size--;
System.out.println(a[i]);
}
}
System.out.println("after size"+size);
for(int i=0;i<size;i++)
{
System.out.println(a[i]);
}
}
}
===================================================================================
===============================
import java.util.Arrays;
int temp;
inputArray[i] = inputArray[inputArray.length-1-i];
inputArray[inputArray.length-1-i] = temp;
}
System.out.println("-------------------------");
System.out.println("-------------------------");
}
}
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
1,2,3,4,4,16,1,2,3,22
===================================================================================
===========================
package com.howtodoinjava.datastructure;
import java.util.Arrays;
public CustomStack() {
elements = new Object[DEFAULT_CAPACITY];
}
@SuppressWarnings("unchecked")
public E pop() {
E e = (E) elements[--size];
elements[size] = null;
return e;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('[');
for(int i = 0; i < size ;i++) {
sb.append(elements[i].toString());
if(i < size-1){
sb.append(",");
}
}
sb.append(']');
return sb.toString();
}
}
-------------------------------------
class Stack
{
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack
boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}
boolean push(int x)
{
if (top >= (MAX-1))
{
System.out.println("Stack Overflow");
return false;
}
else
{
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}
int pop()
{
if (top < 0)
{
System.out.println("Stack Underflow");
return 0;
}
else
{
int x = a[top--];
return x;
}
}
}
// Driver code
class Main
{
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
}
}
--------------------------------------------------------------------
public class StackCustom {
int size;
int arr[];
int top;
StackCustom(int size) {
this.size = size;
this.arr = new int[size];
this.top = -1;
}
} else {
System.out.println("Stack is empty !");
return -1;
}
}
@SuppressWarnings("unchecked")
public Stack(int cap) {
this.CAP = cap;
this.arr = (E[]) new Object[cap];
}
public E pop() {
if(this.size == 0){
return null;
}
this.size--;
E result = this.arr[top];
this.arr[top] = null;//prevent memory leaking
this.top--;
return result;
}
this.size++;
this.arr[++top] = e;
return false;
}
sb.setLength(sb.length()-2);
return sb.toString();
}
System.out.println(stack);
stack.pop();
System.out.println(stack);
stack.pop();
System.out.println(stack);
}
}
---------------------------------------------------------------------
public class Stack {
if (isFull()) {
throw new StackOverflowError("Stack is full");
}
arr[index] = element;
index++;
}
if (isEmpty()) {
throw new EmptyStackException();
}
return arr[--index];
}
if (Character.isAlphabetic(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);
} else {
charMap.put(value, 1);
}
}
}
System.out.println(charMap);
----------------------------------------------------------------------------
class GFG
{
// Method that return count of the given
// character in the string
public static int count(String s, char c)
{
int res = 0;
}
}
-----------------------------------------------------
package com.learn.thread;
PrintNumbers(Object lock) {
this.lock = lock;
}
@Override
public void run() {
while (i <= 10) {
if (i % 2 == 0 && Thread.currentThread().getName().equals("Even")) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " - "
+ i);
i++;
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (i % 2 == 1 && Thread.currentThread().getName().equals("Odd")) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " - "
+ i);
i++;
lock.notify();
}
}
}
}
}
-----------------------------------------------------------------------------------
--
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// t1 finishes before t2
t1.join();
t2.join();
}
System.out.println("Producer produced-"
+ value);
System.out.println("Consumer consumed-"
+
val);
// and sleep
Thread.sleep(1000);
}
}
}
}
}
----------------------------------------------------------------------------
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
---------------------------------------------------------------------------------