HOME JAVA SQL

Los Angeles

We had the best time playing at Venice Beach!

New York

The atmosphere in New York is lorem ipsum.

Chicago

Thank you, Chicago - A night we won't forget.

JAVA

JAVA BASIC PROGRAMS

public class FirstProgram {
	public static void main(String[] args) {
		System.out.println("Hello World...!");
	}
}

It is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition

public class ForLoopExample {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.out.println(i);
		}
	}
}

This loop will execute the code block once, before checking if the condition is true

public class WhileExample {
	 public static void main(String args[]) {
	      int n = 10;

	      while( n < 20 ) {
	         System.out.println(" n : " + n );
	         n++;
	      }
	   }
}

It is used to execute a block of statements continuously until the given condition is true

public class DoWhileExample {
	public static void main(String[] args) {
		int i = 1;
		do {
			System.out.println("i = "+i);
			i++;
		} while (i <= 10);
	}
}

It tells your program to execute a certain section of code only if a particular test evaluates to true

public class IfElseExample {
	public static void main(String[] args) {
		int i = 10;
		if (i == 10) {
			System.out.println("Say hi...");
		} else {
			System.out.println("Say bye...");
		}
	}
}

The switch statement can have a number of possible execution paths

A switch works with the byte, short, char, and int primitive data types

public class SwitchCaseExample {
	public static void main(String args[]) {

		String color = "green";

		switch (color) {
		case "Red":
			System.out.println("Red!");
			break;
		case "Blue":
			System.out.println("Blue");
			break;
		case "green":
			System.out.println("green");
			break;
		case "Orange":
			System.out.println("Orange");
		default:
			System.out.println("Invalid Color");
		}
		System.out.println("Your Color is " + color);
	}
}

Ternary operators are used to test if or else condition

public class TernaryExample {
	public static void main(String args[]) {
		int id=10;
		System.out.println((id==10)?"number is 10":"number other than 10");
		
	}

}

Arthmatic operators that perform addition, subtraction, multiplication, and division

public class ArthmaticOperatorExample {
	public static void main(String[] args) {

		double n1 = 10, n2 = 20, result;

		//addition
		result = n1 + n2;
		System.out.println("n1 + n2 = " + result);

		// subtraction
		result = n1 - n2;
		System.out.println("n1 - n2 = " + result);

		// multiplication
		result = n1 * n2;
		System.out.println("n1 * n2 = " + result);

		//division
		result = n1 / n2;
		System.out.println("n1 / n2 = " + result);

		// remainder
		result = n1 % n2;
		System.out.println("n1 % n2 = " + result);
	}
}

Unary operators are used to increasing or decreasing the value of an operand

public class UnaryOperatorExample {
public static void main(String[] args) {
    	
    	double n = 10;
    	boolean flag = false;
    	
    	System.out.println("n = " + +n);
    	
    	
    	System.out.println("n = " + -n);
   
      
    	System.out.println("n = " + ++n);

    	System.out.println("n = " + --n);


    	System.out.println("flag = " + !flag);

    }
}

It is used to test whether the object is an instance of the specified type

public class InstanceOfOperatorExample {
	public static void main(String[] args) {

		String str = "abcd";
		boolean result;

		result = str instanceof String;
		System.out.println(result);
	}
}

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand

public class RelationalOperatorExample {
	public static void main(String[] args) {

		int n1 = 7, n2 = 9;

		if (n1 > n2) {
			System.out.println("n1 is greater than n2.");
		} else {
			System.out.println("n2 is greater than n1.");
		}
	}
}

Logical operators are used when we want to check multiple conditions together.

public class LogicalOperatorExample {
	public static void main(String[] args) {

		int n1 = 1, n2 = 2, n3 = 9;

		System.out.println((n1 > n2) || (n3 > n1));

		System.out.println((n1 > n2) && (n3 > n1));
	}
}

The bitwise & operator performs a bitwise AND operation.

public class BitWiseAndExample {
public static void main(String[] args) {
    	
    	int n1 = 12, n2 = 25, result;
    	
    	result = n1 & n2;
    	System.out.println(result);
    }
}

The bitwise | operator performs a bitwise OR operation.

public class BitWiseORExample {
	public static void main(String[] args) {

		int n1 = 12, n2 = 25, result;

		result = n1 | n2;
		System.out.println(result);
	}
}

The bitwise ^ operator performs a bitwise XOR operation.

public class BitWiseXORExample {
	public static void main(String[] args) {

		int n1 = 12, n2 = 25, result;

		result = n1 ^ n2;
		System.out.println(result);
	}
}

public class BitWiseComplementExample {
	public static void main(String[] args) {

		int n = 15, result;

		result = ~n;
		System.out.println(result);
	}
}

left shift operator "<<" shifts a bit pattern to the left

public class BitWiseLeftShift {
	public static void main(String[] args) {

		int n = 100;

		System.out.println(n << 1);
		System.out.println(n << 2);
		System.out.println(n << 3);
	}
}

left shift operator ">>" shifts a bit pattern to the right

public class BitWiseRightShift {
	public static void main(String[] args) {

		int n = 100;

		System.out.println(n >> 1);
		System.out.println(n >> 7);
		System.out.println(n >> 9);
	}
}

It is used for initializing variables

Default constructor generated by jvm

public class ConstructorExample {
	int age;
	String name;

	ConstructorExample(int i, String name) {
		this.age = i;
		this.name = name;
		System.out.println("Inside Constructor");
	}

	public void display() {
		System.out.println("name = " + name + "age = " + age);

	}

	public static void main(String args[]) {
		ConstructorExample c = new ConstructorExample(32, "thomas");
		c.display();
	}
}

It is declared within the body of a method

It can use the variable within the method

public class LocalVaribleExamplePerson {

	public void age() {
		int age = 0; // local variable
		System.out.println("Person age is : " + age);
	}

	public static void main(String args[]) {
		LocalVaribleExamplePerson p = new LocalVaribleExamplePerson();
		p.age();
	}
}

Instance variables are declared outside a method. mean it declared in class

When an object is created then instance variables created and when the object is destroyed, instance variable is also destroyed

public class InstanceVariableExample {
	public String name;

	private int age;

	public InstanceVariableExample(String RecName) {
		name = RecName;
	}

	public void setAge(int RecSal) {
		age = RecSal;
	}

	public void showDetails() {
		System.out.println("name : " + name);
		System.out.println("age :" + age);
	}

	public static void main(String args[]) {
		InstanceVariableExample r = new InstanceVariableExample("Thomas");
		r.setAge(32);
		r.showDetails();
	}
}

A static variable is common to all the instances of the class

It is a class level variable

One single copy shared to all instances

public class StaticVariableExample {
	//static varible value  will reflect in all objects if you change in one object
	static int count = 0;

	public void increment() {
		count++;
	}

	public static void main(String args[]) {
		StaticVariableExample obj1 = new StaticVariableExample();
		StaticVariableExample obj2 = new StaticVariableExample();
		obj1.increment();
		obj2.increment();
		System.out.println("Obj1 count is=" + obj1.count);
		System.out.println("Obj2 count is=" + obj2.count);
	}
}

public class ArrayExample {
	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}

String is a group of characters

It is a immutable class mean we cannot changed once its created

Most of the data transport through String in network

public class StringExample {

	public static void main(String[] args) {
		String str = "java formula";
		String str1 = "JAVA FORMULA";
		String trim = " JAVA FORMULA";
		String test = "java";
		
		System.out.println("Index: " + str.charAt(2));
		
		System.out.println("After Concat: " + str.concat(" website "));
		
		System.out.println("Equals ignoring case: " + str.equalsIgnoreCase(str1));
		
		System.out.println("Equals with case: " + str.equals(str1));
		
		System.out.println("Length: " + str.length());
		
		System.out.println("Replace function: " + str.replace("java", "study"));
		
		System.out.println("SubString of String: " + str.substring(4));
		
		System.out.println("SubString from and to index : " + str.substring(4, 8));
		
		System.out.println("Lower case: " + str1.toLowerCase());
		
		System.out.println("Upper case: " + str.toUpperCase());
		
		System.out.println("Triming string: " + trim.trim());
		
		System.out.println("Searching s1 in String: " + str.contains(test));
		

		char[] charArray = str.toCharArray();
		
		System.out.println("length of char array: " + charArray.length);
		

		//checking String intern()
		String s1 = new String("FORMULA");  
        String s2 = s1.intern(); 
          
       
        System.out.println("checking with ==:"+(s1 == s2));              
        System.out.println("checking with equals: "+s1.equals(s2));

	}

}

String Buffer is mutable mean we can change once its created

Additional methods available like delete and reverse

Thread safety and synchronized

Useful in Multithreaded

public class StringBufferExample {
	public static void main(String[] args) {
		StringBuffer strBuffer = new StringBuffer();

		strBuffer.append("Hello World!");
		System.out.println(strBuffer.toString());

		strBuffer.delete(7, 11);
		System.out.println(strBuffer.toString());

		// Delete just one char
		strBuffer.deleteCharAt(7);
		System.out.println(strBuffer.toString());

		// Insert a string
		strBuffer.insert(0, "World ");
		System.out.println(strBuffer.toString());

		// Get the index of string.
		System.out.println("Index of Hello: " + strBuffer.indexOf("Hello"));
		System.out.println();

		StringBuffer newBuffer = new StringBuffer("This is a Hi World string. Hi!");

		System.out.println("Index of Hi: " + newBuffer.indexOf("Hi"));
		System.out.println("Last index of Hi: " + newBuffer.lastIndexOf("Hi"));

		newBuffer.replace(0, 4, "Iam here");
		System.out.println(newBuffer.toString());

		newBuffer.setCharAt(newBuffer.length() - 1, '?');
		System.out.println(newBuffer.toString());

		newBuffer.reverse();
		System.out.println(newBuffer.toString());

	}

}

String Builder is mutable mean we can change once its created

Not Thread safety and synchronized

Not useful in multithreaded env

public class StringBuilderExample {
	public static void main(String args[]) {
		StringBuilder sb = new StringBuilder("Hello ");
		
		//append
		sb.append("Formula");
		System.out.println(sb);
		
		///capacity
		System.out.println("capacity: "+sb.capacity());
		
		//insert
		sb.insert(1,"Java"); 
		System.out.println(sb);
		
		//replace
		sb.replace(1,2,"Java");  
		System.out.println(sb);
		
		//delete
		sb.delete(1,2);  
		System.out.println(sb);
	}
}

It can be used to refer parent class variables and methods

class SuperClass {

	int n = 10;
}

class SuperKeywordExampleSubClass extends SuperClass {

	int n = 160;

	void display() {
		System.out.println(super.n);
	}

	public static void main(String args[]) {
		SuperKeywordExampleSubClass obj = new SuperKeywordExampleSubClass();
		obj.display();
	}
}

It can be used to refer present class variables and methods

public class ThisKeywordExample {
	int variable = 7;

	public static void main(String args[]) {
		ThisKeywordExample obj = new ThisKeywordExample();
		obj.display(20);

	}

	void display(int variable) {
		variable = 10;
		System.out.println("Instance variable :" + this.variable);
		System.out.println("Local variable :" + variable);
	}
}

Encapsulation describes the ability of an object mean it hides data and methods

One of the fundamental principles of object-oriented programming

Encapsulation enables you to write reusable programs

All other fields and methods are private and can be used for internal object processing.

class Employee {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

public class Encapsulation {
	public static void main(String[] args) {

		Employee e = new Employee();

		e.setName("durga");

		System.out.println(e.getName());
	}
}

Abstraction is a process of hiding the implementation details from the user

Abstraction is achieved using abstract classes and interfaces

abstract class Fruit {
	abstract void taste();
}

public class AbstractClassExample extends Fruit {

	void taste() {
		System.out.println("taste is sweet");
	}

	public static void main(String args[]) {
		Fruit fruit = new AbstractClassExample();
		fruit.taste();
	}

}

Inheritance is an important feature of object-oriented programming languages

It enables classes to include properties of other classes

It inherits the properties is called a child class, and the class from which the properties are inherited is called a parent class

class Manager {
	String job = "Software";
	String companyName = "TCS";

	void profession() {
		System.out.println("wriring Programs");
	}
}

public class InheritanceExampleEmployee extends Manager {

	public static void main(String args[]) {
		InheritanceExampleEmployee obj = new InheritanceExampleEmployee();
		System.out.println(obj.companyName);
		System.out.println(obj.job);

		obj.profession();
	}
}

It is a feature that allows a class to have more than one method having the same name

It is Static Polymorphism

It happens at compile time

class Sum {
	public void add(int a, int b){
		System.out.println(a+b);
	}
	
	public void add(int a, int b,int c){
		System.out.println(a+b+c);
	}
}

public class OverLoadingExample {
	public static void main(String[] args) {
		Sum s = new Sum();
		s.add(10, 20);
		s.add(10, 20,30);
	}
}

It is a feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its super-class

It is Runtime Polymorphism

It happens at run time

class Parrot {
	// Overridden method
	public void fly() {
		System.out.println("Parrot is flying");
	}
}

class OverridingExampleBird extends Parrot {
	// Overriding method
	public void fly() {
		System.out.println("Bird is flying");
	}

	public static void main(String args[]) {
		OverridingExampleBird obj = new OverridingExampleBird();
		obj.fly();
		
		Parrot obj1 = new OverridingExampleBird();
		obj1.fly();
		
		
		Parrot obj2 = new Parrot();
		obj2.fly();
	}
}

Super class and Sub class methods defined with static

It usually static methods are bounded at compile time

class Pengvin {
	// Overridden method
	public static void fly() {
		System.out.println("Pengvin is flying");
	}
}

class MethodHidingExampleBird extends Pengvin {
	// Overriding method
	public static void fly() {
		System.out.println("Bird is flying");
	}

	public static void main(String args[]) {
		MethodHidingExampleBird obj = new MethodHidingExampleBird();
		obj.fly();

		Pengvin obj1 = new MethodHidingExampleBird();
		obj1.fly();

		Pengvin obj2 = new Pengvin();
		obj2.fly();
	}
}

Stronger type checks at compile time

Fixing compile-time errors is easier than fixing runtime errors

public class GenericsExample<T> {

	// Accept any object of type T
	T obj;

	GenericsExample(T obj) {
		this.obj = obj;
	}

	public T getObject() {
		return this.obj;
	}

	public static void main(String[] args) {
		GenericsExample<Integer> intObj = new GenericsExample<Integer>(16);
		System.out.println(intObj.getObject());
		GenericsExample<String> strObj = new GenericsExample<String>("Formula");
		System.out.println(strObj.getObject());
	}

}

public class GenericsMultipleTypeExample<T, U> {

