Sie sind auf Seite 1von 29

Private constructor to restrict instantiation of the class from other classes.

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....");
}

public static void main(String a[]){


MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}
============================================================
class DoubletonDemo
{
private static DoubletonDemo doubletonDemo1=null;
private static DoubletonDemo doubletonDemo2=null;

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) {

String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h


d h j j k f sd j e wed a d f";

List<String> list = Arrays.asList(text.split(" "));

Set<String> uniqueWords = new HashSet<String>(list);


for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(list, word));
}
}
}
-----------------------------------------
public class DuplStr {
public static void main(String argu[]) {

String str = "w3schools";


int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (inp[i] == inp[j]) {
System.out.println(inp[j]);
cnt++;
break;
}
}
}
}
}
------------------------------------

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 {

public static void main(String[] args) {

// 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");

// Standard classic way, recommend!


System.out.println("\nExample 1...");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " +
entry.getValue());
}

// Java 8, forEach and Lambda. recommend!


System.out.println("\nExample 2...");
map.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

// 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());
}

// weired, but works anyway, don't use, just for fun


System.out.println("\nExample 4...");
for (Object key : map.keySet()) {
System.out.println("Key : " + key.toString() + " Value : " +
map.get(key));
}

===================================================================================
======================================================
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>();

// enter name/url pair


gfg.put("GFG", "geeksforgeeks.org");
gfg.put("Practice", "practice.geeksforgeeks.org");
gfg.put("Code", "code.geeksforgeeks.org");
gfg.put("Quiz", "quiz.geeksforgeeks.org");

// using for-each loop for iteration over Map.entrySet()


for (Map.Entry<String,String> entry : gfg.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
}
// using iterators
Iterator<Map.Entry<String, String>> itr = gfg.entrySet().iterator();

while(itr.hasNext())
{
Map.Entry<String, String> entry = itr.next();
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
===================================================================================
======================================================
class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[]){


try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}
}

===================================================================================
======================================================
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;
}