	T t;
	U u;

	GenericsMultipleTypeExample(T t, U u) {
		this.t = t;
		this.u = u;
	}

	public void print() {
		System.out.println(t);
		System.out.println(u);
	}
}

class Main {
	public static void main(String[] args) {
		GenericsMultipleTypeExample<String, Integer> multiGeneric = new GenericsMultipleTypeExample<String, Integer>(
				"Formula", 16);
		multiGeneric.print();
	}
}

public class GenericFunctionExample {

	static <T> void display(T element) {
		System.out.println(element.getClass().getName() + " = " + element);
	}

	public static void main(String[] args) {
		display(16);
		display("formula");
		display(7.0);
	}
}

It create copy of instances of that class

Any class that implement this interface should override Object.clone()

public class CloningExample implements Cloneable {

	private String name;

	public CloningExample(String dname) {
		this.name = dname;
	}

	public String getName() {
		return name;
	}

	// Overriding clone() method
	public Object clone() throws CloneNotSupportedException {
		return (CloningExample) super.clone();
	}

	public static void main(String[] args) {
		CloningExample obj1 = new CloningExample("Formula");
		try {
			CloningExample obj2 = (CloningExample) obj1.clone();
			System.out.println(obj2.getName());
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}

}

Serialization is converting object into byte stream and transfer throught the network

When an object is serialized, information that identifies its class is recorded in the serialized stream

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Employee implements Serializable {
	String eName;
	int eId;

	Employee(String n, int i) {
		this.eName = n;
		this.eId = i;
	}
}

public class SerializationExample {

	public static void main(String[] args) {
		try {
			Employee emp = new Employee("Thomas", 106);
			FileOutputStream fos = new FileOutputStream("D:\\formula\\EXAMPLES\\emp.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(emp);
			oos.close();
			fos.close();
			System.out.println("Serialized the employee object successfully...!!!!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

De-serialization is converting byte stream into object and transfer throught the network

It is the responsibility of the system that is deserializing the object to determine how to locate and load the necessary class files

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationExample {

	public static void main(String[] args) {
		Employee emp = null;
		try {
			FileInputStream fis = new FileInputStream("D:\\formula\\EXAMPLES\\emp.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			emp = (Employee) ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(emp.eName);
		System.out.println(emp.eId);
	}
}

It is used for storing elements

Capacity grows automatically.

Capacity is the size of the array used to store the elements in the list.

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time(O(1))

Add operation runs in amortized constant time, that is, adding n elements requires O(n) time

This class used iterator and listIterator methods are fail-fast

Fail-fast iterators throw ConcurrentModificationException

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CreateArrayListExample {
	public static void main(String[] args) {
		// create new ArrayList Object
		List<String> list = new ArrayList<>();
		list.add("January");
		list.add("February");
		list.add("March");

		// using Iterator to see all elemnets in ArrayList
		Iterator<String> itr = list.iterator();
		while (itr.hasNext()) {
			System.out.println(itr.next());
		}

		// adding element at specified index
		list.add(2, "February");
		System.out.println(list);

		// Retrieve ArrayList elements by index
		System.out.println(list.get(2));

		// Search an item in ArrayList
		if (list.contains("January"))
			System.out.println("Month Found");
		else
			System.out.println("Month not Found");

		// Remove a single element from ArrayList by index
		list.remove(1);
		System.out.println(list);

		// Remove all elements from ArrayList
		list.clear();

		// Check ArrayList is empty or not
		if (list.isEmpty())
			System.out.println("ArrayList Empty");
		else
			System.out.println("ArrayList Contains: " + list.size() + " elements  !!");

	}
}

It is used for storing elements

Capacity grows automatically

Vector is synchronized

It can grow or shrink to accommodate add and remove items after the Vector has been created.

It uses Enumerator for iterating elements

import java.util.Enumeration;
import java.util.Vector;

public class VectorExample {
	public static void main(String args[]) {
	
	      Vector<String> v = new Vector<String>();

	      //Add elements
	      v.addElement("Thomas");
	      v.addElement("Robert");
	      v.addElement("Jackson");
	      v.addElement("William");

	      //Vector elements iterating only through Enumerator
	      Enumeration<String> en = v.elements();
	 
	      while(en.hasMoreElements())
	         System.out.print(en.nextElement() + " ");
	   }
}

It is used for storing key - value pairs

It cannot contain duplicate keys

It allows null key and the null values

It does not guarantee order of the elements

It is not thread safe

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapExample {

	public static void main(String args[]) {

		Map<Integer, String> hashMap = new HashMap<>();
		Map<Integer, String> hashMap1 = new HashMap<>();

		hashMap.put(1, "java");

		hashMap.put(2, "formula");

		hashMap.put(3, "website");

		System.out.println("Key value pairs: " + hashMap);
		System.out.println("Size of hashmap: " + hashMap.size());

		hashMap1 = (Map<Integer, String>) ((HashMap) hashMap).clone();

		System.out.println("Cloned  Map: " + hashMap1);
		
		System.out.println("Check if key 3 exists: " + hashMap.containsKey(3));
		 
		System.out.println("Check if value 'formula' exists: " +  hashMap.containsValue("formula"));
		
		Set keyset=hashMap.keySet();

		System.out.println("Key values are: " + keyset);
		  
		Set entrySet=hashMap.entrySet();

		System.out.println("Entry Set values: " + entrySet);
		
		String str=(String)hashMap.get(3);

		System.out.println("Value for key 3 is: " + str);

		hashMap.putAll(hashMap1);

		System.out.println("Values in hashMap1: "+ hashMap1);
		
		hashMap.remove(2);

		System.out.println("hashmap after  using remove method: "+ hashMap);
		
		System.out.println("hashmap values: "+ hashMap.values());
	}
}

It is used for storing key - value pairs

It maintain insertion order.The order in which keys were inserted into the map

It maintains a doubly-linked list running through all of its entries

It is not thread safe

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class LinkedHashMapExample {
	public static void main(String args[]) {
		// Maintain Insertion Order
		LinkedHashMap<Integer, String> lmap = new LinkedHashMap<Integer, String>();

		// Adding elements
		lmap.put(17, "Robert");
		lmap.put(21, "Thomas");
		lmap.put(1, "William");
		lmap.put(2, "Jackson");
		lmap.put(101, "Jason");

		//Get the EntrySet which is having all the key and values
		Set set = lmap.entrySet();

		// Iterating elements of LinkedHashMap
		Iterator<Map.Entry> iterator = set.iterator();
		while (iterator.hasNext()) {
			Map.Entry mapEntry = (Map.Entry) iterator.next();
			System.out.println("Key : " + mapEntry.getKey()+"--------> " + "Value: " + mapEntry.getValue());
		}
	}
}

It is used for storing key - value pairs

An entry in a WeakHashMap will automatically be removed when its key is no longer

It internally uses using the == operator for object testing

This class is not synchronized.It is not thread safe

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapExample {
	public static void main(String[] args) {
		Map<String,String> hMap= new HashMap<>();
		
        Map<String,String> wMap = new WeakHashMap<>();
        
        String s = new String("s");
        String s1 = new String("s1");
        
        hMap.put(s, "hi");
        wMap.put(s1, "Hello");
        System.gc();
        System.out.println("Before hash map :"+hMap.get("s")+" and weak hash map :"+wMap.get("s1"));
        
        s = null;
        s1 = null;
        
        System.gc();  
        
        System.out.println("After hash map :"+hMap.get("s")+" and weak hash map :"+wMap.get("s1"));
    }
}

It is used for storing key - value pairs

Which uses equals method when comparing objects

It designed for use only wherein reference-equality semantics are required

It does not guarantee that the order

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class IdentityHashMapExample {
	public static void main(String[] args) {
		
		Map<String,String> hMap = new HashMap<>();
		Map<String,String> iMap = new IdentityHashMap<>();

		
		hMap.put("Hi", "Hello");
		hMap.put(new String("Hi"), "hvalue");
		iMap.put("abc", "xyz");
		iMap.put(new String("abc"), "ivalue");

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

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

	}
}

It is used for storing elements

It prevent duplicate elemnts

It defines the iteration ordering, the order in which elements were inserted into the set

It maintains a doubly-linked list running through all of its entries

It is not synchronized

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
	public static void main(String args[]) {
        //Maintain Insertion order
        LinkedHashSet<String> lset = new LinkedHashSet<String>();

    
        lset.add("Thomas");
        lset.add("Robert");
        lset.add("Jackson");
        lset.add("Jason");
       
        System.out.println(lset);
   }
}

It is used for storing elements

The elements are ordered using their natural ordering

It provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

It is not synchronized

import java.util.TreeSet;

public class TreeSetExample {
	public static void main(String args[]) {
        //Sorting the elements
		TreeSet<String> t = new TreeSet<String>();

		// Adding elements
		t.add("Jackson");
		t.add("Robert");
		t.add("Jackso");
		t.add("Thomas");

		System.out.println(t);

	}
}

It is used for storing key - value pairs

It cannot have a null key but can have multiple null values

It maintain ascending order

It is not synchronized

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExample {
	public static void main(String args[]) {

		// Sorting the keys
		TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();

		tmap.put(2, "Thomas");
		tmap.put(48, "Jason");
		tmap.put(17, "William");
		tmap.put(42, "Robert");
	

		
		Set set = tmap.entrySet();
		
		Iterator iterator = set.iterator();
		
		while (iterator.hasNext()) {
			Map.Entry mentry = (Map.Entry) iterator.next();
			System.out.print("Key: " + mentry.getKey() +"-----> "+"Value: ");
			System.out.println(mentry.getValue());
		}

	}
}

It is used for storing elements

It maintain LIFO (Last In First Out) order

It usually push(add) and pop(remove) operations are provided

It extend vector class

import java.util.Stack;

public class StackExampe {
	public static void main(String[] args) {
		// Create a Stack 
		//It maintain LIFO(Last In First Out) order
		Stack<String> stack = new Stack<>();

		// insert new elements to the Stack
		stack.push("green");
		stack.push("Red");
		stack.push("Blue");
		stack.push("Yellow");

		System.out.println("Stack: " + stack);
		System.out.println();

		// delete elements from the Stack
		String pop = stack.pop();
		System.out.println("pop: " + pop);
		System.out.println("stack: " + stack);
		System.out.println();

		// Return top of the element
		pop = stack.peek();
		System.out.println("peek: " + pop);
		System.out.println("stack: " + stack);

	}
}

It is used for storing elements

It maintain FIFO (Fast In First Out) order

Queues provide additional insertion, extraction, and inspection operations.

Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value

The offer method inserts an element if possible

The remove() and poll() methods remove and return the head of the queue

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
	public static void main(String[] args) {
		// Queue maintain FIFO(First In First Out) Order
		Queue<Integer> q = new LinkedList<>();

		for (int i = 0; i < 5; i++)
			q.add(i);

		System.out.println("Elements: " + q);

		System.out.println("Elements after removing:" + q.remove());

		System.out.println(q);

		System.out.println("head: " + q.peek());

		System.out.println("size: " + q.size());
	}
}

It is used for storing key - value pairs

It doesn't allow null key or value

The objects used as keys must implement the hashCode method and the equals method

It is synchronized

import java.util.Enumeration;
import java.util.Hashtable;

public class HashTableExample {
	public static void main(String[] args) {

		
		String key;

	
		Hashtable<String, String> hTable = new Hashtable<String, String>();

		
		hTable.put("s1", "Thomas");
		hTable.put("s2", "William");
		hTable.put("s3", "Robert");
		hTable.put("s4", "Jackson");


		Enumeration names = hTable.keys();
		while (names.hasMoreElements()) {
			key = (String) names.nextElement();
			System.out.println("Key: " + key+"---->"+ " Value: " + hTable.get(key));
		}
	}
}

It is used for storing key - value pairs

This navigation methods returning the closest matches for given search targets

Map.Entry objects associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key

import java.util.NavigableMap;
import java.util.TreeMap;

public class NavigableMapExample {
	public static void main(String[] args) {
		NavigableMap<String, Integer> navMap = new TreeMap<String, Integer>();
		navMap.put("A", 1);
		navMap.put("B", 3);
		navMap.put("J", 2);
		navMap.put("T", 6);
		navMap.put("R", 5);
		navMap.put("S", 7);

		System.out.println("Descending Set  : "+ navMap.descendingKeySet());
		//Returns a key-value mapping associated with the greatest key less than or equal to the given key,
		//or null if there is no such key.
		System.out.println("Floor Entry  : "+ navMap.floorEntry("U"));
		System.out.println("First Entry  : "+ navMap.firstEntry());
		System.out.println("Last Key : "+ navMap.lastKey());
		System.out.println("First Key : "+ navMap.firstKey());
		System.out.println("Original Map : "+ navMap);
		System.out.println("Reverse Map : "+ navMap.descendingMap());
	}
}

It is used for storing elements

This navigation methods returning the closest matches for given search targets

A NavigableSet may be accessed and traversed in either ascending or descending order

import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetExample {
	public static void main(String[] args) {
		NavigableSet<Integer> navSet = new TreeSet<>();
		navSet.add(1);
		navSet.add(2);
		navSet.add(3);
		navSet.add(4);
		navSet.add(5);
		navSet.add(5);
		navSet.add(6);

		System.out.println("Normal order: " + navSet);
		System.out.println("Reverse order: " + navSet.descendingSet());

		// Returns a view of the portion of this set whose elements are greater
		// than
		System.out.println("2 or  more:  " + navSet.tailSet(2, true));

		System.out.println("lower: " + navSet.lower(2));
		System.out.println("floor: " + navSet.floor(5));
		System.out.println("higher: " + navSet.higher(2));
		System.out.println("ceiling: " + navSet.ceiling(2));

		System.out.println("pollFirst: " + navSet.pollFirst());
		System.out.println("Navigable Set:  " + navSet);

		System.out.println("pollLast: " + navSet.pollLast());
		System.out.println("Navigable Set:  " + navSet);

	}
}

JAVA 1.12 EXAMPLES

Switch expression, Enhanced switch statement and Multi-constant case labels are Preview features in Java 12.

They are not enabled by default and can by enabled using --enable-preview. In Eclipse, --enable-preview can be enabled from the Preferences

public class SwitchExampleInJava12 {

	@SuppressWarnings("preview")
	public void foo(int i) {
		switch (i) {
		case 2 -> System.out.println("Hello");
		default -> System.out.println("World");
		}
	}

	public static void main(String[] argv) {
		new SwitchExampleInJava12().foo(2);
	}
}

class Test {

	enum Day {
		MON, TUE, WED, THUR, FRI, SAT, SUN
	};

	@SuppressWarnings("preview")
	public String getDay_1(Day today) {
		String day = switch (today) {
		case MON, TUE, WED, THUR, FRI -> "Weekday";
		case SAT, SUN -> "Weekend";
		};
		return day;
	}
}

public class TestSwitch {
	public static void main(String[] argv) {
		Test t = new Test();

		System.out.println(t.getDay_1(Test.Day.MON));
	}
}

JAVA 1.11 EXAMPLES

public class IsBlankExampleInJava11 {
	public static void main(String[] args) throws Exception {
		// Your code here!

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

		String s = "java";
		System.out.println(s.isBlank());
		String s1 = "formula";
		System.out.println(s1.isBlank());
	}
}

import java.util.stream.Collectors;

public class LinesExampleInJava11 {
	  public static void main(String[] args) throws Exception {
	        
	        String str = "Formula\nFormul\nFormu\nForu\nFor"; 
	        System.out.println(str);
	        System.out.println(str.lines().collect(Collectors.toSet()));
	    }
}

public class StringMethodsInJava11 {
	public static void main(String[] args) throws Exception {

        String str = " For "; 
        System.out.print("Start");
        System.out.print(str.strip());
        System.out.println("End");
        
        System.out.print("Start");
        System.out.print(str.stripLeading());
        System.out.println("End");
        
        System.out.print("Start");
        System.out.print(str.stripTrailing());
        System.out.println("End");
    }
}

public class StringRepeatInJava11 {
	public static void main(String[] args) throws Exception {

        String str = "Formula\n".repeat(7);
        System.out.println(str); 
    }
}

import java.util.ArrayList;

public class VarEXampleInJava11 {
	public static void main(String[] args) {
    var list = new ArrayList<String>();
    list.add("java");
    list.add("formula");
    list.forEach(l->System.out.println(l));
	}
}

JAVA 1.9 EXAMPLES

import java.util.stream.IntStream;

public class StreamApiInJava9 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		IntStream.iterate(1, i -> i < 10, i -> i + 1).forEach(System.out::println);
	}

}

import java.util.List;
import java.util.Set;

public class UnmodifibleExampleInJava9 {
	public static void main(String args[]) {
		Set<Integer> ints = Set.of(1, 2, 3);
		List<String> strings = List.of("first", "second");

		for (Integer i : ints) {
			System.out.println(i);
		}

		for (String s : strings) {
			System.out.println(s);
		}
	}
}

public interface PrivateMethodExample {

	default void defaultMthod() {
		init();
	}

	private void init() {
		System.out.println("I'm private method...!");
	}
}

public class PrivateMethodsInInterfaceInJava9 implements PrivateMethodExample {
	public static void main(String[] args) {
		PrivateMethodsInInterfaceInJava9 priv = new PrivateMethodsInInterfaceInJava9();
		priv.defaultMthod();
	}

}

JAVA 1.8-DEFAULT AND STATIC

package com.java18.DefaultAndStatic;

//A simple program to Test Interface default 
//methods in java 
interface TestInterface {
	// abstract method
	public void square(int a);

	// default method
	default void show() {
		System.out.println("Default Method Executed");
	}
}

class DefaultMethod implements TestInterface {
	// implementation of square abstract method
	public void square(int a) {
		System.out.println(a * a);
	}

	public static void main(String args[]) {
		DefaultMethod d = new DefaultMethod();
		d.square(4);

		// default method executed
		d.show();
	}
}

package com.java18.DefaultAndStatic;

// A simple Java program to demonstrate multiple 
// inheritance through default methods. 
interface TestInterface1 {
	// default method
	default void show() {
		System.out.println("Default TestInterface1");
	}
}

interface TestInterface2 {
	// Default method
	default void show() {
		System.out.println("Default TestInterface2");
	}
}

// Implementation class code
class MultipleInheritanceInDefault implements TestInterface1, TestInterface2 {
	// Overriding default show method
	public void show() {
		// use super keyword to call the show
		// method of TestInterface1 interface
		TestInterface1.super.show();

		// use super keyword to call the show
		// method of TestInterface2 interface
		TestInterface2.super.show();
	}

	public static void main(String args[]) {
		MultipleInheritanceInDefault d = new MultipleInheritanceInDefault();
		d.show();
	}
}

package com.java18.DefaultAndStatic;

//A simple Java program to TestClassnstrate static 
//methods in java 
interface StaticInterface {
	// abstract method
	public void square(int a);

	// static method
	static void show() {
		System.out.println("Static Method Executed");
	}
}

class StaticMethod implements StaticInterface {
	// Implementation of square abstract method
	public void square(int a) {
		System.out.println(a * a);
	}

	public static void main(String args[]) {
		StaticMethod d = new StaticMethod();
		d.square(4);

		// Static method executed
		StaticInterface.show();
	}
}

JAVA 1.8-HASHMAP

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;

//If you want to apply a function on all the mappings based on it’s key and value, 
//then compute method should be used. 
//If there is no mapping and this method is used, value will be null for compute function
public class HashMapComputeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		System.out.println("map before compute = "+map);
		for (String key : map.keySet()) {
			map.compute(key, (k,v) -> {return k+v;});
		}
		map.compute("5", (k,v) -> {return k+v;}); //key not present, v = null
		System.out.println("map after compute = "+map);
	}

}

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;


//HashMap computeIfAbsent method computes the value only
//if key is not present in the map. After computing the value, 
//it’s put in the map if it’s not null.
public class HashMapComputeIfAbsent {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");

	
		//lambda way
		map.computeIfAbsent("4", v -> {return v;});
		map.computeIfAbsent("5", v -> {return null;}); //null value won't get inserted
		System.out.println(map);
	}

}

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;

//Java HashMap computeIfPresent method recomputes the value 
//if the specified key is present and value is not-null. 
//If the function returns null, the mapping is removed.
public class HashMapComputeIfPresent {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");
		map.put("10", null);

		System.out.println("map before computeIfPresent = " + map);


		map.computeIfPresent("1", (k,v) -> {return null;}); // mapping will be removed
		System.out.println("map after computeIfPresent = " + map);

	}

}

package com.java18.hashmap;


import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapExample {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<>();

		map.put("1", "1"); // put example
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", null); // null value
		map.put(null, "100"); // null key

		String value = map.get("3"); // get example
		System.out.println("Key = 3, Value = " + value);

		value = map.getOrDefault("5", "Default Value");
		System.out.println("Key = 5, Value=" + value);

		boolean keyExists = map.containsKey(null);
		boolean valueExists = map.containsValue("100");

		System.out.println("keyExists=" + keyExists + ", valueExists=" + valueExists);

		Set<Entry<String, String>> entrySet = map.entrySet();
		System.out.println(entrySet);

		System.out.println("map size=" + map.size());

		Map<String, String> map1 = new HashMap<>();
		map1.putAll(map);
		System.out.println("map1 mappings= " + map1);

		String nullKeyValue = map1.remove(null);
		System.out.println("map1 null key value = " + nullKeyValue);
		System.out.println("map1 after removing null key = " + map1);

		Set<String> keySet = map.keySet();
		System.out.println("map keys = " + keySet);

		Collection<String> values = map.values();
		System.out.println("map values = " + values);

		map.clear();
		System.out.println("map is empty=" + map.isEmpty());

	}

}

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


//If the specified key is not present or is associated with null, 
//then associates it with the given non-null value. Otherwise,
//replaces the associated value with the results of the given remapping function, or removes 
//if the result is null.
public class HashMapMergeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			//merge throws NullPointerException if key or value is null
			if(key != null && value != null) 
			map.merge(entry.getKey(), entry.getValue(), 
					(k, v) -> {return k + v;});
		}
		System.out.println(map);
		
		map.merge("5", "5", (k, v) -> {return k + v;}); // key not present
		System.out.println(map);
		
		map.merge("1", "1", (k, v) -> {return null;}); // method return null, so remove
		System.out.println(map);

	}

}

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;

public class HashMapPutIfAbsentExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		System.out.println("map before putIfAbsent = "+map);
		String value = map.putIfAbsent("1", "4");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
		
		System.out.println("map before putIfAbsent = "+map);
		value = map.putIfAbsent("3", "3");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
	}

}

package com.java18.hashmap;


import java.util.HashMap;
import java.util.Map;

public class HashMapReplaceAllExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "100");

		System.out.println("map before replaceAll = " + map);
		
		System.out.println("map after replaceAll = " + map);

		// replaceAll using lambda expressions
		map.replaceAll((k, v) -> {
			if (k != null) return k + v;
			else return v;});
		System.out.println("map after replaceAll lambda expression = " + map);

	}

}

package com.java18.hashmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class IterateOverHashMap {
    public static void main(String[] args) {
        Map<String, Double> employeeSalary = new HashMap<>();
        employeeSalary.put("David", 76000.00);
        employeeSalary.put("John", 120000.00);
        employeeSalary.put("Mark", 95000.00);
        employeeSalary.put("Steven", 134000.00);

        System.out.println("=== Iterating over a HashMap using Java 8 forEach and lambda ===");
        employeeSalary.forEach((employee, salary) -> {
            System.out.println(employee + " => " + salary);
        });

        System.out.println("\n=== Iterating over the HashMap's entrySet using iterator() ===");
        Set<Map.Entry<String, Double>> employeeSalaryEntries = employeeSalary.entrySet();
        Iterator<Map.Entry<String, Double>> employeeSalaryIterator = employeeSalaryEntries.iterator();
        while (employeeSalaryIterator.hasNext()) {
            Map.Entry<String, Double> entry = employeeSalaryIterator.next();
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("\n=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===");
        employeeSalary.entrySet().forEach(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });

        System.out.println("\n=== Iterating over the HashMap's entrySet using simple for-each loop ===");
        for(Map.Entry<String, Double> entry: employeeSalary.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("\n=== Iterating over the HashMap's keySet ===");
        employeeSalary.keySet().forEach(employee -> {
            System.out.println(employee + " => " + employeeSalary.get(employee));
        });
    }
}

JAVA 1.8-LAMBDA EXPRESSIONS

package com.java18.lambda;

import java.math.BigDecimal;

public class Developer {
	private String name;
	private BigDecimal sal;
	private int age;

	public Developer(String name, BigDecimal sal, int age) {
		super();
		this.name = name;
		this.sal = sal;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public BigDecimal getSal() {
		return sal;
	}

	public void setSal(BigDecimal sal) {
		this.sal = sal;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

package com.java18.lambda;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class SortWithLambda {

	public static void main(String[] args) {

		List<Developer> listDevs = getDevelopers();

		System.out.println("---------Before Sort---------");
		for (Developer developer : listDevs) {
			System.out.println(developer.getName() + " " + developer.getSal() + " " + developer.getAge());
		}

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

		// lambda here!
		listDevs.sort((Developer o1, Developer o2) -> o1.getAge() - o2.getAge());

		// java 8 only, lambda also, to print the List
		listDevs.forEach((developer) -> System.out
				.println(developer.getName() + " " + developer.getSal() + " " + developer.getAge()));
	}

	private static List<Developer> getDevelopers() {

		List<Developer> result = new ArrayList<Developer>();

		result.add(new Developer("mkyong", new BigDecimal("70000"), 33));
		result.add(new Developer("alvin", new BigDecimal("80000"), 20));
		result.add(new Developer("jason", new BigDecimal("100000"), 10));
		result.add(new Developer("iris", new BigDecimal("170000"), 55));

		return result;

	}

}

JAVA 1.8-STREAMS

package com.java18.streams;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConvertMapToList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");

        System.out.println("\n1. Export Map Key to List...");

        List<Integer> result = map.keySet().stream()
                .collect(Collectors.toList());

        result.forEach(System.out::println);

        System.out.println("\n2. Export Map Value to List...");

        List<String> result2 = map.values().stream()
                .collect(Collectors.toList());

        result2.forEach(System.out::println);

       
        
        

    }

}

package com.java18.streams;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountingStreams {

	public static void main(String[] args) {

		// 3 apple, 2 banana, others 1
		List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");

		Map<String, Long> result = items.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

		System.out.println(result);

	}
}

package com.java18.streams;

import java.util.Arrays;
import java.util.stream.Stream;

public class FlatMap {


	    public static void main(String[] args) {

	        String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};

	        //Stream<String[]>
	        Stream<String[]> temp = Arrays.stream(data);

	        //Stream<String>, GOOD!
	        Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));

	        Stream<String> stream = stringStream.filter(x -> "a".equals(x.toString()));

	        stream.forEach(System.out::println);

			
	    }

	}

package com.java18.streams;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FlatMapSet {

	    public static void main(String[] args) {

	        Student obj1 = new Student();
	        obj1.setName("formula");
	        obj1.addBook("Java 8 in Action");
	        obj1.addBook("Spring Boot in Action");
	        obj1.addBook("Effective Java (2nd Edition)");

	        Student obj2 = new Student();
	        obj2.setName("zilap");
	        obj2.addBook("Learning Python, 5th Edition");
	        obj2.addBook("Effective Java (2nd Edition)");

	        List<Student> list = new ArrayList<>();
	        list.add(obj1);
	        list.add(obj2);

	        List<String> collect =
	                list.stream()
	                        .map(x -> x.getBook())      //Stream<Set<String>>
	                        .flatMap(x -> x.stream())   //Stream<String>
	                        .distinct()
	                        .collect(Collectors.toList());

	        collect.forEach(x -> System.out.println(x));
	    }

	}

package com.java18.streams;

import java.util.HashSet;
import java.util.Set;

public class Student {

	private String name;
	private Set<String> book;

	public void addBook(String book) {
		if (this.book == null) {
			this.book = new HashSet<>();
		}
		this.book.add(book);
	}
	// getters and setters

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<String> getBook() {
		return book;
	}

	public void setBook(Set<String> book) {
		this.book = book;
	}

}

package com.java18.streams;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListToMap {

	public static void main(String[] args) {

		List<Web> list = new ArrayList<>();
		list.add(new Web(1, "liquidweb.com", 80000));
		list.add(new Web(2, "linode.com", 90000));
		list.add(new Web(3, "digitalocean.com", 120000));
		list.add(new Web(4, "aws.amazon.com", 200000));
		list.add(new Web(5, "mkyong.com", 1));

		// key = id, value - websites
		Map<Integer, String> result1 = list.stream().collect(Collectors.toMap(Web::getId, Web::getName));

		System.out.println("Result 1 : " + result1);

		// key = name, value - websites
		Map<String, Long> result2 = list.stream().collect(Collectors.toMap(Web::getName, Web::getWebsites));

		System.out.println("Result 2 : " + result2);

		// Same with result1, just different syntax
		// key = id, value = name
		Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));

		System.out.println("Result 3 : " + result3);
	}
}