public static void main (String[] args) {


int arr[] = {10,70,30,90,20,20,30,40,70,50};//unsorted array
Arrays.sort(arr);//sorting array
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
===================================================================================
======================================================
public static void duplicateRemove(int[] arr) {
int temp = 0;

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


for (int j = 0; j < arr.length; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

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 static void main(String[] args) {


String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}

private static String [] mySplit(String text1, String text2) {


text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
===================================================================================
======================================================

public class LinkedListStack {


private Node head; // the first node

// nest class to define linkedlist node


private class Node {
int value;
Node next;
}

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;
}

// Add value to the beginning of the list for demonstrating behaviour of


stack
public void push(int value) {
Node oldHead = head;
head = new Node();
head.value = value;
head.next = oldHead;
}

public static void main(String args[])


{
LinkedListStack lls=new LinkedListStack();
lls.push(20);
lls.push(50);
lls.push(80);
lls.push(40);
lls.push(60);
lls.push(75);
System.out.println("Element removed from LinkedList: "+lls.pop());
System.out.println("Element removed from LinkedList: "+lls.pop());
lls.push(10);
System.out.println("Element removed from LinkedList: "+lls.pop());
printList(lls.head);
}
public static void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}
}

/**
*
* 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();
}

public StackFullException(String message){


super(message);
}

/**
*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);
}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


/**
* StackExampleGeneric Main class
*/
public class StackExampleGeneric {
public static void main(String[] args) {
Stack<Employee> stack = new Stack<Employee>(10); // Creation of Generic
Stack
stack.push(new Employee("11", "sam"));
stack.push(new Employee("22", "sam"));
stack.push(new Employee("33", "sam"));
stack.push(new Employee("44", "sam"));
stack.push(new Employee("11", "sam"));

System.out.print("Popped items: ");


System.out.print(stack.pop()+" ");
System.out.print(stack.pop()+" ");
System.out.print(stack.pop()+" ");
System.out.print(stack.pop()+" ");
System.out.print(stack.pop()+" ");

/** OUTPUT

Popped items: Employee [id=11, name=sam] Employee [id=44, name=sam] Employee


[id=33, name=sam] Employee [id=22, name=sam] Employee [id=11, name=sam]

*/
class LinkedListEmptyException extends RuntimeException {
private static final long serialVersionUID = 1L;

public LinkedListEmptyException() {
super();
}

public LinkedListEmptyException(String message) {


super(message);
}
}
-------------------------------------------------------------------------
import java.util.*;
class SortEmployee{
public static void main(String[] arr) {
List<Employee> list = new ArrayList<Employee>();
Employee e1 = new Employee(1,"Deepak","Maddy");
Employee e2 = new Employee(3,"Shyam","Mishra");
Employee e3 = new Employee(5,"Manish","Singh");
Employee e4 = new Employee(4,"Santosh","Pidugu");
Employee e5 = new Employee(2,"Thakur","Munda");
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
list.add(e5);
System.out.println("Before Sorting...");
Iterator itr = list.iterator();
while (itr.hasNext()) {
Employee e = (Employee)itr.next();
System.out.println(e.id + " - " + e.firstName + " - "+
e.lastName);
}
Employee.order = "id"; // set the order in which you want to sort the
Employee objects. Can be id/firstName/lastName
Collections.sort(list);
System.out.println("After Sorting...");
Iterator itr2 = list.iterator();
while (itr2.hasNext()) {
Employee e = (Employee)itr2.next();
System.out.println(e.id + " - " + e.firstName + " - "+
e.lastName);
}
}
}

/*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;

public class MainClass


{
//Method to calculate sum of 'n' numbers

static int sumOfNnumbers(int n)


{
int sum = (n * (n+1))/ 2;

return sum;
}

//Method to calculate sum of all elements of array

static int sumOfElements(int[] array)


{
int sum = 0;

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


{
sum = sum + array[i];
}

return sum;
}

public static void main(String[] args)


{
int n = 8;

int[] a = {1, 4, 5, 3, 2, 8, 6};

int sumOfNnumbers = sumOfNnumbers(n);

int sumOfElements = sumOfElements(a);

int missingNumber = sumOfNnumbers - sumOfElements;

System.out.println("Input Array : "+Arrays.toString(a));

System.out.println("Missing Number is = "+missingNumber);


}
}
Output :

Input Array : [1, 4, 5, 3, 2, 8, 6]


Missing Number is = 7

[Description]

10) Write a java program to convert an array to ArrayList and an ArrayList to


array?

Array To ArrayList :

import java.util.ArrayList;
import java.util.Arrays;

public class MainClass


{
public static void main(String[] args)
{
String[] array = new String[] {"ANDROID", "JSP", "JAVA", "STRUTS",
"HADOOP", "JSF"};

ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));

System.out.println(list);
}
}
ArrayList To Array :

import java.util.ArrayList;

public class MainClass


{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();

list.add("JAVA");

list.add("JSP");

list.add("ANDROID");

list.add("STRUTS");

list.add("HADOOP");

list.add("JSF");

String[] array = new String[list.size()];

list.toArray(array);

for (String string : array)


{
System.out.println(string);
}
}
}
[Description]

11) Write a java program to count occurrences of each element in an array?

import java.util.Arrays;
import java.util.HashMap;

public class MainClass


{
static void arrayElementCount(int inputArray[])
{
//Creating a HashMap object with elements of inputArray as keys and their
count as values

HashMap<Integer, Integer> elementCountMap = new HashMap<Integer,


Integer>();
//checking every element of the inputArray

for (int i : inputArray)


{
if(elementCountMap.containsKey(i))
{
//If element is present in elementCountMap, incrementing it's count
by 1

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("Input Array : "+Arrays.toString(inputArray));

System.out.println("Element Count : "+elementCountMap);

System.out.println("=======================================");
}

public static void main(String[] args)


{
arrayElementCount(new int[]{4, 5, 4, 5, 4, 6});

arrayElementCount(new int[]{12, 9, 12, 9, 10, 9, 10, 11});

arrayElementCount(new int[]{891, 187, 891, 187, 891, 476, 555, 741});


}
}
Output :

Input Array : [4, 5, 4, 5, 4, 6]


Element Count : {4=3, 5=2, 6=1}
=======================================
Input Array : [12, 9, 12, 9, 10, 9, 10, 11]
Element Count : {9=3, 10=2, 11=1, 12=2}
=======================================
Input Array : [891, 187, 891, 187, 891, 476, 555, 741]
Element Count : {741=1, 891=3, 187=2, 555=1, 476=1}
=======================================
How to find the duplicate in an array?

String str = "HI RAHUL I AM FINE RAHUL"; // String with a duplicate word.

String[] words = str.split(" "); // Splitting and converting to Array .

for(int i = 0; i < words.length; i++){ //iterating array inside for loop

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 .

}}}
===================================================================================
======================================================

public static void main(String[] args) {

int myArr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };

int largest = myArr[0];

int secondLargest = myArr[0];

System.out.println("The given array is:" );

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

System.out.print(myArr[i]+"\t");

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

if (myArr[i] > largest) {

secondLargest = largest;

largest = myArr[i];

} else if (myArr[i] > secondLargest) {secondLargest = myArr[i];

}}

System.out.println("\nSecond largest number is:" + secondLargest);

}
===================================================================================
======================================================
Remove Dublicate Element from array
public class HelloWorld{

public static void main(String []args){

int a[] = {10,2,3,2,4,5,6,4,7,8,9,6};


int size = a.length;
System.out.println("toal size befoer detection:"+size);
for(int i=0;i<size;i++)
{

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;

public class ArrayReverseExample


{
static void reverseArray(int inputArray[])
{
System.out.println("Array Before Reverse : "+Arrays.toString(inputArray));

int temp;

for (int i = 0; i < inputArray.length/2; i++)


{
temp = inputArray[i];

inputArray[i] = inputArray[inputArray.length-1-i];

inputArray[inputArray.length-1-i] = temp;
}

System.out.println("Array After Reverse : "+Arrays.toString(inputArray));


}

public static void main(String[] args)


{
reverseArray(new int[]{4, 5, 8, 9, 10});

System.out.println("-------------------------");

reverseArray(new int[]{12, 9, 21, 17, 33, 7});

System.out.println("-------------------------");

reverseArray(new int[]{891, 569, 921, 187, 343, 476, 555});


}
}
===================================================================================
============================
import java.util.*;
import java.lang.*;
public class Rextester
{
public static void main(String args[])
{
System.out.println("Hello, World!");
int a[]={2,5,3,4,6,1};
sortingArray(a);
System.out.println("array is"+ Arrays.toString(a));
}
private static void sortingArray(int []a){
System.out.println("Hello, World!"+a.length);
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1;j++){
if(a[j]>a[j+1]){
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}

}
}
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };

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


for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
Another sample example of Arrays Merge.

public class HelloWorld {


public static void main(String[] args) {
int[]a = {1,2,3,4};
int[]b = {4,16,1,2,3,22};
int[]c = new int[a.length+b.length];
int count = 0;

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


c[i] = a[i];
count++;
}
for(int j = 0;j<b.length;j++) {
c[count++] = b[j];
}
for(int i = 0;i<c.length;i++) System.out.print(c[i]+" ");
}
}
The above code sample will produce the following result.

1,2,3,4,4,16,1,2,3,22
===================================================================================
===========================

package com.howtodoinjava.datastructure;

import java.util.Arrays;

public class CustomStack <E>


{
private int size = 0;
private static final int DEFAULT_CAPACITY = 10;
private Object elements[];

public CustomStack() {
elements = new Object[DEFAULT_CAPACITY];
}

public void push(E e) {


if (size == elements.length) {
ensureCapacity();
}
elements[size++] = e;
}

@SuppressWarnings("unchecked")
public E pop() {
E e = (E) elements[--size];
elements[size] = null;
return e;
}

private void ensureCapacity() {


int newSize = elements.length * 2;
elements = Arrays.copyOf(elements, newSize);
}

@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;
}

public void push(int pushedElement) {


if (!isFull()) {
top++;
arr[top] = pushedElement;
System.out.println("Pushed element:" + pushedElement);
} else {
System.out.println("Stack is full !");
}
}

public int pop() {


if (!isEmpty()) {
int returnedTop = top;
top--;
System.out.println("Popped element :" + arr[returnedTop]);
return arr[returnedTop];

} else {
System.out.println("Stack is empty !");
return -1;
}
}

public int peek() {


return arr[top];
}

public boolean isEmpty() {


return (top == -1);
}

public boolean isFull() {


return (size - 1 == top);
}

public static void main(String[] args) {


StackCustom StackCustom = new StackCustom(10);
StackCustom.pop();
System.out.println("=================");
StackCustom.push(10);
StackCustom.push(30);
StackCustom.push(50);
StackCustom.push(40);
System.out.println("=================");
StackCustom.pop();
StackCustom.pop();
StackCustom.pop();
System.out.println("=================");
}
}
------------------------------------------------------------------------------
public class Stack<E> {
private E[] arr = null;
private int CAP;
private int top = -1;
private int size = 0;

@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;
}

public boolean push(E e) {


if (!isFull())
return false;

this.size++;
this.arr[++top] = e;
return false;
}

public boolean isFull() {


if (this.size == this.CAP)
return false;
return true;
}

public String toString() {


if(this.size==0){
return null;
}

StringBuilder sb = new StringBuilder();


for(int i=0; i<this.size; i++){
sb.append(this.arr[i] + ", ");
}

sb.setLength(sb.length()-2);
return sb.toString();
}

public static void main(String[] args) {

Stack<String> stack = new Stack<String>(11);


stack.push("hello");
stack.push("world");

System.out.println(stack);
stack.pop();
System.out.println(stack);

stack.pop();
System.out.println(stack);
}
}
---------------------------------------------------------------------
public class Stack {

private int arr[];


private int size;
private int index = 0;

public Stack(int size) {


this.size = size;
arr = new int[size];
}

public void push(int element) {

if (isFull()) {
throw new StackOverflowError("Stack is full");
}

arr[index] = element;
index++;
}

public int pop() {

if (isEmpty()) {
throw new EmptyStackException();
}
return arr[--index];
}

public boolean isEmpty() {


if (index == 0) {
return true;
}
return false;
}

public boolean isFull() {


if (index == size) {
return true;
}
return false;
}

public int size() {


return index;
}
}
------------------------------------------------------------------------------
String str = "asdfasdfafk asd234asda";
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
char[] arr = str.toCharArray();

for (char value: arr) {

if (Character.isAlphabetic(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);

} else {
charMap.put(value, 1);
}
}
}

System.out.println(charMap);

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

public class DuplicateCharsInString {

public void findDuplicateChars(String str){

Map<Character, Integer> dupMap = new HashMap<Character, Integer>();


char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set<Character> keys = dupMap.keySet();
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}

public static void main(String a[]){


DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("AshawiniKumar");
}
}
----------------------------------------------------------------------------------
// JAVA program to count occurrences
// of a character

class GFG
{
// Method that return count of the given
// character in the string
public static int count(String s, char c)
{
int res = 0;

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


{
// checking character in string
if (s.charAt(i) == c)
res++;
}
return res;
}
----------------------------------------------------------------------------------
public class Exercise4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();

System.out.print("Number of Vowels in the string: " + count_Vowels(str)


+"\n");
}
public static int count_Vowels(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) ==
'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
count++;
}
}
return count;
}
}
-----------------------------------------------------------------------------------
---
public class MultiThreadExample {

static AtomicInteger atomicNumber = new AtomicInteger(1);

public static void main(String[] args) {


Runnable print = () -> {
while (atomicNumber.get() < 10) {
synchronized (atomicNumber) {
if ((atomicNumber.get() % 2 == 0) &&
"Even".equals(Thread.currentThread().getName())) {
System.out.println("Even" + ":" +
atomicNumber.getAndIncrement());
} else if ((atomicNumber.get() % 2 != 0) &&
"Odd".equals(Thread.currentThread().getName())) {
System.out.println("Odd" + ":" +
atomicNumber.getAndIncrement());
}
}
}
};

Thread t1 = new Thread(print);


t1.setName("Even");
t1.start();
Thread t2 = new Thread(print);
t2.setName("Odd");
t2.start();

}
}

-----------------------------------------------------
package com.learn.thread;

public class PrintNumbers extends Thread {


volatile static int i = 1;
Object lock;

PrintNumbers(Object lock) {
this.lock = lock;
}

public static void main(String ar[]) {


Object obj = new Object();
// This constructor is required for the identification of wait/notify
// communication
PrintNumbers odd = new PrintNumbers(obj);
PrintNumbers even = new PrintNumbers(obj);
odd.setName("Odd");
even.setName("Even");
odd.start();
even.start();
}

@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();

// Create producer thread


Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();

System.out.println("Producer produced-"
+ value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();

//to retrive the ifrst job in the list


int val = list.removeFirst();

System.out.println("Consumer consumed-"
+
val);

// Wake up producer thread


notify();

// 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");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};

t1.start();
t2.start();
}
}
---------------------------------------------------------------------------------

Das könnte Ihnen auch gefallen