package com.java18.streams;

public class Web {

	private int Id;
	private String name;
	private long websites;

	public int getId() {
		return Id;
	}

	public void setId(int id) {
		Id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getWebsites() {
		return websites;
	}

	public void setWebsites(long websites) {
		this.websites = websites;
	}

	public Web(int id, String name, long websites) {
		super();
		Id = id;
		this.name = name;
		this.websites = websites;
	}

	// getters, setters and toString()
}

package com.java18.streams;

import java.util.stream.Stream;

public class StreamOfElements
{
     public static void main(String[] args)
     {
         Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
         stream.forEach(p -> System.out.println(p));
     }
}	

package com.java18.streams;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFilter {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("spring", "node", "formula");

        List<String> result = lines.stream()                // convert list to stream
                .filter(line -> !"formula".equals(line))     // we dont like mkyong
                .collect(Collectors.toList());              // collect the output and convert streams to a List

        result.forEach(System.out::println);                //output : spring, node

    }

}

package com.java18.streams;

import java.util.Arrays;
import java.util.List;

public class StreamFilterFindAnyElse {


    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("formula", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()                        // Convert to steam
                .filter(x -> "jack".equals(x.getName()))        // we want "jack" only
                .findAny()                                      // If 'findAny' then return found
                .orElse(null);                                  // If not found, return null

        System.out.println(result1);
        
        Person result2 = persons.stream()
                .filter(x -> "ahmook".equals(x.getName()))
                .findAny()
                .orElse(null);

        System.out.println(result2);

    }

}

package com.java18.streams;

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

    //gettersm setters, toString
}

package com.java18.streams;



import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SumQtnty {


	    public static void main(String[] args) {

	        //3 apple, 2 banana, others 1
	        List<Fruit> items = Arrays.asList(
	                new Fruit("apple", 10, new BigDecimal("9.99")),
	                new Fruit("banana", 20, new BigDecimal("19.99")),
	                new Fruit("orang", 10, new BigDecimal("29.99")),
	                new Fruit("watermelon", 10, new BigDecimal("29.99")),
	                new Fruit("papaya", 20, new BigDecimal("9.99")),
	                new Fruit("apple", 10, new BigDecimal("9.99")),
	                new Fruit("banana", 10, new BigDecimal("19.99")),
	                new Fruit("apple", 20, new BigDecimal("9.99"))
	        );

	        Map<String, Long> counting = items.stream().collect(
	                Collectors.groupingBy(Fruit::getName, Collectors.counting()));

	        System.out.println(counting);

	        Map<String, Integer> sum = items.stream().collect(
	                Collectors.groupingBy(Fruit::getName, Collectors.summingInt(Fruit::getQty)));

	        System.out.println(sum);

	    }
	}

package com.java18.streams;

import java.math.BigDecimal;

public class Fruit {

	private String name;
	private int qty;
	private BigDecimal price;

	public Fruit(String name, int qty, BigDecimal price) {
		super();
		this.name = name;
		this.qty = qty;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getQty() {
		return qty;
	}

	public void setQty(int qty) {
		this.qty = qty;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	// constructors, getter/setters
}

package com.java18.streams;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class TestMapFilter {

    public static void main(String[] args) {

        Map<Integer, String> web = new HashMap<>();
        web.put(1, "linode.com");
        web.put(2, "heroku.com");
        web.put(3, "digitalocean.com");
        web.put(4, "aws.amazon.com");

        // Before Java 8
        String result = "";
        for (Map.Entry<Integer, String> entry : web.entrySet()) {
            if ("aws.amazon.com".equals(entry.getValue())) {
                result = entry.getValue();
            }
        }
        System.out.println("Before Java 8 : " + result);

        //Map -> Stream -> Filter -> String
        result = web.entrySet().stream()
                .filter(map -> "aws.amazon.com".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("With Java 8 : " + result);

        // filter more values
        result = web.entrySet().stream()
                .filter(x -> {
                    if (!x.getValue().contains("amazon") && !x.getValue().contains("digital")) {
                        return true;
                    }
                    return false;
                })
                .map(map -> map.getValue())
                .collect(Collectors.joining(","));

        System.out.println("With Java 8 : " + result);

    }

}

package com.java18.streams;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class TestMapFilter2 {

    public static void main(String[] args) {

        Map<Integer, String> web = new HashMap<>();
        web.put(1, "linode.com");
        web.put(2, "heroku.com");
        web.put(3, "digitalocean.com");
        web.put(4, "aws.amazon.com");

        //Map -> Stream -> Filter -> Map
        Map<Integer, String> collect = web.entrySet().stream()
                .filter(map -> map.getKey() == 2)
                .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

        System.out.println(collect); //output : {2=heroku.com}

        Map<Integer, String> collect2 = web.entrySet().stream()
                .filter(map -> map.getKey() <= 3)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(collect2); //output : {1=linode.com, 2=heroku.com, 3=digitalocean.com}

    }

}

package com.java18.streams;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class TestMapFilter3 {

	// Generic Map filterbyvalue, with predicate
    public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
        return map.entrySet()
                .stream()
                .filter(x -> predicate.test(x.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public static void main(String[] args) {

        Map<Integer, String> web = new HashMap<>();
        web.put(1, "linode.com");
        web.put(2, "heroku.com");
        web.put(3, "digitalocean.com");
        web.put(4, "aws.amazon.com");
        web.put(5, "aws2.amazon.com");

        //  {1=linode.com}
        Map<Integer, String> filteredMap = filterByValue(web, x -> x.contains("linode"));
        System.out.println(filteredMap);

        // {1=linode.com, 4=aws.amazon.com, 5=aws2.amazon.com}
        Map<Integer, String> filteredMap2 = filterByValue(web, x -> (x.contains("aws") || x.contains("linode")));
        System.out.println(filteredMap2);

        // {4=aws.amazon.com}
        Map<Integer, String> filteredMap3 = filterByValue(web, x -> (x.contains("aws") && !x.contains("aws2")));
        System.out.println(filteredMap3);

        // {1=linode.com, 2=heroku.com}
        Map<Integer, String> filteredMap4 = filterByValue(web, x -> (x.length() <= 10));
        System.out.println(filteredMap4);

    }

}

W3.CSS

ARRAYS

public class PairsOfElementsEqualsToNumberInArray {
	static void findThePairs(int inputArray[], int inputNumber) {
		System.out.println("Pairs of elements whose sum is " + inputNumber + " are : ");

		for (int i = 0; i < inputArray.length; i++) {
			for (int j = i + 1; j < inputArray.length; j++) {
				if (inputArray[i] + inputArray[j] == inputNumber) {
					System.out.println(inputArray[i] + " + " + inputArray[j] + " = " + inputNumber);
				}
			}
		}
	}

	public static void main(String[] args) {
		findThePairs(new int[] { 4, 6, 5, -10, 8, 5, 20 }, 11);

		findThePairs(new int[] { 4, -5, 9, 11, 25, 13, 12, 8 }, 20);

		findThePairs(new int[] { 12, 13, 40, 15, 8, 10, -15 }, 25);

		findThePairs(new int[] { 12, 23, 125, 41, -75, 38, 27, 11 }, 50);
	}
}


public class EightQueensProblem {


   /***************************************************************************
    * Prints n-by-n placement of queens in ASCII.
    ***************************************************************************/
    public static void printQueens(int[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (a[i] == j) System.out.println("Q ");
                else           System.out.println("* ");
            }
            System.out.println();
        }  
        System.out.println();
    }

   /***************************************************************************
    * Solve the n queens problem by brute force.
    ***************************************************************************/
    public static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    // try all n! permutations, but prune useless ones
    public static void enumerate(int[] a, boolean[] diag1, boolean[] diag2, int k) {
        int n = a.length;

        // found one, so print out and stop
        if (k == 0) {
            printQueens(a);
            // System.exit(0);
        }

        for (int i = 0; i < k; i++) {
            swap(a, i, k-1);
            int j = k-1;

            // if placement of new queen is ok, then enumerate
            if (!diag1[j + a[j]] && !diag2[n + j - a[j]]) {
                diag1[j + a[j]] = true;
                diag2[n + j - a[j]] = true;
                enumerate(a, diag1, diag2, k-1);
                diag1[j + a[j]] = false;
                diag2[n + j - a[j]] = false;
            }
            swap(a, i, k-1);
        }
    }  


    public static void main(String[] args) {
        int n = 5;
        int[] a         = new int[n];         // a[i] = row of queen in ith column
        boolean[] diag1 = new boolean[2*n];   // is ith top diagonal occupied?
        boolean[] diag2 = new boolean[2*n];   // is ith bottom diagonal occupied?
        for (int i = 0; i < n; i++)
            a[i] = i;
        enumerate(a, diag1, diag2, n);
    }


}

public class RotateClockWise {

	static int arr[] = new int[] { 10, 20, 30, 40, 50, 60 };

	static void rotate_array() {
		int a = arr[arr.length - 1], i;
		for (i = arr.length - 1; i > 0; i--)
			arr[i] = arr[i - 1];
		arr[0] = a;
	}

	public static void main(String[] args) {
		System.out.println("Original arraay:");
		System.out.println(Arrays.toString(arr));

		rotate_array();

		System.out.println("Rotated arraay:");
		System.out.println(Arrays.toString(arr));
	}
}

import java.util.Arrays;

public class EvenFirstOddSecond {

	public static void main(String[] args) {
		int[] nums = { 7, 2, 4, 1, 3, 5, 6, 8, 2, 10 };
		System.out.println("Original array: " + Arrays.toString(nums));
		int[] result = partitionArray2(nums);
		System.out.println("After partition the said array becomes: " + Arrays.toString(result));
	}

	public static int[] partitionArray2(int[] nums) {
		int i = 0;
		int j = nums.length - 1;
		while (i < j) {
			while (nums[i] % 2 == 0)
				i++;
			while (nums[j] % 2 != 0)
				j--;
			if (i < j) {
				int temp = nums[i];
				nums[i] = nums[j];
				nums[j] = temp;
			}
		}
		return nums;
	}
}

import java.util.Arrays;

public class FindCommonElements {

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

		System.out.println("Array1 : " + Arrays.toString(arr1));
		System.out.println("Array2 : " + Arrays.toString(arr2));

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

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

	}
}

public class FindDuplicates {

	public static void main(String[] args) {
		int[] arr = { 1, 2, 5, 5, 6, 6, 7, 2 };

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

import java.util.Arrays;

public class FindEvenAndOdds {

	public static void main(String[] args) {
		int[] arr = { 5, 7, 2, 4, 9 };
		System.out.println("Original Array: " + Arrays.toString(arr));
		int count = 0;
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] % 2 == 0)
				count++;
		}
		System.out.println("Number of even numbers : " + count);
		System.out.println("Number of odd numbers  : " + (arr.length - count));
	}
}

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class FindMedian {

	public static void main(String[] args) {
		int[] nums = { 10, 2, 38, 23, 38, 23, 21 };
		System.out.println(Arrays.toString(nums));
		int n = nums.length;
		if (n < 1) {
			System.out.printf("False");
		}
		Queue<Integer> min = new PriorityQueue<Integer>(n);
		for (int num : nums) {
			min.add(num);
		}
		if ((n & 1) == 0) {
			n >>= 1;
			n -= 1;
		} else {
			n >>= 1;
		}
		int i = 0;
		while (i < n) {
			min.remove();
			i++;
		}
		System.out.print(min.remove());
	}
}

package com.arrays;

import java.util.Arrays;

public class FindMinMaxValue {

	static int max;
	static int min;

	public static void max_min(int arr[]) {
		max = arr[0];
		min = arr[0];
		int len = arr.length;
		for (int i = 1; i < len - 1; i = i + 2) {
			if (i + 1 > len) {
				if (arr[i] > max)
					max = arr[i];
				if (arr[i] < min)
					min = arr[i];
			}
			if (arr[i] > arr[i + 1]) {
				if (arr[i] > max)
					max = arr[i];
				if (arr[i + 1] < min)
					min = arr[i + 1];
			}
			if (arr[i] < arr[i + 1]) {
				if (arr[i] < min)
					min = arr[i];
				if (arr[i + 1] > max)
					max = arr[i + 1];
			}
		}
	}

	public static void main(String[] args) {
		int[] arr = { 25, 14, 56, 15, 36, 56, 77, 18, 29, 49 };
		max_min(arr);
		System.out.println(" Original Array: " + Arrays.toString(arr));
		System.out.println(" Maximum value  = " + max);
		System.out.println(" Minimum value  = " + min);
	}
}

package com.arrays;

import java.util.Arrays;

public class FindSecondLargest {

	public static void main(String[] args) {
		int[] arr = { 10789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165, 1457, 2456 };
		System.out.println("Original numeric array : " + Arrays.toString(arr));
		Arrays.sort(arr);
		int index = arr.length - 1;
		while (arr[index] == arr[arr.length - 1]) {
			index--;
		}
		System.out.println("Second largest value: " + arr[index]);
	}
}

package com.arrays;

import java.util.Arrays;

public class FindSecondSmallest {

	public static void main(String[] args) {

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

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

package com.arrays;

import java.util.Arrays;

public class InsertElementIntoAnArray {

	public static void main(String[] args) {

		int[] arr = { 25, 14, 56, 15, 36, 56, 77, 18, 29, 49 };

		// Insert an element in 3rd position of the array (index->2, value->5)

		int index = 2;
		int val = 5;

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

		for (int i = arr.length - 1; i > index; i--) {
			arr[i] = arr[i - 1];
		}
		arr[index] = val;
		System.out.println("New Array: " + Arrays.toString(arr));
	}
}

package com.arrays;

import java.util.Scanner;

public class IntegerToStringFormat {

	public static String transform_int_to_string(int n) {
		boolean is_negative = false;
		StringBuilder tsb = new StringBuilder();
		if (n == 0) {
			return "0";
		} else if (n < 0) {
			is_negative = true;
		}
		n = Math.abs(n);
		while (n > 0) {
			tsb.append(n % 10);
			n /= 10;
		}
		if (is_negative) {
			tsb.append("-");
		}
		return tsb.reverse().toString();
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Input an integer: ");
		int n = in.nextInt();
		System.out.println("String format of the said integer: " + transform_int_to_string(n));
	}
}

package com.arrays;

import java.util.Arrays;
import java.util.Collections;

public class KLargestElementsInArray {

	public static void main(String[] args) {
		Integer arr[] = new Integer[] { 1, 4, 17, 7, 25, 3, 100 };
		int k = 3;
		System.out.println("Original Array: ");
		System.out.println(Arrays.toString(arr));
		System.out.println(k + " largest elements of the said array are:");
		Arrays.sort(arr, Collections.reverseOrder());
		for (int i = 0; i < k; i++)
			System.out.print(arr[i] + " ");
	}
}

package com.arrays;

import java.util.Arrays;
import java.util.Collections;

public class KthLargestSmallest {

	public static void main(String[] args) {
		Integer arr[] = new Integer[] { 1, 4, 17, 7, 25, 3, 100 };
		int k = 2;
		System.out.println("Original Array: ");
		System.out.println(Arrays.toString(arr));
		System.out.println("K'th smallest element of the said array: ");
		Arrays.sort(arr);
		System.out.print(arr[k - 1] + " ");
		System.out.println("\nK'th largest element of the said array:");
		Arrays.sort(arr, Collections.reverseOrder());
		System.out.print(arr[k - 1] + " ");
	}
}

package com.arrays;

public class MissingNumber {

	public static void main(String[] args) {

		int total;
		int[] num = new int[] { 1, 2, 3, 4, 6, 7 };
		total = 7;
		int result = total * ((total + 1) / 2);
		int sum = 0;
		for (int i : num) {
			sum += i;
		}
		System.out.print(result - sum);
		System.out.print("\n");
	}
}

package com.arrays;

public class MoveAllZerosToEnd {

	public static void main(String[] args) throws Exception {
		int[] arr = { 0, 0, 1, 0, 3, 0, 5, 0, 6 };
		int i = 0;
		System.out.print("\nOriginal array: \n");
		for (int n : arr)
			System.out.print(n + "  ");

		for (int j = 0, l = arr.length; j < l;) {
			if (arr[j] == 0)
				j++;
			else {
				int temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
				i++;
				j++;
			}
		}
		while (i < arr.length)
			arr[i++] = 0;
		System.out.print("\nAfter moving 0's to the end of the array: \n");
		for (int n : arr)
			System.out.print(n + "  ");
		System.out.print("\n");
	}
}

package com.arrays;

import java.util.Scanner;

public class MultipyWithoutOperator {

	public static int multiply(int n1, int n2) {
		int result = 0;
		boolean negative_num = (n1 < 0 && n2 >= 0) || (n2 < 0 && n1 >= 0);
		boolean positive_num = !negative_num;
		n1 = Math.abs(n1);
		for (int i = 0; i < n1; i++) {
			if (negative_num && n2 > 0 || positive_num && n2 < 0)
				result -= n2;
			else
				result += n2;
		}

		return result;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Input the first number: ");
		int n1 = in.nextInt();
		System.out.print("Input the second number: ");
		int n2 = in.nextInt();
		System.out.println("\nResult: " + multiply(n1, n2));
	}

}

package com.arrays;

import java.util.Arrays;

public class PositiveRightNegativeLeft {

	public static int[] split_sorting_array(int[] nums) {
		if (nums == null) {
			throw new IllegalArgumentException("Null array......!");
		}
		boolean flag = true;
		while (flag) {
			flag = false;
			for (int j = 0; j < nums.length - 1; j++) {
				if (nums[j] > nums[j + 1]) {
					swap(nums, j, j + 1);
					flag = true;
				}
			}
		}
		return nums;
	}

	private static void swap(int[] nums, int left, int right) {
		int temp = nums[right];
		nums[right] = nums[left];
		nums[left] = temp;
	}

	public static void main(String[] args) {
		int[] nums = { -2, 3, 4, -1, -3, 1, 2, -4, 0 };
		System.out.println("\nOriginal array: " + Arrays.toString(nums));
		int[] result = split_sorting_array(nums);
		System.out.println("\nResult: " + Arrays.toString(result));
	}
}

package com.arrays;

import java.util.Arrays;

public class RemoveDuplicates {

	static void unique_array(int[] arr) {
		System.out.println("Original Array : ");

		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
		}

		// Assuming all elements in input array are unique

		int no_unique_elements = arr.length;

		// Comparing each element with all other elements

		for (int i = 0; i < no_unique_elements; i++) {
			for (int j = i + 1; j < no_unique_elements; j++) {
				// If any two elements are found equal

				if (arr[i] == arr[j]) {
					// Replace duplicate element with last unique element

					arr[j] = arr[no_unique_elements - 1];

					no_unique_elements--;

					j--;
				}
			}
		}

		// Copying only unique elements of my_array into array1

		int[] arr1 = Arrays.copyOf(arr, no_unique_elements);

		// Printing arrayWithoutDuplicates

		System.out.println();

		System.out.println("Array with unique values : ");

		for (int i = 0; i < arr1.length; i++) {
			System.out.print(arr1[i] + "\t");
		}

		System.out.println();

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

	public static void main(String[] args) {
		unique_array(new int[] { 0, 3, -2, 4, 3, 2 });

		unique_array(new int[] { 10, 22, 10, 20, 11, 22 });

	}
}

package com.arrays;

import java.util.Arrays;

public class ReverseOrder {


	public static void main(String[] args){   
	    int[] arr = {
	            1789, 2035, 1899, 1456, 2013, 
	            1458, 2458, 1254, 1472, 2365, 
	            1456, 2165, 1457, 2456};
	  System.out.println("Original array : "+Arrays.toString(arr));  
	   for(int i = 0; i < arr.length / 2; i++)
	  {
	    int temp = arr[i];
	    arr[i] = arr[arr.length - i - 1];
	    arr[arr.length - i - 1] = temp;
	  }
	    System.out.println("Reverse array : "+Arrays.toString(arr));
	 }
	}

package com.arrays;

import java.util.Arrays;

public class RotateArray {

	 public static void main(String[] args)
	 {
	    int[] arr = {20, 30, 40};
		System.out.println("Original Array: "+Arrays.toString(arr)); 
		int[] arr1 = {arr[1], arr[2], arr[0]};
		System.out.println("Rotated Array: "+Arrays.toString(arr1)); 	 
	 }
	}

package com.arrays;

import java.util.Arrays;

public class SeparateEvenAndOdd {

	public static void main(String[] args) {
		int nums[] = { 20, 12, 23, 17, 7, 8, 10, 2, 1, 0 };
		int result[];
		System.out.println("Original Array ");
		System.out.println(Arrays.toString(nums));

		result = separate_odd_even(nums);

		System.out.print("Array after separation ");
		System.out.println(Arrays.toString(result));
	}

	static int[] separate_odd_even(int arr[]) {
		int left_side = 0, right_side = arr.length - 1;
		while (left_side < right_side) {
			while (arr[left_side] % 2 == 0 && left_side < right_side)
				left_side++;

			while (arr[right_side] % 2 == 1 && left_side < right_side)
				right_side--;

			if (left_side < right_side) {
				int temp = arr[left_side];
				arr[left_side] = arr[right_side];
				arr[right_side] = temp;
				left_side++;
				right_side--;
			}
		}
		return arr;
	}
}

package com.arrays;

public class SumEqualToNumber {

	static void pairs_value(int inputArray[], int input) {
		System.out.println("Pairs of elements and their sum : ");

		for (int i = 0; i < inputArray.length; i++) {
			for (int j = i + 1; j < inputArray.length; j++) {
				if (inputArray[i] + inputArray[j] == input) {
					System.out.println(inputArray[i] + " + " + inputArray[j] + " =  " + input);
				}
			}
		}
	}

	public static void main(String[] args) {
		pairs_value(new int[] { 2, 7, 4, -5, 11, 5, 20 }, 15);

		pairs_value(new int[] { 14, -15, 9, 16, 25, 45, 12, 8 }, 30);

	}
}

package com.arrays;

import java.util.Arrays;

public class ZerosLeftOnesRight {

	public static void main(String[] args) {
		int nums[] = { 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1 };
		int i, length = nums.length;
		int left = 0, right = length - 1;

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

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

			/* While we see 1 at right decrement right index */
			while (nums[right] == 1 && left < right)
				right--;

			if (left < right) {
				nums[left] = 0;
				nums[right] = 1;
				left++;
				right--;
			}
		}

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

STRINGS

package com.strings;

public class Combinations {

	// print all subsets of the characters in s
	public static void comb1(String s) {
		comb1("", s);
	}

	// print all subsets of the remaining elements, with given prefix
	private static void comb1(String prefix, String s) {
		if (s.length() > 0) {
			System.out.println(prefix + s.charAt(0));
			comb1(prefix + s.charAt(0), s.substring(1));
			comb1(prefix, s.substring(1));
		}
	}

	// alternate implementation
	public static void comb2(String s) {
		comb2("", s);
	}

	private static void comb2(String prefix, String s) {
		System.out.println(prefix);
		for (int i = 0; i < s.length(); i++)
			comb2(prefix + s.charAt(i), s.substring(i + 1));
	}

	// read in N from command line, and print all subsets among N elements
	public static void main(String[] args) {
		int n = 3;
		String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String elements = alphabet.substring(0, n);

		// using first implementation
		comb1(elements);
		System.out.println();

		// using second implementation
		comb2(elements);
		System.out.println();
	}

}

package com.strings;

public class CombinationsK {


	    // print all subsets that take k of the remaining elements, with given prefix 
	    public  static void comb1(String s, int k) { comb1(s, "", k); }
	    private static void comb1(String s, String prefix, int k) {
	        if (s.length() < k) return;
	        else if (k == 0) System.out.println(prefix);
	        else {
	            comb1(s.substring(1), prefix + s.charAt(0), k-1);
	            comb1(s.substring(1), prefix, k);
	        }
	    }  


	    // print all subsets that take k of the remaining elements, with given prefix 
	    public  static void comb2(String s, int k) { comb2(s, "", k); }
	    private static void comb2(String s, String prefix, int k) {
	        if (k == 0) System.out.println(prefix);
	        else {
	            for (int i = 0; i < s.length(); i++)
	                comb2(s.substring(i + 1), prefix + s.charAt(i), k-1);
	        }
	    }  

	    // reads in two integer command-line arguments n and k and
	    // print all subsets of size k from n elements
	    public static void main(String[] args) {
	        int n = 5;
	        int k = 3;
	        String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	        String elements = alphabet.substring(0, n);

	        comb1(elements, k);
	        System.out.println();
	        comb2(elements, k);
	    }

	}

package com.strings;


public class Converter { 

   // converts integer n into a base b string
    public static String toString(int n, int base) {
        // special case
        if (n == 0) return "0";

        String s = "";
        while (n > 0) {
            s = toChar(n % base) + s;
            n = n / base;
        }
        return s;
    }

    // converts integer n into a base b string
    public static String toStringRecursive(int n, int base) {
        if (n == 0) return "";
        return toStringRecursive(n/base, base) + toChar(n % base);
    }

    // convert a String representing a base b integer into an int
    public static int parseInt(String s, int base) {
        int n = 0;
        for (int i = 0; i < s.length(); i++)
            n = base*n + toInt(s.charAt(i));
        return n;
    }

    public static int toInt(char c) {
        if (c < '0' || c > 'Z') throw new IllegalArgumentException("invalid char");
        if ((c >= '0') && (c <= '9')) return c - '0';
        return c - 'A' + 10;
    }

    public static char toChar(int i) {
        if (i < 0 || i > 36) throw new IllegalArgumentException("invalid digit");
        if (i < 10) return (char) ('0' + i);
        return (char) ('A' + i - 10);
    }


    // sample test client
    public static void main(String[] args) {
      
            String s = "FACE";
            int baseFrom = 16;
            int baseTo =2;
            int n = parseInt(s, baseFrom);
            System.out.println(toString(n, baseTo));
    
    }
}

package com.strings;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class ConvertStringToDate {

	public static void main(String[] args) {
		String string = "May 1, 2016";
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
		LocalDate date = LocalDate.parse(string, formatter);
		System.out.println();
		System.out.println(date);
		System.out.println();
	}
}

package com.strings;

import java.util.Scanner;

public class CountAllVowels {

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

package com.strings;

import java.util.Scanner;

public class CountAllWords {

	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 words in the string: " + count_Words(str) + "\n");
	}

	public static int count_Words(String str) {
		int count = 0;
		if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))) {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) == ' ') {
					count++;
				}
			}
			count = count + 1;
		}
		return count; // returns 0 if string starts or ends with space " ".
	}
}

package com.strings;

public class FindMaxOccurance {

	static final int N = 256;

	static char MaxOccuringChar(String str1) {
		int num[] = new int[N];
		int l = str1.length();
		for (int i = 0; i < l; i++)
			num[str1.charAt(i)]++;
		int max = -1;
		char result = ' ';

		for (int i = 0; i < l; i++) {
			if (max < num[str1.charAt(i)]) {
				max = num[str1.charAt(i)];
				result = str1.charAt(i);
			}
		}

		return result;
	}

	public static void main(String[] args) {
		String str1 = "test string";
		System.out.println("The given string is: " + str1);
		System.out.println("Max occurring character in the given string is: " + MaxOccuringChar(str1));
	}
}

package com.strings;

public class FirstNonRepeatCharInString {

	public static void main(String[] args) {
		String str1 = "abcdcderba";
		System.out.println("The given string is: " + str1);
		for (int i = 0; i < str1.length(); i++) {
			boolean unique = true;
			for (int j = 0; j < str1.length(); j++) {
				if (i != j && str1.charAt(i) == str1.charAt(j)) {
					unique = false;
					break;
				}
			}
			if (unique) {
				System.out.println("The first non repeated character in String is: " + str1.charAt(i));
				break;
			}
		}
	}
}

package com.strings;

import java.util.Arrays;

public class MissingString {

	public static void main(String[] args) {
		String str1 = "Java Programming Exercises, Practice, Solution";
		String str2 = "Java Programming Exercises, Practice,";
		System.out.println("Missing string: " + Arrays.toString(missing_Words(str1, str2)));
	}

	public static String[] missing_Words(String t, String s) {

		String[] s1 = t.split(" ");
		String[] s2 = s.split(" ");
		int sz = s1.length - s2.length;
		String[] missing_str = new String[sz];
		int c = 0;
		for (int i = 0; i < s1.length; i++) {
			int flag = 0;
			for (int j = 0; j < s2.length; j++) {
				if (s1[i].equals(s2[j]))
					flag = 1;
			}
			if (flag == 0) {
				missing_str[c++] = s1[i];
			}
		}
		return missing_str;
	}
}

package com.strings;

public class Permutations {

    // print n! permutation of the characters of the string s (in order)
    public  static void perm1(String s) { perm1("", s); }
    private static void perm1(String prefix, String s) {
        int n = s.length();
        if (n == 0) System.out.println(prefix);
        else {
            for (int i = 0; i < n; i++)
               perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
        }

    }

    // print n! permutation of the elements of array a (not in order)
    public static void perm2(String s) {
        int n = s.length();
        char[] a = new char[n];
        for (int i = 0; i < n; i++)
            a[i] = s.charAt(i);
        perm2(a, n);
    }

    private static void perm2(char[] a, int n) {
        if (n == 1) {
            System.out.println(new String(a));
            return;
        }
        for (int i = 0; i < n; i++) {
            swap(a, i, n-1);
            perm2(a, n-1);
            swap(a, i, n-1);
        }
    }  

    // swap the characters at indices i and j
    private static void swap(char[] a, int i, int j) {
        char c = a[i];
        a[i] = a[j];
        a[j] = c;
    }



    public static void main(String[] args) {
        int n = 3;
        String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String elements = alphabet.substring(0, n);
        perm1(elements);
        System.out.println();
        perm2(elements);
    }
}

package com.strings;

public class PrintAllDuplicates {

	static final int MAX_CHARS = 256;

	static void CountCharacters(String str1, int[] ctr) {
		for (int i = 0; i < str1.length(); i++)
			ctr[str1.charAt(i)]++;
	}

	static void showDuplicates(String str1) {
		int num[] = new int[MAX_CHARS];
		CountCharacters(str1, num);
		for (int i = 0; i < MAX_CHARS; i++)
			if (num[i] > 1)
				System.out.printf("%c  appears  %d  times\n", i, num[i]);
	}

	public static void main(String[] args) {
		String str1 = "w3resource";
		System.out.println("The given string is: " + str1);
		System.out.println("The duplicate characters and counts are: ");
		showDuplicates(str1);
	}
}

package com.strings;

public class RemoveDuplicatesFromString {

	public static void main(String[] args) {
		String str1 = "javaformulaa";
		System.out.println("The given string is: " + str1);
		System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1));
	}

	private static String removeDuplicateChars(String sourceStr) {
		char[] arr1 = sourceStr.toCharArray();
		String targetStr = "";
		for (char value : arr1) {
			if (targetStr.indexOf(value) == -1) {
				targetStr += value;
			}
		}
		return targetStr;
	}
}

package com.strings;

public class ReverseEveryWord {

	public void reverseEachWordInString(String str1) {
		String[] each_words = str1.split(" ");
		String revString = "";
		for (int i = 0; i < each_words.length; i++) {
			String word = each_words[i];
			String reverseWord = "";
			for (int j = word.length() - 1; j >= 0; j--) {
				reverseWord = reverseWord + word.charAt(j);
			}
			revString = revString + reverseWord + " ";
		}
		System.out.println(revString);
	}

	public static void main(String[] args) {
		ReverseEveryWord r = new ReverseEveryWord();
		String StrGiven = "This is a test string";
		System.out.println("The given string is: " + StrGiven);
		System.out.println("The string reversed word by word is: ");
		r.reverseEachWordInString(StrGiven);
	}
}

package com.strings;

public class ReverseWords {

	public static String WordsInReverse(String str1) {
		StringBuilder sb = new StringBuilder(str1);
		String StrRev = sb.reverse().toString();

		String[] words = StrRev.split(" ");
		StringBuilder reverse = new StringBuilder();
		for (String tmp : words) {
			sb = new StringBuilder(tmp);
			reverse.append(sb.reverse() + " ");
		}
		reverse.deleteCharAt(reverse.length() - 1);
		return reverse.toString();
	}

	public static void main(String[] args) {
		String str1 = "Reverse words in a given string";
		System.out.println("The given string is: " + str1);
		System.out.println("The new string after reversed the words: " + WordsInReverse(str1));
	}
}

BINARY,DECIMAL,OCTAL,HEXA DECIMAL

package com.binary;

import java.util.Scanner;

public class BinaryToDecimal {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long binaryNumber, decimalNumber = 0, j = 1, remainder;
		System.out.print("Input a binary number: ");
		binaryNumber = sc.nextLong();

		while (binaryNumber != 0) {
			remainder = binaryNumber % 10;
			decimalNumber = decimalNumber + remainder * j;
			j = j * 2;
			binaryNumber = binaryNumber / 10;
		}
		System.out.println("Decimal Number: " + decimalNumber);
	}
}

package com.binary;

import java.util.Scanner;

public class BinaryToHexa {

	public static void main(String[] args) {
		int[] hex = new int[1000];
		int i = 1, j = 0, rem, dec = 0, bin;
		Scanner in = new Scanner(System.in);
		System.out.print("Input a Binary Number: ");
		bin = in.nextInt();
		while (bin > 0) {
			rem = bin % 2;
			dec = dec + rem * i;
			i = i * 2;
			bin = bin / 10;
		}
		i = 0;
		while (dec != 0) {
			hex[i] = dec % 16;
			dec = dec / 16;
			i++;
		}
		System.out.print("HexaDecimal value: ");
		for (j = i - 1; j >= 0; j--) {
			if (hex[j] > 9) {
				System.out.print((char) (hex[j] + 55) + "\n");
			} else {
				System.out.print(hex[j] + "\n");
			}
		}
	}
}

package com.binary;

import java.util.Scanner;

public class BinaryToOcta {

	public static void main(String[] args) {
		int binnum, binnum1, rem, decnum = 0, quot, i = 1, j;
		int octnum[] = new int[100];
		Scanner scan = new Scanner(System.in);
		System.out.print("Input a Binary Number : ");
		binnum = scan.nextInt();
		binnum1 = binnum;

		while (binnum > 0) {
			rem = binnum % 10;
			decnum = decnum + rem * i;
			// System.out.println(rem);
			i = i * 2;
			binnum = binnum / 10;
		}

		i = 1;
		quot = decnum;

		while (quot > 0) {
			octnum[i++] = quot % 8;
			quot = quot / 8;
		}

		System.out.print("Equivalent Octal Value of " + binnum1 + " is :");
		for (j = i - 1; j > 0; j--) {
			System.out.print(octnum[j]);
		}
		System.out.print("\n");

	}
}

package com.binary;

import java.util.Scanner;

public class DecimalToBinary {

	      public static void main(String args[])
	    {
	        int dec_num, rem, quot, i=1, j;
	        int bin_num[] = new int[100];
	        Scanner scan = new Scanner(System.in);
			
	        System.out.print("Input a Decimal Number : ");
	        dec_num = scan.nextInt();
			
	        quot = dec_num;
			
	        while(quot != 0)
	        {
	            bin_num[i++] = quot%2;
	            quot = quot/2;
	        }
			
	        System.out.print("Binary number is: ");
	        for(j=i-1; j>0; j--)
	        {
	            System.out.print(bin_num[j]);
	        }
	        System.out.print("\n");
	    }
	}

package com.binary;

import java.util.Scanner;

public class DecimalToHexaDecimal {

	public static void main(String args[]) {
		int dec_num, rem;
		String hexdec_num = "";

		/* hexadecimal number digits */

		char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

		Scanner in = new Scanner(System.in);

		System.out.print("Input a decimal number: ");
		dec_num = in.nextInt();

		while (dec_num > 0) {
			rem = dec_num % 16;
			hexdec_num = hex[rem] + hexdec_num;
			dec_num = dec_num / 16;
		}
		System.out.print("Hexadecimal number is : " + hexdec_num + "\n");
	}
}

package com.binary;

import java.util.Scanner;

public class DecimalToOcta {

	public static void main(String args[]) {
		int dec_num, rem, quot, i = 1, j;
		int oct_num[] = new int[100];
		Scanner scan = new Scanner(System.in);

		System.out.print("Input a Decimal Number: ");
		dec_num = scan.nextInt();

		quot = dec_num;

		while (quot != 0) {
			oct_num[i++] = quot % 8;
			quot = quot / 8;
		}

		System.out.print("Octal number is: ");
		for (j = i - 1; j > 0; j--) {
			System.out.print(oct_num[j]);
		}
		System.out.print("\n");
	}
}

package com.binary;

import java.util.Scanner;

public class HexaToBinary {

	public static int hex_to_decimal(String s) {
		String digits = "0123456789ABCDEF";
		s = s.toUpperCase();
		int val = 0;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			int d = digits.indexOf(c);
			val = 16 * val + d;
		}
		return val;
	}

	public static void main(String args[]) {
		String hexdec_num;
		int dec_num, i = 1, j;
		int bin_num[] = new int[100];
		Scanner scan = new Scanner(System.in);

		System.out.print("Enter Hexadecimal Number : ");
		hexdec_num = scan.nextLine();

		/* convert hexadecimal to decimal */
		dec_num = hex_to_decimal(hexdec_num);

		/* convert decimal to binary */
		while (dec_num != 0) {
			bin_num[i++] = dec_num % 2;
			dec_num = dec_num / 2;
		}

		System.out.print("Equivalent Binary Number is: ");
		for (j = i - 1; j > 0; j--) {
			System.out.print(bin_num[j]);
		}
		System.out.print("\n");
	}
}

package com.binary;

import java.util.Scanner;

public class HexaToDecimal {

	public static int hex_to_decimal(String s) {
		String digits = "0123456789ABCDEF";
		s = s.toUpperCase();
		int val = 0;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			int d = digits.indexOf(c);
			val = 16 * val + d;
		}
		return val;
	}

	public static void main(String args[]) {
		String hexdec_num;
		int dec_num;
		Scanner scan = new Scanner(System.in);

		System.out.print("Input a hexadecimal number: ");
		hexdec_num = scan.nextLine();

		dec_num = hex_to_decimal(hexdec_num);

		System.out.print("Equivalent decimal number is: " + dec_num + "\n");
	}
}

package com.binary;

import java.util.Scanner;

public class HexaToOcta {

	public static int hex_to_decimal(String s) {
		String digits = "0123456789ABCDEF";
		s = s.toUpperCase();
		int val = 0;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			int d = digits.indexOf(c);
			val = 16 * val + d;
		}
		return val;
	}

	public static void main(String args[]) {
		String hexdec_num;
		int dec_num, i = 1, j;
		int octal_num[] = new int[100];
		Scanner in = new Scanner(System.in);

		System.out.print("Input a hexadecimal number: ");
		hexdec_num = in.nextLine();

		// Convert hexadecimal to decimal

		dec_num = hex_to_decimal(hexdec_num);

		// Convert decimal to octal

		while (dec_num != 0) {
			octal_num[i++] = dec_num % 8;
			dec_num = dec_num / 8;
		}

		System.out.print("Equivalent of octal number is: ");
		for (j = i - 1; j > 0; j--) {
			System.out.print(octal_num[j]);
		}
		System.out.print("\n");
	}
}

package com.binary;

import java.util.Scanner;

public class OctaToBinary {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int[] octal_numvalues = { 0, 1, 10, 11, 100, 101, 110, 111 };
		long octal_num, tempoctal_num, binary_num, place;
		int rem;
		System.out.print("Input any octal number: ");
		octal_num = in.nextLong();
		tempoctal_num = octal_num;
		binary_num = 0;
		place = 1;
		while (tempoctal_num != 0) {
			rem = (int) (tempoctal_num % 10);
			binary_num = octal_numvalues[rem] * place + binary_num;
			tempoctal_num /= 10;
			place *= 1000;
		}
		System.out.print("Equivalent binary number: " + binary_num + "\n");
	}
}

package com.binary;

import java.util.Scanner;

public class OctaToDecimal {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		long octal_num, decimal_num = 0;
		int i = 0;
		System.out.print("Input any octal number: ");
		octal_num = in.nextLong();
		while (octal_num != 0) {
			decimal_num = (long) (decimal_num + (octal_num % 10) * Math.pow(8, i++));
			octal_num = octal_num / 10;
		}
		System.out.print("Equivalent decimal number: " + decimal_num + "\n");
	}
}

package com.binary;

import java.util.Scanner;

public class OctaToHexa {

	public static void main(String args[]) {
		String octal_num, hex_num;
		int decnum;
		Scanner in = new Scanner(System.in);

		System.out.print("Input a octal number : ");
		octal_num = in.nextLine();

		decnum = Integer.parseInt(octal_num, 8);
		hex_num = Integer.toHexString(decnum);

		System.out.print("Equivalent hexadecimal number: " + hex_num + "\n");
	}
}

package com.binary;

import java.util.Scanner;

public class SumOfTwoBinary {

	public static void main(String[] args) {
		long binary1, binary2;
		int i = 0, remainder = 0;
		int[] sum = new int[20];
		Scanner in = new Scanner(System.in);

		System.out.print("Input first binary number: ");
		binary1 = in.nextLong();
		System.out.print("Input second binary number: ");
		binary2 = in.nextLong();

		while (binary1 != 0 || binary2 != 0) {
			sum[i++] = (int) ((binary1 % 10 + binary2 % 10 + remainder) % 2);
			remainder = (int) ((binary1 % 10 + binary2 % 10 + remainder) / 2);
			binary1 = binary1 / 10;
			binary2 = binary2 / 10;
		}
		if (remainder != 0) {
			sum[i++] = remainder;
		}
		--i;
		System.out.print("Sum of two binary numbers: ");
		while (i >= 0) {
			System.out.print(sum[i--]);
		}
		System.out.print("\n");
	}
}

THREADS

package com.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
    private AtomicInteger count = new AtomicInteger(0);

    public int incrementAndGet() {
        return count.incrementAndGet();
    }

    public int getCount() {
        return count.get();
    }
}

public class AtomicIntegerExample {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        AtomicCounter atomicCounter = new AtomicCounter();

        for(int i = 0; i < 1000; i++) {
            executorService.submit(() -> atomicCounter.incrementAndGet());
        }

        executorService.shutdown();
        executorService.awaitTermination(60, TimeUnit.SECONDS);

        System.out.println("Final Count is : " + atomicCounter.getCount());
    }
}

package com.threads;

class TicketThread {

	int availableSeats = 2;

	synchronized void bookTicket(String pname, int numberOfSeats) {
		if ((availableSeats >= numberOfSeats) && (numberOfSeats > 0)) {
			System.out.println(pname + " : " + numberOfSeats + " Seats Booking Success");
			availableSeats -= numberOfSeats;
		} else
			System.out.println(pname + " : Seats Not Available");
	}
}

class TicketBookingThread extends Thread {

	TicketThread tc;
	String name;
	int seats;

	TicketBookingThread(TicketThread t, String pname, int pseats) {
		tc = t;
		name = pname;
		seats = pseats;
		start();
	}

	public void run() {
		tc.bookTicket(name, seats);
	}
}

public class BusReservationUsingThreadSynchron {

	public static void main(String[] args) {

		TicketThread tc = new TicketThread();
		TicketBookingThread th1 = new TicketBookingThread(tc, "durga", 2);
		TicketBookingThread th2 = new TicketBookingThread(tc, "suguna", 2);
	}
}

package com.threads;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFutureExample {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService executorService = Executors.newSingleThreadExecutor();

		Callable<String> callable = () -> {
			// Perform some computation
			System.out.println("Entered Callable");
			Thread.sleep(2000);
			return "Hello from Callable";
		};

		System.out.println("Submitting Callable");
		Future<String> future = executorService.submit(callable);

		// This line executes immediately
		System.out.println("Do something else while callable is getting executed");

		System.out.println("Retrieve the result of the future");
		// Future.get() blocks until the result is available
		String result = future.get();
		System.out.println(result);

		executorService.shutdown();
	}

}

package com.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {

	public static void main(String[] args) {
		System.out.println("Inside : " + Thread.currentThread().getName());

		System.out.println("Creating Executor Service...");
		ExecutorService executorService = Executors.newSingleThreadExecutor();

		System.out.println("Creating a Runnable...");
		Runnable runnable = () -> {
			System.out.println("Inside : " + Thread.currentThread().getName());
		};

		System.out.println("Submit the task specified by the runnable to the executor service.");
		executorService.submit(runnable);
	}
}

package com.threads;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceInvokeAll {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService executorService = Executors.newFixedThreadPool(5);

		Callable<String> task1 = () -> {
			Thread.sleep(2000);
			return "Result of Task1";
		};

		Callable<String> task2 = () -> {
			Thread.sleep(1000);
			return "Result of Task2";
		};

		Callable<String> task3 = () -> {
			Thread.sleep(5000);
			return "Result of Task3";
		};

		List<Callable<String>> taskList = Arrays.asList(task1, task2, task3);

		List<Future<String>> futures = executorService.invokeAll(taskList);

		for (Future<String> future : futures) {
			// The result is printed only after all the futures are complete.
			// (i.e. after 5 seconds)
			System.out.println(future.get());
		}

		executorService.shutdown();
	}
}

package com.threads;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceInvokeAny {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService executorService = Executors.newFixedThreadPool(5);

		Callable<String> task1 = () -> {
			Thread.sleep(2000);
			return "Result of Task1";
		};

		Callable<String> task2 = () -> {
			Thread.sleep(1000);
			return "Result of Task2";
		};

		Callable<String> task3 = () -> {
			Thread.sleep(5000);
			return "Result of Task3";
		};

		// Returns the result of the fastest callable. (task2 in this case)
		String result = executorService.invokeAny(Arrays.asList(task1, task2, task3));

		System.out.println(result);

		executorService.shutdown();
	}
}

package com.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceWithMultipleThreads {

	public static void main(String[] args) {
		System.out.println("Inside : " + Thread.currentThread().getName());

		System.out.println("Creating Executor Service with a thread pool of Size 2");
		ExecutorService executorService = Executors.newFixedThreadPool(2);

		Runnable task1 = () -> {
			System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException ex) {
				throw new IllegalStateException(ex);
			}
		};

		Runnable task2 = () -> {
			System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(4);
			} catch (InterruptedException ex) {
				throw new IllegalStateException(ex);
			}
		};

		Runnable task3 = () -> {
			System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(3);
			} catch (InterruptedException ex) {
				throw new IllegalStateException(ex);
			}
		};

		System.out.println("Submitting the tasks for execution...");
		executorService.submit(task1);
		executorService.submit(task2);
		executorService.submit(task3);

		executorService.shutdown();
	}
}

package com.threads;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintEvenOddUsingLock {

	Lock lock;
	Condition evenCondition;
	Condition oddCondition;

	public static void main(String[] args) {
		PrintEvenOddUsingLock printEvenOdd = new PrintEvenOddUsingLock();
		printEvenOdd.lock = new ReentrantLock();
		printEvenOdd.evenCondition = printEvenOdd.lock.newCondition();
		printEvenOdd.oddCondition = printEvenOdd.lock.newCondition();

		Thread evenThread = new Thread(() -> {
			printEvenOdd.printEven();
		});
		Thread oddThread = new Thread(() -> {
			printEvenOdd.printOdd();
		});
		evenThread.start();
		oddThread.start();
	}

	private void printEven() {
		try {
			lock.lockInterruptibly();
		} catch (InterruptedException e) {

		}

		int i = 0;
		while (i < Integer.MAX_VALUE) {
			if (i % 2 == 0) {
				System.out.println(Thread.currentThread().getName()+" "+i + " ");
				if (i % 10 == 0)
					System.out.println();
				oddCondition.signal();
				try {
					Thread.sleep(1000);
					evenCondition.await();
				} catch (InterruptedException e) {

				}
			}
			i += 1;
		}
		lock.unlock();
	}

	private void printOdd() {
		try {
			lock.lockInterruptibly();
		} catch (InterruptedException e) {

		}

		int i = 0;
		while (i < Integer.MAX_VALUE) {
			if (i % 2 == 1) {
				System.out.println(Thread.currentThread().getName()+" "+i + " ");
			
				evenCondition.signal();
				try {
					Thread.sleep(1000);
					oddCondition.await();
				} catch (InterruptedException e) {

				}
			}
			i += 1;
		}
		lock.unlock();
	}

}

package com.threads;

import java.util.concurrent.atomic.AtomicInteger;

public class PrintSequenceUsingAutomicInt {

	public static AtomicInteger shared = new AtomicInteger(1);

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Thread even = new Thread(new one(1));
		Thread odd = new Thread(new one(2));
		Thread third = new Thread(new one(3));
		even.start();
		odd.start();
		third.start();

	}

}

class one implements Runnable {
	int threadid;

	public one(int num) {
		this.threadid = num;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		while (true) {
			if (PrintSequenceUsingAutomicInt.shared.get() % 4 == this.threadid) {
				int i = PrintSequenceUsingAutomicInt.shared.get();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("Thread ID -->> " + this.threadid + "Value-->>" + i);

				if (PrintSequenceUsingAutomicInt.shared.incrementAndGet() >= 4) {
					PrintSequenceUsingAutomicInt.shared.set(1);
				}

			}

		}

	}

}

package com.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

class ReentrantLockMethodsCounter {
	private final ReentrantLock lock = new ReentrantLock();

	private int count = 0;

	public int incrementAndGet() {
		// Check if the lock is currently acquired by any thread
		System.out.println("IsLocked : " + lock.isLocked());

		// Check if the lock is acquired by the current thread itself.
		System.out.println("IsHeldByCurrentThread : " + lock.isHeldByCurrentThread());

		// Try to acquire the lock
		boolean isAcquired = lock.tryLock();
		System.out.println("Lock Acquired : " + isAcquired + "\n");

		if (isAcquired) {
			try {
				Thread.sleep(2000);
				count = count + 1;
			} catch (InterruptedException e) {
				throw new IllegalStateException(e);
			} finally {
				lock.unlock();
			}
		}
		return count;
	}
}

public class ReEntrantLockExample {

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(2);

		ReentrantLockMethodsCounter lockMethodsCounter = new ReentrantLockMethodsCounter();

		executorService.submit(() -> {
			System.out.println("IncrementCount (First Thread) : " + lockMethodsCounter.incrementAndGet() + "\n");
		});

		executorService.submit(() -> {
			System.out.println("IncrementCount (Second Thread) : " + lockMethodsCounter.incrementAndGet() + "\n");
		});

		executorService.shutdown();
	}
}

package com.threads;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPool {

	public static void main(String[] args) {
		ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
		Runnable task = () -> {
			System.out.println("Executing Task At " + System.nanoTime());
		};

		System.out.println("Submitting task at " + System.nanoTime() + " to be executed after 5 seconds.");
		scheduledExecutorService.schedule(task, 5, TimeUnit.SECONDS);

		scheduledExecutorService.shutdown();
	}
}

package com.threads;

class NewThread extends Thread {

	NewThread() {
		start();
	}

	public void run() {
		synchronized (this) {
			for (int i = 0; i < 5; i++) {
				System.out.println("Child Thread Running..." + i);
			}
			System.out.println("Exiting Chiled Thread");
			notify();
		}
	}
}

public class ThreadCommunicationUsingWaitNotify {

	public static void main(String[] args) {

		NewThread child = new NewThread();

		synchronized (child) {
			try {
				System.out.println("Main Thread Waiting for Child Thread to Complete...");
				child.wait();
				System.out.println("Notification Received From Child Thread");
			} catch (InterruptedException ie) {
				System.out.println("Thread Interrupted");
			}
		}
		System.out.println("Exiting Main Thread");
	}
}

package com.threads;

import java.util.concurrent.Semaphore;

public class ThreadEvenOddUsingSemaphore implements Runnable {

	private boolean isEven;
	private int count;
	static Semaphore s = new Semaphore(1);
	static Semaphore t = new Semaphore(0);

	ThreadEvenOddUsingSemaphore(boolean flag, int c) {
		isEven = flag;
		count = c;
	}

	@Override
	public void run() {
		if (isEven) {
			try {
				printEven(count);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			try {
				printOdd(count);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void printOdd(int count) throws InterruptedException {
		int c = 1;
		for (int i = 0; i < count; i++) {

			s.acquire(1);
			System.out.println(Thread.currentThread().getName()+" "+c);
			c = c + 2;
			t.release(1);

		}

	}

	private void printEven(int count) throws InterruptedException {
		int c = 2;
		for (int i = 0; i < count; i++) {

			t.acquire(1);
			System.out.println(Thread.currentThread().getName()+" "+c);
			c = c + 2;
			s.release(1);
		}

	}

	public static void main(String[] args) {

		Thread a = new Thread(new ThreadEvenOddUsingSemaphore(true, 20));
		Thread b = new Thread(new ThreadEvenOddUsingSemaphore(false, 20));
		a.start();
		b.start();

	}

}

package com.threads;

public class ThreadPrintSequentially {

	static Object monitor = new Object();

	static boolean one = true;
	static boolean two = false;
	static boolean three = false;

	public static void main(String[] args) {

		Thread t1 = new Thread(new SequenceDisplayImpl(1));
		Thread t2 = new Thread(new SequenceDisplayImpl(2));
		Thread t3 = new Thread(new SequenceDisplayImpl(3));
		t1.start();
		t2.start();
		t3.start();

	}

	static class SequenceDisplayImpl implements Runnable {

		int threadId;

		SequenceDisplayImpl(int threadId) {
			this.threadId = threadId;
		}

		public void run() {
			print();
		}

		private void print() {
			try {
				while (true) {
					Thread.sleep(500);
					synchronized (monitor) {
						if (1 == threadId) {
							if (!one) {
								monitor.wait();
							} else {
								System.out.print(threadId + " ");
								one = false;
								two = true;
								three = false;
								monitor.notifyAll();
							}
						}
						if (2 == threadId) {
							if (!two) {
								monitor.wait();
							} else {
								System.out.print(threadId + " ");
								one = false;
								two = false;
								three = true;
								monitor.notifyAll();
							}
						}
						if (3 == threadId) {
							if (!three) {
								monitor.wait();
							} else {
								System.out.print(threadId + " ");
								one = true;
								two = false;
								three = false;
								monitor.notifyAll();
							}
						}
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

}

package com.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadSequenceUsingExecutor {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		PrintNumber one = new PrintNumber("1");
		PrintNumber two = new PrintNumber("2", one);
		PrintNumber three = new PrintNumber("3", two);
		one.parent = three;
		threadPool.execute(one);
		threadPool.execute(two);
		threadPool.execute(three);
	}

}

class PrintNumber implements Runnable {
	public String number;
	public Runnable parent;

	public PrintNumber(String number) {
		this.number = number;
	}

	public PrintNumber(String number, Runnable parent) {
		this.number = number;
		this.parent = parent;
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
				System.out.println(number);
				synchronized (this) {
					notify();
				}

				synchronized (parent) {
					parent.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalMonitorStateException ex) {
				ex.printStackTrace();
			}

		}
	}
}

package com.threads;

public class ThreadSequenceUsingWaitNotify {

	Object monitor = new Object();

	boolean one = true;
	boolean two = false;
	boolean three = false;

	public static void main(String[] args) {

		ThreadSequenceUsingWaitNotify s = new ThreadSequenceUsingWaitNotify();
		Thread t1 = new Thread(s.new MyRunnable(1));
		Thread t2 = new Thread(s.new MyRunnable(2));
		Thread t3 = new Thread(s.new MyRunnable(3));
		t1.start();
		t2.start();
		t3.start();

	}

	public class MyRunnable implements Runnable {

		int threadId;

		MyRunnable(int threadId) {
			this.threadId = threadId;
		}

		@Override
		public void run() {
			print();
		}

		private void print() {
			try {
				while (true) {
					Thread.sleep(101);
					synchronized (monitor) {
						if (1 == threadId) {
							if (!one) {
								monitor.wait();
							} else {
								Thread.sleep(1000);
								System.out.println(threadId);
								one = false;
								two = true;
								three = false;
								monitor.notifyAll();
							}
						}
						if (2 == threadId) {
							if (!two) {
								monitor.wait();
							} else {
								Thread.sleep(1000);
								System.out.println(threadId);
								one = false;
								two = false;
								three = true;
								monitor.notifyAll();
							}
						}
						if (3 == threadId) {
							if (!three) {
								monitor.wait();
							} else {
								Thread.sleep(1000);
								System.out.println(threadId);
								one = true;
								two = false;
								three = false;
								monitor.notifyAll();
							}
						}
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}
}

package com.threads;

public class VolatileExample {

	private static volatile boolean sayHello = false;

	public static void main(String[] args) throws InterruptedException {

		Thread thread = new Thread(() -> {
			while (!sayHello) {
			}

			System.out.println("Hello World!");

			while (sayHello) {
			}

			System.out.println("Good Bye!");
		});

		thread.start();

		Thread.sleep(1000);
		System.out.println("Say Hello..");
		sayHello = true;

		Thread.sleep(1000);
		System.out.println("Say Bye..");
		sayHello = false;
	}
}

BINARY TREE

package com.binaryTree;

class InNode
{
    int key;
    InNode left, right;
 
    public InNode(int item)
    {
        key = item;
        left = right = null;
    }
}
 
class InOrder
{
    // Root of Binary Tree
	InNode root;
 
    InOrder()
    {
        root = null;
    } 
  
    // Print the nodes of binary tree in inorder
    void print_Inorder(InNode node)
    {
        if (node == null)
            return;
 
        print_Inorder(node.left);
 
     // Print the data of node
        System.out.print(node.key + " ");
 
        print_Inorder(node.right);
    }
 
	void print_Inorder()
	   {     
	     print_Inorder(root);   
	     
	   }
    
    public static void main(String[] args)
    {
        InOrder tree = new InOrder();
        tree.root = new InNode(55);
        tree.root.left = new InNode(21);
        tree.root.right = new InNode(80);
        tree.root.left.left = new InNode(9);
        tree.root.left.right = new InNode(29);
        tree.root.right.left = new InNode(76);
        tree.root.right.right = new InNode(91);
 
        System.out.println("\nInorder traversal of binary tree is: ");
        tree.print_Inorder(); 
    }
}

package com.binaryTree;

class PreNode {
	int key;
	PreNode left, right;

	public PreNode(int item) {
		key = item;
		left = right = null;
	}
}

class PreOrder {
	// Root of Binary Tree
	PreNode root;

	PreOrder() {
		root = null;
	}

	// Print the nodes of binary tree

	void print_Preorder(PreNode node) {
		if (node == null)
			return;

		/* Print data of node */
		System.out.print(node.key + " ");

		print_Preorder(node.left);

		print_Preorder(node.right);
	}

	void print_Preorder() {
		print_Preorder(root);
	}

	// Driver method
	public static void main(String[] args) {
		PreOrder tree = new PreOrder();
		tree.root = new PreNode(55);
		tree.root.left = new PreNode(21);
		tree.root.right = new PreNode(80);
		tree.root.left.left = new PreNode(9);
		tree.root.left.right = new PreNode(29);
		tree.root.right.left = new PreNode(76);
		tree.root.right.right = new PreNode(91);

		System.out.println("Preorder traversal of binary tree is: ");
		tree.print_Preorder();
	}
}

package com.binaryTree;
class PostNode
{
    int key;
    PostNode left, right;

    public PostNode(int item)
    {
        key = item;
        left = right = null;
    }
}

class PostOrder
{
  // Root of Binary Tree
	PostNode root;

    PostOrder()
    {
        root = null;
    }

  // Print the nodes of binary tree

    void print_Postorder(PostNode node)
    {
        if (node == null)
            return;

        print_Postorder(node.left);

        print_Postorder(node.right);

        System.out.print(node.key + " ");
    }

   // Wrappers over above recursive functions
    void print_Postorder()  
	{   
	   print_Postorder(root);  
	}
        public static void main(String[] args)
    {
       PostOrder tree = new PostOrder();
        tree.root = new PostNode(55);
        tree.root.left = new PostNode(21);
        tree.root.right = new PostNode(80);
        tree.root.left.left = new PostNode(9);
        tree.root.left.right = new PostNode(29);
        tree.root.right.left = new PostNode(76);
        tree.root.right.right = new PostNode(91);

        System.out.println("\nPostorder traversal of binary tree is: ");
        tree.print_Postorder();
    }
}

SORTING

package com.sort;

import java.util.Arrays;

public class BubbleSort {

	    void bubbleSort(int nums[])
	    {
	        int n = nums.length;
	        for (int i = 0; i < n-1; i++)
	            for (int j = 0; j < n-i-1; j++)
	                if (nums[j] > nums[j+1])
	                {
	                    // swap temp and nums[i]
	                    int temp = nums[j];
	                    nums[j] = nums[j+1];
	                    nums[j+1] = temp;
	                }
	    }
	 
	    // Method to test above
	    public static void main(String args[])
	    {
	        BubbleSort ob = new BubbleSort();
	        int nums[] = {7, -5, 3, 2, 1, 0, 45};
	        System.out.println("Original Array:");
	        System.out.println(Arrays.toString(nums));
	        ob.bubbleSort(nums);
	        System.out.println("Sorted Array");
	        System.out.println(Arrays.toString(nums));
	    }
	}

package com.sort;

import java.util.Arrays;

public class BucketSort {

	static int[] sort(int[] nums, int max_value) {
		// Bucket Sort
		int[] Bucket = new int[max_value + 1];
		int[] sorted_nums = new int[nums.length];
		for (int i = 0; i < nums.length; i++)
			Bucket[nums[i]]++;
		int outPos = 0;
		for (int i = 0; i < Bucket.length; i++)
			for (int j = 0; j < Bucket[i]; j++)
				sorted_nums[outPos++] = i;
		return sorted_nums;
	}

	static int max_value(int[] nums) {
		int max_value = 0;
		for (int i = 0; i < nums.length; i++)
			if (nums[i] > max_value)
				max_value = nums[i];
		return max_value;
	}

	// Method to test above
	public static void main(String args[]) {
		int nums[] = { 7, 3, 2, 1, 0, 45 };
		int max_value = max_value(nums);
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		nums = sort(nums, max_value);
		System.out.println("Sorted Array:");
		System.out.println(Arrays.toString(nums));
	}
}

package com.sort;

import java.util.Arrays;

public class HeapSort {

	void HeapSort(int nums[]) {
		buildheap(nums);
		for (int i = nums.length - 1; i >= 0; i--) {
			exchange(nums, i, 0);
			heap(nums, i, 0);
		}
	}

	private void exchange(int[] nums, int i, int j) {
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}

	private void heap(int[] nums, int size, int i) {
		int left = ((2 * i) + 1);
		int right = ((2 * i) + 2);
		int max = i;

		if ((left < size) && (nums[left] > nums[i])) {
			max = left;
		}

		if ((right < size) && (nums[right] > nums[max])) {
			max = right;
		}

		if (max != i) {
			exchange(nums, i, max);
			heap(nums, size, max);
		}
	}

	private void buildheap(int[] nums) {
		for (int i = (nums.length / 2) - 1; i >= 0; i--) {
			heap(nums, (nums.length - 1), i);
		}
	}

	// Method to test above
	public static void main(String args[]) {
		HeapSort ob = new HeapSort();
		int nums[] = { 7, -5, 3, 2, 1, 0, 45 };
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		ob.HeapSort(nums);
		System.out.println("Sorted Array");
		System.out.println(Arrays.toString(nums));
	}
}

package com.sort;

import java.util.Arrays;

public class InsertionSort {

	void InsertionSort(int[] nums) {
		for (int i = 1; i < nums.length; i++) {
			int value = nums[i];
			int j = i - 1;
			while (j >= 0 && nums[j] > value) {
				nums[j + 1] = nums[j];
				j = j - 1;
			}
			nums[j + 1] = value;
		}
	}

	// Method to test above
	public static void main(String args[]) {
		InsertionSort ob = new InsertionSort();
		int nums[] = { 7, -5, 3, 2, 1, 0, 45 };
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		ob.InsertionSort(nums);
		System.out.println("Sorted Array");
		System.out.println(Arrays.toString(nums));
	}
}

package com.sort;

import java.util.Arrays;

public class MergeSort {

	void merge(int nums[], int left, int m, int right) {
		int n1 = m - left + 1;
		int n2 = right - m;

		int Left_part_arra[] = new int[n1];
		int Right_part_arra[] = new int[n2];

		for (int i = 0; i < n1; ++i)
			Left_part_arra[i] = nums[left + i];
		for (int j = 0; j < n2; ++j)
			Right_part_arra[j] = nums[m + 1 + j];

		int i = 0, j = 0;

		int k = left;
		while (i < n1 && j < n2) {
			if (Left_part_arra[i] <= Right_part_arra[j]) {
				nums[k] = Left_part_arra[i];
				i++;
			} else {
				nums[k] = Right_part_arra[j];
				j++;
			}
			k++;
		}

		while (i < n1) {
			nums[k] = Left_part_arra[i];
			i++;
			k++;
		}

		while (j < n2) {
			nums[k] = Right_part_arra[j];
			j++;
			k++;
		}
	}

	// merge()
	void sort(int nums[], int left, int right) {
		if (left < right) {
			// Find the middle point
			int m = (left + right) / 2;

			// Sort first halve
			sort(nums, left, m);
			// Sort second halve
			sort(nums, m + 1, right);

			// Merge the sorted halves
			merge(nums, left, m, right);
		}
	}

	// Method to test above
	public static void main(String args[]) {
		MergeSort ob = new MergeSort();
		int nums[] = { 7, -5, 3, 2, 1, 0, 45 };
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		ob.sort(nums, 0, nums.length - 1);
		System.out.println("Sorted Array:");
		System.out.println(Arrays.toString(nums));
	}

}

package com.sort;

import java.util.Arrays;

public class QuickSort {

	private int temp_array[];
	private int len;

	public void sort(int[] nums) {

		if (nums == null || nums.length == 0) {
			return;
		}
		this.temp_array = nums;
		len = nums.length;
		quickSort(0, len - 1);
	}

	private void quickSort(int low_index, int high_index) {

		int i = low_index;
		int j = high_index;
		// calculate pivot number
		int pivot = temp_array[low_index + (high_index - low_index) / 2];
		// Divide into two arrays
		while (i <= j) {
			while (temp_array[i] < pivot) {
				i++;
			}
			while (temp_array[j] > pivot) {
				j--;
			}
			if (i <= j) {
				exchangeNumbers(i, j);
				// move index to next position on both sides
				i++;
				j--;
			}
		}
		// call quickSort() method recursively
		if (low_index < j)
			quickSort(low_index, j);
		if (i < high_index)
			quickSort(i, high_index);
	}

	private void exchangeNumbers(int i, int j) {
		int temp = temp_array[i];
		temp_array[i] = temp_array[j];
		temp_array[j] = temp;
	}

	// Method to test above
	public static void main(String args[]) {
		QuickSort ob = new QuickSort();
		int nums[] = { 7, -5, 3, 2, 1, 0, 45 };
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		ob.sort(nums);
		System.out.println("Sorted Array");
		System.out.println(Arrays.toString(nums));
	}
}

package com.sort;

import java.util.Arrays;

public class RadixSort {

	public static void sort(int[] array) {
		RadixSort.sort(array, 10);
	}

	public static void sort(int[] array, int radix) {
		if (array.length == 0) {
			return;
		}

		// Determine minimum and maximum values
		int minValue = array[0];
		int maxValue = array[0];
		for (int i = 1; i < array.length; i++) {
			if (array[i] < minValue) {
				minValue = array[i];
			} else if (array[i] > maxValue) {
				maxValue = array[i];
			}
		}

		// Perform counting sort on each exponent/digit, starting at the least
		// significant digit
		int exponent = 1;
		while ((maxValue - minValue) / exponent >= 1) {
			RadixSort.countingSortByDigit(array, radix, exponent, minValue);
			exponent *= radix;
		}
	}

	private static void countingSortByDigit(int[] array, int radix, int exponent, int minValue) {
		int bucketIndex;
		int[] buckets = new int[radix];
		int[] output = new int[array.length];

		// Initialize bucket
		for (int i = 0; i < radix; i++) {
			buckets[i] = 0;
		}

		// Count frequencies
		for (int i = 0; i < array.length; i++) {
			bucketIndex = (int) (((array[i] - minValue) / exponent) % radix);
			buckets[bucketIndex]++;
		}

		// Compute cumulates
		for (int i = 1; i < radix; i++) {
			buckets[i] += buckets[i - 1];
		}

		// Move records
		for (int i = array.length - 1; i >= 0; i--) {
			bucketIndex = (int) (((array[i] - minValue) / exponent) % radix);
			output[--buckets[bucketIndex]] = array[i];
		}

		// Copy back
		for (int i = 0; i < array.length; i++) {
			array[i] = output[i];
		}
	}

	// Method to test above
	public static void main(String args[]) {
		RadixSort ob = new RadixSort();
		int nums[] = { 7, -5, 3, 2, 1, 0, 45 };
		System.out.println("Original Array:");
		System.out.println(Arrays.toString(nums));
		ob.sort(nums);
		System.out.println("Sorted Array:");
		System.out.println(Arrays.toString(nums));
	}
}

SERACHING

package com.search;

public class FindElementBinarySearch {

	public static int binarySearch(int[] nums, int flag) {
		int hi_num = nums.length - 1;
		int lo_num = 0;
		while (hi_num >= lo_num) {
			int guess = (lo_num + hi_num) >>> 1;
			if (nums[guess] > flag) {
				hi_num = guess - 1;
			} else if (nums[guess] < flag) {
				lo_num = guess + 1;
			} else {
				return guess;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		int[] nums = { 1, 5, 6, 7, 8, 11 };
		int search_num = 7;
		int index = binarySearch(nums, search_num);
		if (index == -1) {
			System.out.println(search_num + " is not in the array");
		} else {
			System.out.println(search_num + " is at index " + index);
		}
	}
}

package com.search;

public class FindElementLinearSearch {

	static int[] nums;

	public static void main(String[] args) {
		nums = new int[] { 3, 2, 4, 5, 6, 6, 7, 8, 9, 9, 0, 9 };
		int result = Linear_Search(nums, 6);
		if (result == -1) {
			System.out.print("Not present in the array!");
		} else
			System.out.print("Number found at index " + result);
	}

	private static int Linear_Search(int[] nums, int search) {
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == search) {
				return i;

			}
		}
		return -1;

	}
}

LINKED LISTS

package com.linkedList;

/***************************************************************************
 * A Linked List class with a private static inner Node class.
 *
 *****************************************************************************/

import java.util.*;

public class LinkedList<AnyType> implements Iterable<AnyType> {
	private Node<AnyType> head;

	/**
	 * Constructs an empty list
	 */
	public LinkedList() {
		head = null;
	}

	/**
	 * Returns true if the list is empty
	 *
	 */
	public boolean isEmpty() {
		return head == null;
	}

	/**
	 * Inserts a new node at the beginning of this list.
	 *
	 */
	public void addFirst(AnyType item) {
		head = new Node<AnyType>(item, head);
	}

	/**
	 * Returns the first element in the list.
	 *
	 */
	public AnyType getFirst() {
		if (head == null)
			throw new NoSuchElementException();

		return head.data;
	}

	/**
	 * Removes the first element in the list.
	 *
	 */
	public AnyType removeFirst() {
		AnyType tmp = getFirst();
		head = head.next;
		return tmp;
	}

	/**
	 * Inserts a new node to the end of this list.
	 *
	 */
	public void addLast(AnyType item) {
		if (head == null)
			addFirst(item);
		else {
			Node<AnyType> tmp = head;
			while (tmp.next != null)
				tmp = tmp.next;