We had the best time playing at Venice Beach!
The atmosphere in New York is lorem ipsum.
Thank you, Chicago - A night we won't forget.
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); } }
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; tmp.next = new Node<AnyType>(item, null); } } /** * Returns the last element in the list. * */ public AnyType getLast() { if (head == null) throw new NoSuchElementException(); Node<AnyType> tmp = head; while (tmp.next != null) tmp = tmp.next; return tmp.data; } /** * Removes all nodes from the list. * */ public void clear() { head = null; } /** * Returns true if this list contains the specified element. * */ public boolean contains(AnyType x) { for (AnyType tmp : this) if (tmp.equals(x)) return true; return false; } /** * Returns the data at the specified position in the list. * */ public AnyType get(int pos) { if (head == null) throw new IndexOutOfBoundsException(); Node<AnyType> tmp = head; for (int k = 0; k < pos; k++) { tmp = tmp.next; } if (tmp == null) throw new IndexOutOfBoundsException(); return tmp.data; } /** * Returns a string representation * */ public String toString() { StringBuffer result = new StringBuffer(); for (Object x : this) result.append(x + " "); return result.toString(); } /** * Inserts a new node after a node containing the key. * */ public void insertAfter(AnyType key, AnyType toInsert) { Node<AnyType> tmp = head; while (tmp != null && !tmp.data.equals(key)) tmp = tmp.next; if (tmp != null) tmp.next = new Node<AnyType>(toInsert, tmp.next); } /** * Inserts a new node before a node containing the key. * */ public void insertBefore(AnyType key, AnyType toInsert) { if (head == null) return; if (head.data.equals(key)) { addFirst(toInsert); return; } Node<AnyType> prev = null; Node<AnyType> cur = head; while (cur != null && !cur.data.equals(key)) { prev = cur; cur = cur.next; } // insert between cur and prev if (cur != null) prev.next = new Node<AnyType>(toInsert, cur); } /** * Removes the first occurrence of the specified element in this list. * */ public void remove(AnyType key) { if (head == null) throw new RuntimeException("cannot delete"); if (head.data.equals(key)) { head = head.next; return; } Node<AnyType> cur = head; Node<AnyType> prev = null; while (cur != null && !cur.data.equals(key)) { prev = cur; cur = cur.next; } if (cur == null) throw new RuntimeException("cannot delete"); // delete cur node prev.next = cur.next; } /** * Returns a deep copy of the list Complexity: O(n^2) */ public LinkedList<AnyType> copy1() { LinkedList<AnyType> twin = new LinkedList<AnyType>(); Node<AnyType> tmp = head; while (tmp != null) { twin.addLast(tmp.data); tmp = tmp.next; } return twin; } /** * Returns a deep copy of the list Complexity: O(n) */ public LinkedList<AnyType> copy2() { LinkedList<AnyType> twin = new LinkedList<AnyType>(); Node<AnyType> tmp = head; while (tmp != null) { twin.addFirst(tmp.data); tmp = tmp.next; } return twin.reverse(); } /** * Reverses the list Complewxity: O(n) */ public LinkedList<AnyType> reverse() { LinkedList<AnyType> list = new LinkedList<AnyType>(); Node<AnyType> tmp = head; while (tmp != null) { list.addFirst(tmp.data); tmp = tmp.next; } return list; } /** * Returns a deep copy of the immutable list It uses a tail reference. * Complexity: O(n) */ public LinkedList<AnyType> copy3() { LinkedList<AnyType> twin = new LinkedList<AnyType>(); Node<AnyType> tmp = head; if (head == null) return null; twin.head = new Node<AnyType>(head.data, null); Node<AnyType> tmpTwin = twin.head; while (tmp.next != null) { tmp = tmp.next; tmpTwin.next = new Node<AnyType>(tmp.data, null); tmpTwin = tmpTwin.next; } return twin; } /******************************************************* * * The Node class * ********************************************************/ private static class Node<AnyType> { private AnyType data; private Node<AnyType> next; public Node(AnyType data, Node<AnyType> next) { this.data = data; this.next = next; } } /******************************************************* * * The Iterator class * ********************************************************/ public Iterator<AnyType> iterator() { return new LinkedListIterator(); } private class LinkedListIterator implements Iterator<AnyType> { private Node<AnyType> nextNode; public LinkedListIterator() { nextNode = head; } public boolean hasNext() { return nextNode != null; } public AnyType next() { if (!hasNext()) throw new NoSuchElementException(); AnyType res = nextNode.data; nextNode = nextNode.next; return res; } public void remove() { throw new UnsupportedOperationException(); } } /***** Include the main() for testing and debugging *****/ public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("j"); list.addFirst("a"); list.addFirst("v"); list.addFirst("a"); System.out.println(list); LinkedList<String> twin = list.copy3(); System.out.println(twin); System.out.println(list.get(1)); // System.out.println(list.get(4)); //exception list.addLast("f"); Iterator itr = list.iterator(); while (itr.hasNext()) System.out.print(itr.next() + " "); System.out.println(); for (Object x : list) System.out.print(x + " "); System.out.println(); list.insertAfter("ea", "o"); System.out.println(list); System.out.println(list.getLast()); list.insertBefore("a", "r"); System.out.println(list); list.remove("v"); System.out.println(list); } }
package com.linkedList; public class CheckPalinromeInLinkedList { private Node head; private static class Node { private int value; private Node next; Node(int value) { this.value = value; } } public void addNodesToTheLast(Node node) { if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } public void printNodesInList() { Node temp = head; while (temp != null) { System.out.format("%d ", temp.value); temp = temp.next; } System.out.println(); } // This function will find middle element in linkedlist public static Node findMiddleNode(Node head) { // step 1 Node slowPointer, fastPointer; slowPointer = fastPointer = head; while (fastPointer != null) { fastPointer = fastPointer.next; if (fastPointer != null && fastPointer.next != null) { slowPointer = slowPointer.next; fastPointer = fastPointer.next; } } return slowPointer; } // Function to check if linked list is palindrome or not public static boolean validatePalindrome(Node head) { // Find middle node using slow and fast pointer Node middleNode = findMiddleNode(head); // we got head of second part Node secondHead = middleNode.next; // It is end of first part of linked list middleNode.next = null; // get reversed linked list for second part Node reverseSecondHead = reverseList(secondHead); while (head != null && reverseSecondHead != null) { if (head.value == reverseSecondHead.value) { head = head.next; reverseSecondHead = reverseSecondHead.next; continue; } else { return false; } } return true; } public static Node reverseList(Node currentNode) { // For first node, previousNode will be null Node previousNode = null; Node nextNode; while (currentNode != null) { nextNode = currentNode.next; // reversing the link currentNode.next = previousNode; // moving currentNode and previousNode by 1 node previousNode = currentNode; currentNode = nextNode; } return previousNode; } public static void main(String[] args) { CheckPalinromeInLinkedList list = new CheckPalinromeInLinkedList(); // Creating a linked list Node head = new Node(1); list.addNodesToTheLast(head); list.addNodesToTheLast(new Node(2)); list.addNodesToTheLast(new Node(1)); list.addNodesToTheLast(new Node(2)); list.addNodesToTheLast(new Node(1)); list.printNodesInList(); System.out.println("Linked list palidrome: " + validatePalindrome(head)); } }
package com.linkedList; public class DeleteDuplicates { Node head; // head of list /* Linked list Node */ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void remove_Duplicates() { Node current = head; Node next_next; if (head == null) return; while (current.next != null) { if (current.data == current.next.data) { next_next = current.next.next; current.next = null; current.next = next_next; } else current = current.next; } } // In front of the list insert a new Node public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data); if (temp.next != null) { System.out.print("->"); } temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { DeleteDuplicates l_list = new DeleteDuplicates(); // Insert data into LinkedList l_list.push(17); l_list.push(17); l_list.push(16); l_list.push(15); l_list.push(15); l_list.push(14); l_list.push(13); l_list.push(12); l_list.push(12); System.out.println("Original List with duplicate elements:"); l_list.printList(); l_list.remove_Duplicates(); System.out.println("After removing duplicates from the said list:"); l_list.printList(); } }
package com.linkedList; public class DeleteSpecifiedNode { public static ListNode head = new ListNode(10); public static void main(String[] args) { head.next = new ListNode(20); head.next.next = new ListNode(30); head.next.next.next = new ListNode(40); head.next.next.next.next = new ListNode(50); ListNode p = head; System.out.println("Original Linked list:"); printList(p); System.out.println("\nAfter deleting the fourth node, Linked list becomes:"); deleteNode(head.next.next.next); p = head; printList(p); } public static void deleteNode(ListNode node) { if (node.next != null) { int temp = node.val; node.val = node.next.val; node.next.val = temp; node.next = node.next.next; } else { ListNode p = head; while (p.next.val != node.val) { p = p.next; } p.next = null; } } static void printList(ListNode p) { while (p != null) { System.out.print(p.val); if (p.next != null) { System.out.print("->"); } p = p.next; } } } class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } }
package com.linkedList; public class DetectLoopInLinkedList { private Node head; private static class Node { private int value; private Node next; Node(int value) { this.value = value; } } public void addNodesToTheLast(Node node) { if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } public void printNodesInList() { Node temp = head; while (temp != null) { System.out.format("%d ", temp.value); temp = temp.next; } System.out.println(); } public boolean ifLoopExists() { Node fastPtr = head; Node slowPtr = head; while (fastPtr != null && fastPtr.next != null) { fastPtr = fastPtr.next.next; slowPtr = slowPtr.next; if (slowPtr == fastPtr) return true; } return false; } public static void main(String[] args) { DetectLoopInLinkedList list = new DetectLoopInLinkedList(); // Creating a linked list list.addNodesToTheLast(new Node(5)); list.addNodesToTheLast(new Node(6)); list.addNodesToTheLast(new Node(7)); list.addNodesToTheLast(new Node(1)); list.addNodesToTheLast(new Node(2)); list.printNodesInList(); // Test if loop existed or not System.out.println("Loop existed-->" + list.ifLoopExists()); } }
package com.linkedList; public class FindMergePointInLinkedList { static Node head1, head2; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } int getNode() { int c1 = getCountNodesInList(head1); int c2 = getCountNodesInList(head2); int d; if (c1 > c2) { d = c1 - c2; return getInsertionNode(d, head1, head2); } else { d = c2 - c1; return getInsertionNode(d, head2, head1); } } int getInsertionNode(int d, Node node1, Node node2) { int i; Node current1 = node1; Node current2 = node2; for (i = 0; i < d; i++) { if (current1 == null) { return -1; } current1 = current1.next; } while (current1 != null && current2 != null) { if (current1.data == current2.data) { return current1.data; } current1 = current1.next; current2 = current2.next; } return -1; } int getCountNodesInList(Node node) { Node current = node; int count = 0; while (current != null) { count++; current = current.next; } return count; } public static void main(String[] args) { FindMergePointInLinkedList list = new FindMergePointInLinkedList(); // creating first linked list list.head1 = new Node(3); list.head1.next = new Node(6); list.head1.next.next = new Node(15); list.head1.next.next.next = new Node(15); list.head1.next.next.next.next = new Node(30); // creating second linked list list.head2 = new Node(10); list.head2.next = new Node(15); list.head2.next.next = new Node(30); System.out.println("The node of intersection is " + list.getNode()); } }
package com.linkedList; public class FindMiddleElementInLinkedList { private Node head; private static class Node { private int value; private Node next; Node(int value) { this.value = value; } } public void addNodeToTheLast(Node node) { if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } public void printListOfNodes() { Node temp = head; while (temp != null) { System.out.format("%d ", temp.value); temp = temp.next; } System.out.println(); } // This function will find middle element in linkedlist public Node findMiddleNode(Node head) { Node slowPointer, fastPointer; slowPointer = fastPointer = head; while (fastPointer != null) { fastPointer = fastPointer.next; if (fastPointer != null && fastPointer.next != null) { slowPointer = slowPointer.next; fastPointer = fastPointer.next; } } return slowPointer; } public static void main(String[] args) { FindMiddleElementInLinkedList list = new FindMiddleElementInLinkedList(); // Creating a linked list Node head = new Node(5); list.addNodeToTheLast(head); list.addNodeToTheLast(new Node(6)); list.addNodeToTheLast(new Node(7)); list.addNodeToTheLast(new Node(1)); list.addNodeToTheLast(new Node(2)); list.printListOfNodes(); // finding middle element Node middle = list.findMiddleNode(head); System.out.println("Middle node will be: " + middle.value); } }
package com.linkedList; import java.util.LinkedList; public class MergeTwoLinkedLists { public static LinkedList<Integer> combine(LinkedList<Integer> l1, LinkedList<Integer> l2) { if (l1 == null && l2 == null) { return null; } else if (l1 == null) { return l2; } else if (l2 == null) { return l1; } // handle common cases LinkedList<Integer> result = new LinkedList<Integer>(); int size1 = l1.size(); int size2 = l2.size(); int size = size1 < size2 ? size1 : size2; for (int i = 0; i < size; i++) { result.add(l1.get(i)); result.add(l2.get(i)); } if (size1 < size2) { for (int i = size1; i < size2; i++) { result.add(l2.get(i)); } } else if (size1 > size2) { for (int i = size2; i < size1; i++) { result.add(l1.get(i)); } } else { ; } return result; } public static void main(String[] args) { LinkedList<Integer> list1 = new LinkedList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); LinkedList<Integer> list2 = new LinkedList<Integer>(); list2.add(5); list2.add(6); list2.add(7); LinkedList<Integer> list = combine(list1, list2); System.out.println(list); } }
package com.linkedList; import java.util.LinkedList; public class ReverseLinkedList { static Node head; static class Node { int data; Node next_node; Node(int d) { data = d; next_node = null; } } /* Reverse the linked list */ Node reverse(Node node) { Node prev_node = null; Node current_node = node; Node next_node = null; while (current_node != null) { next_node = current_node.next_node; current_node.next_node = prev_node; prev_node = current_node; current_node = next_node; } node = prev_node; return node; } // Prints the elements of the double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next_node; } } public static void main(String[] args) { ReverseLinkedList list = new ReverseLinkedList(); list.head = new Node(20); list.head.next_node = new Node(40); list.head.next_node.next_node = new Node(60); list.head.next_node.next_node.next_node = new Node(80); System.out.println("Original Linked list:"); list.printList(head); head = list.reverse(head); System.out.println(""); System.out.println("Reversed Linked list:"); list.printList(head); } }
package com.linkedList; public class SwaptwoAdjacentNodes { public static void main(String[] args) { String str1 = "The length of last word"; System.out.println("Original String: " + str1); System.out.println("Length of the last word of the above string: " + length_Of_last_word(str1)); } public static int length_Of_last_word(String str1) { int length_word = 0; String[] words = str1.split(" "); if (words.length > 0) { length_word = words[words.length - 1].length(); } else { length_word = 0; } return length_word; } }
STACK
package com.stack; import java.util.Iterator; import java.util.NoSuchElementException; /** * Stack follows LIFO(Last In First Out) Order * * @author HP * * @param <Item> */ public class Stack<Item> implements Iterable<Item> { private int n; // size of the stack private Node first; // top of stack // helper linked list class private class Node { private Item item; private Node next; } /** * Initializes an empty stack. */ public Stack() { first = null; n = 0; } /** * Returns true if this stack is empty. * * @return true if this stack is empty; false otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this stack. * * @return the number of items in this stack */ public int size() { return n; } /** * Adds the item to this stack. * * @param item * the item to add */ public void push(Item item) { Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; n++; } /** * Removes and returns the item most recently added to this stack. * * @return the item most recently added * @throws NoSuchElementException * if this stack is empty */ public Item pop() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); Item item = first.item; // save item to return first = first.next; // delete first node n--; return item; // return the saved item } /** * Returns (but does not remove) the item most recently added to this stack. * * @return the item most recently added to this stack * @throws NoSuchElementException * if this stack is empty */ public Item peek() { if (isEmpty()) throw new NoSuchElementException("Stack underflow"); return first.item; } /** * Returns a string representation of this stack. * * @return the sequence of items in this stack in LIFO order, separated by * spaces */ public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) { s.append(item); s.append(' '); } return s.toString(); } /** * Returns an iterator to this stack that iterates through the items in LIFO * order. * * @return an iterator to this stack that iterates through the items in LIFO * order */ public Iterator<Item> iterator() { return new ListIterator(); } // an iterator, doesn't implement remove() since it's optional private class ListIterator implements Iterator<Item> { private Node current = first; public boolean hasNext() { return current != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } /** * Unit tests the {@code Stack} data type. */ public static void main(String[] args) { Stack<String> stack = new Stack<String>(); String item = "test"; if (!item.equals("-")) stack.push(item); else if (!stack.isEmpty()) System.out.println(stack.pop() + " "); System.out.println("(" + stack.size() + " left on stack)"); } }
package com.stack; import java.util.Stack; class TestStack { Stack<Integer> stack; Integer minEle; TestStack() { stack = new Stack<Integer>(); } // Get Minimum Element void getMinElement() { if (stack.isEmpty()) System.out.println("Stack is empty"); else System.out.println("Minimum Element in the " + " stack is: " + minEle); } // prints top element of TestStack void peek() { if (stack.isEmpty()) { System.out.println("Stack is empty "); return; } Integer ele = stack.peek(); System.out.print("Top Most Element is: "); if (ele < minEle) System.out.println(minEle); else System.out.println(ele); } // Removes the top element from TestStack void pop() { if (stack.isEmpty()) { System.out.println("Stack is empty"); return; } System.out.print("Top Most Element Removed: "); Integer t = stack.pop(); if (t < minEle) { System.out.println(minEle); minEle = 2 * minEle - t; } else System.out.println(t); } // Insert new element into TestStack void push(Integer x) { if (stack.isEmpty()) { minEle = x; stack.push(x); System.out.println("Number Inserted: " + x); return; } if (x < minEle) { stack.push(2 * x - minEle); minEle = x; } else stack.push(x); System.out.println("Number Inserted: " + x); } }; // Driver Code public class FindMinimumElementInStack { public static void main(String[] args) { TestStack min = new TestStack(); min.push(14); min.push(71); min.getMinElement(); min.push(4); min.push(2); min.getMinElement(); min.pop(); min.getMinElement(); min.pop(); min.peek(); } }
package com.stack; import java.util.LinkedList; import java.util.Queue; public class ImplementStackUsing2QueuesAndPop { private Queue<Integer> q1 = new LinkedList<>(); private Queue<Integer> q2 = new LinkedList<>(); private int top; //Pop O(n) public void push(int x) { q2.add(x); top = x; while (!q1.isEmpty()) { q2.add(q1.remove()); } Queue<Integer> temp = q1; q1 = q2; q2 = temp; } // Push O(1) public void pop() { q1.remove(); if (!q1.isEmpty()) { top = q1.peek(); } } public static void main(String[] args) { ImplementStackUsing2QueuesAndPop is = new ImplementStackUsing2QueuesAndPop(); is.push(1); is.push(2); is.push(3); is.push(4); is.pop(); } }
package com.stack; import java.util.LinkedList; import java.util.Queue; public class ImplementStackUsing2QueuesAndPush { private Queue<Integer> q1 = new LinkedList<>(); private Queue<Integer> q2 = new LinkedList<>(); private int top; // Push O(1) public void push(int x) { q1.add(x); top = x; } // Pop O(n) public void pop() { while (q1.size() > 1) { top = q1.remove(); q2.add(top); } q1.remove(); Queue<Integer> temp = q1; q1 = q2; q2 = temp; } public static void main(String[] args) { ImplementStackUsing2QueuesAndPush is = new ImplementStackUsing2QueuesAndPush(); is.push(1); is.push(2); is.push(3); is.push(4); is.pop(); } }
package com.stack; import java.util.LinkedList; public class ImplementStackUsingOneQueue { private LinkedList<Integer> q1 = new LinkedList<>(); // Push O(n). public void push(int x) { q1.add(x); int sz = q1.size(); while (sz > 1) { q1.add(q1.remove()); sz--; } } // Pop O(1). public void pop() { q1.remove(); } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty(); } // Get the top element. public int top() { return q1.peek(); } public static void main(String[] args) { ImplementStackUsingOneQueue is = new ImplementStackUsingOneQueue(); is.push(1); is.push(2); is.push(3); is.push(4); is.pop(); } }
QUEUE
package com.queue; import java.util.Iterator; import java.util.NoSuchElementException; /** * Queue follows FIFO(First In First Out) Order * @author HP * * @param <Item> */ public class Queue<Item> implements Iterable<Item> { private int n; // number of elements on queue private Node first; // beginning of queue private Node last; // end of queue // helper linked list class private class Node { private Item item; // the item in the node private Node next; // reference to next item } /** * Initializes an empty queue. */ public Queue() { first = null; last = null; n = 0; } /** * Returns true if this queue is empty. * * @return {@code true} if this queue is empty; {@code false} otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this queue. * * @return the number of items in this queue */ public int size() { return n; } /** * Returns the number of items in this queue. * * @return the number of items in this queue */ public int length() { return n; } /** * Returns the item least recently added to this queue. * * @return the item least recently added to this queue * @throws NoSuchElementException if this queue is empty */ public Item peek() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); return first.item; } /** * Add the item to the queue. */ public void enqueue(Item item) { Node oldlast = last; last = new Node(); last.item = item; last.next = null; if (isEmpty()) first = last; else oldlast.next = last; n++; } /** * Removes and returns the item on this queue that was least recently added. * * @return the item on this queue that was least recently added * @throws NoSuchElementException if this queue is empty */ public Item dequeue() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); Item item = first.item; first = first.next; n--; if (isEmpty()) last = null; // to avoid loitering return item; } /** * Returns a string representation of this queue. * * @return the sequence of items in FIFO order, separated by spaces */ public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) s.append(item + " "); return s.toString(); } /** * Returns an iterator that iterates over the items in this queue in FIFO order. * * @return an iterator that iterates over the items in this queue in FIFO order */ public Iterator<Item> iterator() { return new ListIterator(); } // an iterator, doesn't implement remove() since it's optional private class ListIterator implements Iterator<Item> { private Node current = first; // node containing current item public boolean hasNext() { return current != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } /** * Unit tests the {@code Queue} data type. */ public static void main(String[] args) { Queue<String> queue = new Queue<String>(); String item = "test"; if (!item.equals("-")) queue.enqueue(item); else if (!queue.isEmpty()) System.out.println(queue.dequeue() + " "); System.out.println("(" + queue.size() + " left on queue)"); } }
package com.queue; import java.util.Stack; public class ImplementQueueUsingStack { private Stack<Integer> s1 = new Stack<>(); private Stack<Integer> s2 = new Stack<>(); private int front; //Pop O(n) public void push(int x) { if (s1.empty()) front = x; while (!s1.isEmpty()) s2.push(s1.pop()); s2.push(x); while (!s2.isEmpty()) s1.push(s2.pop()); } // Pop O(1) public void pop() { s1.pop(); if (!s1.empty()) front = s1.peek(); } // Return whether the queue is empty. public boolean empty() { return s1.isEmpty(); } // Get the front element. public int peek() { return front; } public static void main(String[] args) { ImplementQueueUsingStack iq = new ImplementQueueUsingStack(); iq.push(10); iq.push(12); iq.push(9); iq.pop(); iq.peek(); } }
RECURSION
package com.recursion; public class Factorial { // return n! // precondition: n >= 0 and n <= 20 public static long factorial(long n) { if (n < 0) throw new RuntimeException("Underflow error in factorial"); else if (n > 20) throw new RuntimeException("Overflow error in factorial"); else if (n == 0) return 1; else return n * factorial(n-1); } public static void main(String[] args) { long n = 5; System.out.println(factorial(n)); } }
package com.recursion; public class IntegerToBinary { public static void convert(int n) { if (n == 0) return; convert(n / 2); System.out.println(n % 2); } public static void main(String[] args) { int n = 10; convert(n); System.out.println(); } }
package com.recursion; public class ReverseString { void reverseString(String str1) { if ((str1 == null) || (str1.length() <= 1)) System.out.println(str1); else { System.out.print(str1.charAt(str1.length() - 1)); reverseString(str1.substring(0, str1.length() - 1)); } } public static void main(String[] args) { String str1 = "The quick brown fox jumps"; System.out.println("The given string is: " + str1); System.out.println("The string in reverse order is:"); ReverseString r = new ReverseString(); r.reverseString(str1); } }
package com.recursion; public class TowersOfHanoi { // print out instructions for moving n discs to // the left (if left is true) or right (if left is false) public static void moves(int n, boolean left) { if (n == 0) return; moves(n-1, !left); if (left) System.out.println(n + " left"); else System.out.println(n + " right"); moves(n-1, !left); } public static void main(String[] args) { int n = 3; moves(n, true); } }
DESIGNS
package com.bank; public class Bank { public static void main(String[] args) { BankAccount account = new BankAccount(100); int slaveCount = 4; Thread[] slaves = new Thread[slaveCount]; for(int i = 0; i < slaveCount; i++) { if (i % 2 == 0) { slaves[i] = new Producer(account); } else { slaves[i] = new Consumer(account); } } for(int i = 0; i < slaveCount; i++) { slaves[i].start(); } for(int i = 0; i < slaveCount; i++) { try { slaves[i].join(); } catch(InterruptedException ie) { System.err.println(ie.getMessage()); } finally { System.out.println("slave "+ i + " has died"); } } System.out.print("Closing balance = "); System.out.println("$" + account.getBalance()); } }
package com.bank; class BankAccount { private double balance; public BankAccount(double bal) { balance = bal; } public BankAccount() { this(0); } public synchronized double getBalance() { return balance; } public void deposit(double amt) { double temp = balance; temp = temp + amt; try { Thread.sleep(300); // simulate production time } catch (InterruptedException ie) { System.err.println(ie.getMessage()); } System.out.println("after deposit balance = $" + temp); balance = temp; } public void withdraw(double amt) { if (balance < amt) { System.out.println("Insufficient funds!"); return; } double temp = balance; temp = temp - amt; try { Thread.sleep(200); // simulate consumption time } catch (InterruptedException ie) { System.err.println(ie.getMessage()); } System.out.println("after withdrawl balance = $" + temp); balance = temp; } }
package com.bank; class Producer extends Thread { private BankAccount account; public Producer(BankAccount acct) { account = acct; } public void run() { for(int i = 0; i < 5; i++) { synchronized(account) { account.deposit(10); } } } }
package com.bank; class Consumer extends Thread { private BankAccount account; public Consumer(BankAccount acct) { account = acct; } public void run() { for(int i = 0; i < 5; i++) { synchronized(account) { account.withdraw(10); } } } }
import java.util.Scanner; public class Elevator { static int floor; public static void main(String args[]) { floor = (int) (Math.random() * 10 + 1); Scanner sr = new Scanner(System.in); System.out.println("The elevator is now on floor " + floor); System.out.print("Which floor are you at now (0-10) where 0 = basement: "); int current_floor = sr.nextInt(); if (floor == current_floor) { System.out.println("Enter the elevator"); } else { MoveElevator(current_floor); } System.out.println("To which floor would you want to go (0-10) where 0 = basement"); int target_floor = sr.nextInt(); MoveElevator(target_floor); } public static void MoveElevator(int target_floor) { int direction; if (target_floor > floor) { System.out.println("The elevator is on it's way up..."); direction = 1; } else { System.out.println("The elevator is on it's way down..."); direction = -1; } while (target_floor != floor) { floor += direction; System.out.println(floor); } System.out.println("The elevator has arrived"); } }
public class MainBus{ public static void main(String[] args){ BusReservation br = new BusReservation(); PassengerThread pt1 = new PassengerThread(2,br,"DUR"); PassengerThread pt2 = new PassengerThread(2, br, "SUG"); pt1.start(); pt2.start(); } }
public class BusReservation implements Runnable{ private int totalSeatsAvailable=2; public void run() { //BusReservation br = new BusReservation(); PassengerThread pt = (PassengerThread) Thread.currentThread(); boolean ticketsBooked = this.bookTickets(pt.getSeatsNeeded(), pt.getName()); if(ticketsBooked==true){ System.out.println("CONGRATS"+Thread.currentThread().getName()+" .. The number of seats requested("+pt.getSeatsNeeded()+") are BOOKED"); }else{ System.out.println("Sorry Mr."+Thread.currentThread().getName()+" .. The number of seats requested("+pt.getSeatsNeeded()+") are not available"); } } public synchronized boolean bookTickets(int seats, String name){ System.out.println("Welcome to Bus Resrvation "+Thread.currentThread().getName()+" Number of Tickets Available are:"+this.getTotalSeatsAvailable()); if (seats>this.getTotalSeatsAvailable()) { return false; } else { totalSeatsAvailable = totalSeatsAvailable-seats; return true; } } private int getTotalSeatsAvailable() { return totalSeatsAvailable; } }
public class PassengerThread extends Thread{ private int seatsNeeded; public PassengerThread(int seats, Runnable target, String name) { super(target,name); this.seatsNeeded = seats; } public int getSeatsNeeded() { return seatsNeeded; } }
import java.util.Scanner; public class MovieBooking { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] SeatNo = new int[30]; int Seats; int YesOrNo = 1; String CustomerName; while (YesOrNo == 1) { System.out.print("Welcome to Crazy Cinema!\nWhat is your name?\n"); CustomerName = input.nextLine(); System.out.printf("Welcome %s! Please have a look at the seating plan.\n\n", CustomerName); for (int i = 1; i <= 34; i++) { System.out.print("*"); } System.out.println(); System.out.print(" CINEMA 1 SEATING PLAN"); System.out.println(); for (int j = 1; j <= 34; j++) { System.out.print("*"); } System.out.println(); for (int SeatCounter = 0; SeatCounter < SeatNo.length; SeatCounter++) { System.out.printf(SeatCounter + "\t"); if (SeatCounter == 4) { System.out.println(); } else if (SeatCounter == 9) { System.out.println(); } else if (SeatCounter == 14) { System.out.println(); } else if (SeatCounter == 19) { System.out.println(); } else if (SeatCounter == 24) { System.out.println(); } else if (SeatCounter == 29) { System.out.println(); } } for (int k = 1; k <= 34; k++) { System.out.print("*"); } System.out.println(); System.out.print("Which seat would you like to book? "); Seats = input.nextInt(); while (Seats < 0 || Seats > 29) { System.out.println("Only 0 - 29 seats are allowed to book. Please try again: "); Seats = input.nextInt(); } for (int SeatCounter = 0; SeatCounter < SeatNo.length; SeatCounter++) { if (SeatCounter == Seats) { System.out.println("Seat " + Seats + " is successfully booked."); System.out.println( "Thanks for booking!\n\nWould you like to make next booking? (Type 1 = Yes; Type 2 = No)"); YesOrNo = input.nextInt(); if (YesOrNo == 2) { System.out.println("Thank you for using this program."); } } } while (YesOrNo != 1 && YesOrNo != 2) { System.out.println("Invalid input."); System.out.println("Type 1 = Continue booking; Type 2 = Exit the program"); YesOrNo = input.nextInt(); if (YesOrNo == 2) { System.out.println("Thank you for using this program."); } } } } }
import java.util.Scanner; public class Library { static Book head, pointer; static Scanner scan = new Scanner(System.in); public static void main(String[] args) { System.out.println("Welcome to Smart Book Store"); System.out.println("Please choose an option from the list below"); int choice = 0; do { System.out.println("1. Insert Book\n2. Delete Book\n3. Search Book\n4. Update Book\n5. View Book\n6. Exit"); choice = scan.nextInt(); try { choice = Integer.parseInt(scan.nextLine()); } catch (Exception e) { switch (choice) { case 1: addBook(); break; case 2: case 3: searchBook(); break; case 4: updateBook(); break; case 5: break; case 6: scan.close(); System.exit(0); break; default: System.out.println("Please choose from 1 to 5"); break; } } } while (true); } static void addBook() { if (head == null) { String details[] = enterDetails(); pointer = new Book(details[0], details[1], details[2]); head = pointer; pointer.next = null; } else { String details[] = enterDetails(); pointer.next = new Book(details[0], details[1], details[2]); pointer = (Book) pointer.next; } } static String[] enterDetails() { String[] details = new String[4]; try { String title; String ISBN; String authors; System.out.println("Please enter Book title"); title = scan.nextLine(); System.out.println("Please enter ISBN of book"); ISBN = scan.nextLine(); System.out.println("Please enter book's Author(s)"); authors = scan.nextLine(); details[0] = title; details[1] = ISBN; details[2] = authors; } catch (Exception e) { e.printStackTrace(); } return details; } private static void searchBook() { System.out.println(); System.out.println("1. Search by TITLE"); System.out.println("2. Search by ISBN"); System.out.println("3. Search by AUTHOR"); int choice = 0; choice: try { choice = Integer.parseInt(scan.nextLine()); } catch (Exception e) { System.out.println(); System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3"); break choice; } switch (choice) { case 1: System.out.println("Please enter Title of BOOK"); String title = scan.nextLine(); if (head == null) { System.out.println("List is EMPTY !"); return; } else { System.out.println(); System.out.println("BOOK(S) IN THE SYSTEM ARE: "); System.out.println(); pointer = head; while (pointer != null) { if (pointer.title.equals(title)) { System.out.println(pointer.getBook()); } pointer = (Book) pointer.next; } } break; case 2: System.out.println("Please enter ISBN of BOOK"); String ISBN = scan.nextLine(); if (head == null) { System.out.println("List is EMPTY !"); return; } else { System.out.println(); System.out.println("BOOK(S) IN THE SYSTEM ARE: "); System.out.println(); pointer = head; while (pointer != null) { if (pointer.ISBN.equals(ISBN)) { System.out.println(pointer.getBook()); break; } pointer = (Book) pointer.next; } } break; case 3: System.out.println("Please enter Author(s) of BOOK"); String authors = scan.nextLine(); if (head == null) { System.out.println("List is EMPTY !"); return; } else { System.out.println(); System.out.println("BOOK(S) IN THE SYSTEM ARE: "); System.out.println(); pointer = head; while (pointer != null) { if (pointer.authors.contains(authors)) { System.out.println(pointer.getBook()); break; } pointer = (Book) pointer.next; } } break; default: System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 5"); } } static void updateBook() { System.out.println(); System.out.println("1. Update TITLE"); System.out.println("2. Update ISBN"); System.out.println("3. Update AUTHOR"); int choice = 0; choice: try { choice = Integer.parseInt(scan.nextLine()); } catch (Exception e) { System.out.println(); System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3"); break choice; } switch (choice) { case 1: System.out.println("Please update Title of BOOK"); String another1 = scan.nextLine(); if (head == null) { System.out.println("Title not Updated !"); return; } else { System.out.println(); System.out.println("Your new title is: " + another1); System.out.println(); pointer = head; while (pointer != null) { if (pointer.title.equals(another1)) { System.out.println(pointer.getBook()); break; } pointer = (Book) pointer.next; } } case 2: System.out.println("Please update ISBN of BOOK"); String ISBN = scan.nextLine(); if (head == null) { System.out.println("Isbn not updated !"); return; } else { System.out.println(); int aISBN = Integer.parseInt(ISBN.trim()); System.out.println("Your book's updated ISBN is: " + aISBN); System.out.println(); pointer = head; while (pointer != null) { if (pointer.ISBN.equals(aISBN)) { System.out.println(pointer.getBook()); break; } pointer = (Book) pointer.next; } } case 3: System.out.println("Please enter Author(s) of BOOK"); String upauthor1 = scan.nextLine(); if (head == null) { System.out.println("List is EMPTY !"); return; } else { System.out.println(); System.out.println("Book's Updated author is: " + upauthor1); System.out.println(); pointer = head; while (pointer != null) { if (pointer.authors.contains(upauthor1)) { System.out.println(pointer.getBook()); break; } pointer = (Book) pointer.next; } break; } } } }
public class Book { String authors; final String ISBN; final String title; public Object next; Book(String title, String ISBN, String authors) { this.title = title; this.authors = authors; this.ISBN = ISBN ; } public String getBook() { return "Book Title: " + this.title + "\n" + "Book ISBN: " + this.ISBN + "\n" + "Book Authors: " + this.authors + "\n" ; } }
import java.io.BufferedReader; import java.io.InputStreamReader; class RailwayTicketDesign { int i, x = 0, index = 0, w = 0; int c = 0; String names[], address[], contact[], gender[]; String wnames[], waddress[], wcontact[], wgender[]; String stations[] = { "Howrah", "Burdwan", "Asansol", "Dhanbad", "Tatanagar" }; int distance[] = { 0, 100, 200, 250, 350 }; int age[], wage[]; String ans, start, end; String fare[] = { "Howrah - Burdwan - 60", "Howrah - Asansol - 110", "Howrah - Dhanbad - 160", "Howrah - Tatanagar - 200", "Burdwan - Asansol - 60", "Burdwan - Dhanbad - 110", "Burdwan - Tatanagar - 160", "Asansol - Dhanbad - 60", "Asansol - Tatanagar - 110", "Dhanbad - Tatanagar - 60" }; // FOR SECOND TRAIN String names2[], address2[], contact2[], gender2[]; String wnames2[], waddress2[], wcontact2[], wgender2[]; String stations2[] = { "Howrah", "Burdwan", "Gaya", "Ayodhya", "Jammu Tawi" }; int distance2[] = { 0, 100, 200, 250, 350 }; int age2[], wage2[]; String ans2, start2, end2; String fare2[] = { "Howrah - Burdwan - 60", "Howrah - Gaya - 110", "Howrah -Ayodhya- 360", "Howrah -Jammu Tawi - 580", "Burdwan - Gaya - 60", "Burdwan - Ayodhya - 310", "Burdwan - Jammu Tawi - 460", "Gaya - Ayodhya- 160", "Gaya - Jammu Tawi - 310", "Ayodhya - Jammu Tawi - 260" }; // FOR THIRD TRAIN String names3[], address3[], contact3[], gender3[]; String wnames3[], waddress3[], wcontact3[], wgender3[]; String stations3[] = { "Howrah", "Liluah", "Burdwan", "Durgapur", "Ondal" }; int distance3[] = { 0, 100, 200, 250, 350 }; int age3[], wage3[]; String ans3, start3, end3; String fare3[] = { "Howrah - Liluah - 60", "Howrah - Burdwan - 110", "Howrah - Durgapur - 160", "Howrah -Ondal- 200", " Liluah- Burdwan - 60", "Liluah - Durgapur - 110", "Liluah - Ondal - 160", " Burdwan-Durgapur - 60", "Burdwan - Ondal - 110", "Durgapur - Ondal- 60" }; // FOR FOURTH TRAIN String names4[], address4[], contact4[], gender4[]; String wnames4[], waddress4[], wcontact4[], wgender4[]; String stations4[] = { "Srinagar", "Katra", "Jammu Tawi", "Ludhiana", "Amritsar" }; int distance4[] = { 0, 100, 200, 250, 350 }; int age4[], wage4[]; String ans4, start4, end4; String fare4[] = { "Srinagar- Katra - 60", " Srinagar- Jammu Tawi - 110", "Srinagar - Ludhiana - 160", " Srinagar- Amritsar - 200", " Katra- Jammu Tawi - 60", "Katra -Ludhiana - 110", "Katra -Amritsar - 160", " Jammu Tawi-Ludhiana - 60", "Jammu Tawi - Amritsar - 110", " Ludhiana-Amritsar - 60" }; // FOR FIFTH TRAIN String names5[], address5[], contact5[], gender5[]; String wnames5[], waddress5[], wcontact5[], wgender5[]; String stations5[] = { "Howrah", "Kharagpur", "Khoddar", "Bhubaneshwar", "Puri" }; int distance5[] = { 0, 100, 200, 250, 350 }; int age5[], wage5[]; String ans5, start5, end5; String fare5[] = { "Howrah - Kharagpur - 160", "Howrah - Khoddar - 210", "Howrah -Bhubaneshwar - 270", "Howrah - Puri - 350", "Kharagpur -Khoddar - 160", "Kharagpur -Bhubaneshwar - 210", " Kharagpur- Puri - 300", "Khoddar - Bhubaneshwar - 160", "Khoddar - Puri - 210", " Bhubaneshwar-Puri- 160" }; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int booked[] = new int[100]; int booked2[] = new int[100]; int booked3[] = new int[100]; int booked4[] = new int[100]; int booked5[] = new int[100]; RailwayTicketDesign() { names = new String[100]; address = new String[100]; contact = new String[100]; gender = new String[100]; age = new int[100]; wnames = new String[100]; waddress = new String[100]; wcontact = new String[100]; wgender = new String[100]; wage = new int[100]; for (int i = 0; i < 100; i++) booked[i] = -1; // second train names2 = new String[100]; address2 = new String[100]; contact2 = new String[100]; gender2 = new String[100]; age2 = new int[100]; wnames2 = new String[100]; waddress2 = new String[100]; wcontact2 = new String[100]; wgender2 = new String[100]; wage2 = new int[100]; for (int i = 0; i < 100; i++) booked2[i] = -1; // third names3 = new String[100]; address3 = new String[100]; contact3 = new String[100]; gender3 = new String[100]; age3 = new int[100]; wnames3 = new String[100]; waddress3 = new String[100]; wcontact3 = new String[100]; wgender3 = new String[100]; wage3 = new int[100]; for (int i = 0; i < 100; i++) booked3[i] = -1; // fourth names4 = new String[100]; address4 = new String[100]; contact4 = new String[100]; gender4 = new String[100]; age4 = new int[100]; wnames4 = new String[100]; waddress4 = new String[100]; wcontact4 = new String[100]; wgender4 = new String[100]; wage4 = new int[100]; for (int i = 0; i < 100; i++) booked4[i] = -1; // fifth names5 = new String[100]; address5 = new String[100]; contact5 = new String[100]; gender5 = new String[100]; age5 = new int[100]; wnames5 = new String[100]; waddress5 = new String[100]; wcontact5 = new String[100]; wgender5 = new String[100]; wage5 = new int[100]; for (int i = 0; i < 100; i++) booked5[i] = -1; } public void takeData() throws Exception { int train; System.out.println( "Enter 1 for Tatanagar Mail , 2 for Jammu Tawi \n 3 for Mayurakshi, 4 for Punjab Mail AND 5 for Puri Mail"); train = Integer.parseInt(br.readLine()); if (train == 1) first(); else if (train == 2) second(); else if (train == 3) third(); else if (train == 4) fourth(); else if (train == 5) fifth(); } void first() throws Exception { System.out.print("\nStaring Station:"); for (i = 0; i < stations.length; i++) System.out.print(" " + stations[i]); System.out.print(" :"); start = br.readLine(); System.out.print("\nEnding Station:"); for (i = 0; i < stations.length; i++) System.out.print(" " + stations[i]); System.out.print(" :"); end = br.readLine(); start = start + " - " + end; while (true) { System.out.print("\nName:"); names[x] = br.readLine(); if (c == 0) { System.out.print("\nAddress:"); address[x] = br.readLine(); } else address[x] = address[x - 1]; System.out.print("\nAge:"); age[x] = Integer.parseInt(br.readLine()); System.out.print("\nGender:"); gender[x] = br.readLine(); c++; x++; if (c == 6) break; System.out.print("\nAny More Member (y/n):"); ans = br.readLine(); if (ans.equalsIgnoreCase("N")) break; } show1(); } void second() throws Exception { System.out.print("\nStaring Station:"); for (i = 0; i < stations2.length; i++) System.out.print(" " + stations2[i]); System.out.print(" :"); start2 = br.readLine(); System.out.print("\nEnding Station:"); for (i = 0; i < stations2.length; i++) System.out.print(" " + stations2[i]); System.out.print(" :"); end2 = br.readLine(); start2 = start2 + " - " + end2; while (true) { System.out.print("\nName:"); names2[x] = br.readLine(); if (c == 0) { System.out.print("\nAddress:"); address2[x] = br.readLine(); } else address2[x] = address2[x - 1]; System.out.print("\nAge:"); age2[x] = Integer.parseInt(br.readLine()); System.out.print("\nGender:"); gender2[x] = br.readLine(); c++; x++; if (c == 6) break; System.out.print("\nAny More Member (y/n):"); ans = br.readLine(); if (ans.equalsIgnoreCase("N")) break; } show2(); } void third() throws Exception { System.out.print("\nStaring Station:"); for (i = 0; i < stations3.length; i++) System.out.print(" " + stations3[i]); System.out.print(" :"); start3 = br.readLine(); System.out.print("\nEnding Station:"); for (i = 0; i < stations3.length; i++) System.out.print(" " + stations3[i]); System.out.print(" :"); end3 = br.readLine(); start3 = start3 + " - " + end3; while (true) { System.out.print("\nName:"); names3[x] = br.readLine(); if (c == 0) { System.out.print("\nAddress:"); address3[x] = br.readLine(); } else address3[x] = address3[x - 1]; System.out.print("\nAge:"); age3[x] = Integer.parseInt(br.readLine()); System.out.print("\nGender:"); gender3[x] = br.readLine(); c++; x++; if (c == 6) break; System.out.print("\nAny More Member (y/n):"); ans = br.readLine(); if (ans.equalsIgnoreCase("N")) break; } show3(); } void fourth() throws Exception { System.out.print("\nStaring Station:"); for (i = 0; i < stations4.length; i++) System.out.print(" " + stations4[i]); System.out.print(" :"); start4 = br.readLine(); System.out.print("\nEnding Station:"); for (i = 0; i < stations4.length; i++) System.out.print(" " + stations4[i]); System.out.print(" :"); end4 = br.readLine(); start4 = start4 + " - " + end4; while (true) { System.out.print("\nName:"); names4[x] = br.readLine(); if (c == 0) { System.out.print("\nAddress:"); address4[x] = br.readLine(); } else address4[x] = address4[x - 1]; System.out.print("\nAge:"); age4[x] = Integer.parseInt(br.readLine()); System.out.print("\nGender:"); gender4[x] = br.readLine(); c++; x++; if (c == 6) break; System.out.print("\nAny More Member (y/n):"); ans = br.readLine(); if (ans.equalsIgnoreCase("N")) break; } show4(); } void fifth() throws Exception { System.out.print("\nStaring Station:"); for (i = 0; i < stations5.length; i++) System.out.print(" " + stations5[i]); System.out.print(" :"); start5 = br.readLine(); System.out.print("\nEnding Station:"); for (i = 0; i < stations5.length; i++) System.out.print(" " + stations5[i]); System.out.print(" :"); end5 = br.readLine(); start5 = start5 + " - " + end5; while (true) { System.out.print("\nName:"); names5[x] = br.readLine(); if (c == 0) { System.out.print("\nAddress:"); address5[x] = br.readLine(); } else address5[x] = address5[x - 1]; System.out.print("\nAge:"); age5[x] = Integer.parseInt(br.readLine()); System.out.print("\nGender:"); gender5[x] = br.readLine(); c++; x++; if (c == 6) break; System.out.print("\nAny More Member (y/n):"); ans = br.readLine(); if (ans.equalsIgnoreCase("N")) break; } show5(); } void show1() throws Exception { String s; int famt1 = 0, famt = 0; index = 0; for (i = 0; i < fare.length; i++) { s = fare[i]; index = s.lastIndexOf("-"); famt1 = Integer.parseInt(s.substring(index + 1).trim()); s = s.substring(0, index).trim(); // System.out.println(s+ " \n "+famt1 + "\n"+start); if (start.equalsIgnoreCase(s)) break; } for (i = 0; i < 100; i++) { if (booked[i] < 0) index++; } if (x > index) { System.out.println("No Berth...\nWant waiting list ticket?(y/n):"); ans = br.readLine(); if (!ans.equalsIgnoreCase("N")) { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nWaiting List Tickets\n"); System.out.println("\nName Address Age Gender Fare(Rs.) Waiting No\n"); for (i = x - c; i < x; i++) { wnames[w] = names[i]; waddress[w] = address[i]; wage[w] = age[i]; wgender[w] = gender[i]; w++; // System.out.println("Age="+age[i]); if (age[i] <= 12) { famt += famt1 / 2; System.out.println(names[i] + " " + address[i] + " " + age[i] + " " + gender[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names[i] + " " + address[i] + " " + age[i] + " " + gender[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); x = x - c; } } else { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nConfirmed Tickets\n"); System.out.println("\nName Address Age Gender Fare (Rs.) Berth No\n"); for (i = x - c; i < x; i++) { for (int j = 0; j < 100; j++) { if (booked[j] == -1) booked[j] = 0; break; } // famt+=famt1; if (age[i] <= 12) { famt += famt1 / 2; System.out.println(names[i] + " " + address[i] + " " + age[i] + " " + gender[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names[i] + " " + address[i] + " " + age[i] + " " + gender[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); } c = 0; } void show2() throws Exception { String s; int famt1 = 0, famt = 0; index = 0; for (i = 0; i < fare2.length; i++) { s = fare2[i]; index = s.lastIndexOf("-"); famt1 = Integer.parseInt(s.substring(index + 1).trim()); s = s.substring(0, index).trim(); // System.out.println(s+ " \n "+famt1 + "\n"+start); if (start2.equalsIgnoreCase(s)) break; } for (i = 0; i < 100; i++) { if (booked2[i] < 0) index++; } if (x > index) { System.out.println("No Berth...\nWant waiting list ticket?(y/n):"); ans = br.readLine(); if (!ans.equalsIgnoreCase("N")) { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nWaiting List Tickets\n"); System.out.println("\nName Address Age Gender Fare(Rs.) Waiting No\n"); for (i = x - c; i < x; i++) { wnames2[w] = names2[i]; waddress2[w] = address2[i]; wage2[w] = age2[i]; wgender2[w] = gender2[i]; w++; if (age2[i] <= 12) { famt += famt1 / 2; System.out.println(names2[i] + " " + address2[i] + " " + age2[i] + " " + gender2[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names2[i] + " " + address2[i] + " " + age2[i] + " " + gender2[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); x = x - c; } } else { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nConfirmed Tickets\n"); System.out.println("\nName Address Age Gender Fare (Rs.) Berth No\n"); for (i = x - c; i < x; i++) { for (int j = 0; j < 100; j++) { if (booked2[j] == -1) booked2[j] = 0; break; } if (age2[i] <= 12) { famt += famt1 / 2; System.out.println(names2[i] + " " + address2[i] + " " + age2[i] + " " + gender2[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names2[i] + " " + address2[i] + " " + age2[i] + " " + gender2[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); } c = 0; } void show3() throws Exception { String s; int famt1 = 0, famt = 0; index = 0; for (i = 0; i < fare3.length; i++) { s = fare3[i]; index = s.lastIndexOf("-"); famt1 = Integer.parseInt(s.substring(index + 1).trim()); s = s.substring(0, index).trim(); // System.out.println(s+ " \n "+famt1 + "\n"+start); if (start3.equalsIgnoreCase(s)) break; } for (i = 0; i < 100; i++) { if (booked3[i] < 0) index++; } if (x > index) { System.out.println("No Berth...\nWant waiting list ticket?(y/n):"); ans = br.readLine(); if (!ans.equalsIgnoreCase("N")) { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nWaiting List Tickets\n"); System.out.println("\nName Address Age Gender Fare(Rs.) Waiting No\n"); for (i = x - c; i < x; i++) { wnames3[w] = names3[i]; waddress3[w] = address3[i]; wage3[w] = age3[i]; wgender3[w] = gender3[i]; w++; if (age3[i] <= 12) { famt += famt1 / 2; System.out.println(names3[i] + " " + address3[i] + " " + age3[i] + " " + gender3[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names3[i] + " " + address3[i] + " " + age3[i] + " " + gender3[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); x = x - c; } } else { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nConfirmed Tickets\n"); System.out.println("\nName Address Age Gender Fare (Rs.) Berth No\n"); for (i = x - c; i < x; i++) { for (int j = 0; j < 100; j++) { if (booked3[j] == -1) booked3[j] = 0; break; } if (age3[i] <= 12) { famt += famt1 / 2; System.out.println(names3[i] + " " + address3[i] + " " + age3[i] + " " + gender3[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names3[i] + " " + address3[i] + " " + age3[i] + " " + gender3[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); } c = 0; } void show4() throws Exception { String s; int famt1 = 0, famt = 0; index = 0; for (i = 0; i < fare4.length; i++) { s = fare4[i]; index = s.lastIndexOf("-"); famt1 = Integer.parseInt(s.substring(index + 1).trim()); s = s.substring(0, index).trim(); // System.out.println(s+ " \n "+famt1 + "\n"+start); if (start4.equalsIgnoreCase(s)) break; } for (i = 0; i < 100; i++) { if (booked4[i] < 0) index++; } if (x > index) { System.out.println("No Berth...\nWant waiting list ticket?(y/n):"); ans = br.readLine(); if (!ans.equalsIgnoreCase("N")) { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nWaiting List Tickets\n"); System.out.println("\nName Address Age Gender Fare(Rs.) Waiting No\n"); for (i = x - c; i < x; i++) { wnames4[w] = names4[i]; waddress4[w] = address4[i]; wage4[w] = age4[i]; wgender4[w] = gender4[i]; w++; if (age4[i] <= 12) { famt += famt1 / 2; System.out.println(names4[i] + " " + address4[i] + " " + age4[i] + " " + gender4[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names4[i] + " " + address4[i] + " " + age4[i] + " " + gender4[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); x = x - c; } } else { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nConfirmed Tickets\n"); System.out.println("\nName Address Age Gender Fare (Rs.) Berth No\n"); for (i = x - c; i < x; i++) { for (int j = 0; j < 100; j++) { if (booked4[j] == -1) booked4[j] = 0; break; } if (age4[i] <= 12) { famt += famt1 / 2; System.out.println(names4[i] + " " + address4[i] + " " + age4[i] + " " + gender4[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names4[i] + " " + address4[i] + " " + age4[i] + " " + gender4[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); } c = 0; } void show5() throws Exception { String s; int famt1 = 0, famt = 0; index = 0; for (i = 0; i < fare5.length; i++) { s = fare5[i]; index = s.lastIndexOf("-"); famt1 = Integer.parseInt(s.substring(index + 1).trim()); s = s.substring(0, index).trim(); // System.out.println(s+ " \n "+famt1 + "\n"+start); if (start5.equalsIgnoreCase(s)) break; } for (i = 0; i < 100; i++) { if (booked5[i] < 0) index++; } if (x > index) { System.out.println("No Berth...\nWant waiting list ticket?(y/n):"); ans = br.readLine(); if (!ans.equalsIgnoreCase("N")) { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nWaiting List Tickets\n"); System.out.println("\nName Address Age Gender Fare(Rs.) Waiting No\n"); for (i = x - c; i < x; i++) { wnames5[w] = names5[i]; waddress5[w] = address5[i]; wage5[w] = age5[i]; wgender5[w] = gender5[i]; w++; if (age5[i] <= 12) { famt += famt1 / 2; System.out.println(names5[i] + " " + address5[i] + " " + age5[i] + " " + gender5[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names5[i] + " " + address5[i] + " " + age5[i] + " " + gender5[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); x = x - c; } } else { System.out.println("\nSouth Eastern Railway\n"); System.out.println("\nConfirmed Tickets\n"); System.out.println("\nName Address Age Gender Fare (Rs.) Berth No\n"); for (i = x - c; i < x; i++) { for (int j = 0; j < 100; j++) { if (booked5[j] == -1) booked5[j] = 0; break; } if (age5[i] <= 12) { famt += famt1 / 2; System.out.println(names5[i] + " " + address5[i] + " " + age5[i] + " " + gender5[i] + " " + (famt1 / 2) + " " + w); } else { famt += famt1; System.out.println(names5[i] + " " + address5[i] + " " + age5[i] + " " + gender5[i] + " " + famt1 + " " + w); } } System.out.println("Total (Rs.)" + famt); System.out.println("In Words Rs:" + numToWord(famt)); } c = 0; } String numToWord(int n) { String str = ""; int zero = 0, i, rev = 0, n1; n1 = n; while (true) { if (n % 10 == 0) zero++; else break; n = n / 10; } n = n1; for (i = n; i > 0; i = i / 10) { rev = rev * 10 + i % 10; } while (rev > 0) { switch (rev % 10) { case 0: str = str + " Zero"; break; case 1: str = str + " One"; break; case 2: str = str + " Two"; break; case 3: str = str + " Three"; break; case 4: str = str + " Four"; break; case 5: str = str + " Five"; break; case 6: str = str + " Six"; break; case 7: str = str + " Seven"; break; case 8: str = str + " Eight"; break; case 9: str = str + " Nine"; break; } rev = rev / 10; } for (i = 0; i < zero; i++) str = str + " Zero"; return str; } public static void main(String args[]) throws Exception { BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); RailwayTicketDesign ob = new RailwayTicketDesign(); char ch; while (true) { ob.takeData(); System.out.println("Any More(y/n):"); ch = (char) br1.read(); ch = Character.toLowerCase(ch); if (ch == 'n') break; } } }
package com.design; import java.util.concurrent.Semaphore; public class Library { private static final int MAX_PERMIT = 3; private final Semaphore availableBook = new Semaphore(MAX_PERMIT, true); private Book[] books = { new Book("Vikramarka"), new Book("Mahabharat"), new Book("Panchtantra") }; private boolean[] beingRead = new boolean[MAX_PERMIT]; // Book is being issued to reader public Object issueBook() throws InterruptedException { availableBook.acquire(); return getNextAvailableBook(); } private synchronized Book getNextAvailableBook() { Book book = null; for (int i = 0; i < MAX_PERMIT; ++i) { if (!beingRead[i]) { beingRead[i] = true; book = books[i]; System.out.println(book.getBookName() + " has been issued."); break; } } return book; } // Book is being returned to library public void returnBook(Book book) { if (markAsAvailableBook(book)) availableBook.release(); } private synchronized boolean markAsAvailableBook(Book book) { boolean flag = false; for (int i = 0; i < MAX_PERMIT; ++i) { if (book == books[i]) { if (beingRead[i]) { beingRead[i] = false; flag = true; System.out.println(book.getBookName() + " has been returned."); } break; } } return flag; } }
package com.design; public class Book { private String bookName; public Book(String bookName) { this.bookName = bookName; } public void read() { System.out.println(bookName + " is being read......"); try { Thread.sleep(2000); }catch(InterruptedException e) { e.printStackTrace(); } } public String getBookName() { return bookName; } }
package com.design; public class Reader implements Runnable { private Library library; public Reader(Library library) { this.library = library; } @Override public void run() { try { Book book = (Book)library.issueBook(); book.read(); library.returnBook(book); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.design; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { final int threadCount = 6; final ExecutorService exService = Executors.newFixedThreadPool(threadCount); final Library library = new Library(); for(int i=0; i < threadCount; i++) { Reader reader = new Reader(library); exService.execute(reader); } exService.shutdown(); } }
package com.design; import java.util.concurrent.Semaphore; public class Printer { private static final int MAX_PERMIT = 1; private final Semaphore semaphore = new Semaphore(MAX_PERMIT, true); public void print(String jobName) { try { semaphore.acquire(); System.out.println("Printing Job: "+ jobName); Thread.sleep(2000); System.out.println("Finished Job: "+ jobName); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release(); } } }
package com.design; public class Job implements Runnable { private Printer printer; private String jobName; public Job(Printer printer, String jobName) { this.printer = printer; this.jobName = jobName; } @Override public void run() { System.out.println("Job sent to printer:"+ jobName); printer.print(jobName); } }
package com.design; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainProgram { public static void main(String[] args) { final int threadCount = 5; final ExecutorService exService = Executors.newFixedThreadPool(threadCount); final Printer printer = new Printer(); for (int i = 1; i <= threadCount; i++) { exService.execute(new Job(printer, "Job-" + i)); } exService.shutdown(); } }
EXCEPTIONS
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CustomerCustomizedException { public void analyze(List<String> data) { if (data.size() > 50) { // runtime exception throw new TooLargeException("List can't exceed 50 items!"); } // ... } public static void main(String[] args) { CustomerCustomizedException customer = new CustomerCustomizedException(); // create 100 size List<String> data = new ArrayList<>(Collections.nCopies(100, "formula")); customer.analyze(data); } }
public class TooLargeException extends RuntimeException{ public TooLargeException(String message) { super(message); } }
package com.exceptions; public class ArthmaticException { public static void main(String args[]) { try { int a = 70, b = 0; int result = a / b; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("throws arthmatic exception"); } } }
package com.exceptions; public class NumberFormatException { public static void main(String[] args) { try { // intentional error String str = "formula"; int i = Integer.parseInt(str); System.out.println("int value = " + i); } catch (Exception e) { e.printStackTrace(); } } }
package com.exceptions; class Super { int i = 10; } class Sub extends Super { int j = 20; } class Child extends Sub { int k = 30; } public class ClassCastException { public static void main(String[] args) { Super sup = new Sub(); Sub sub = (Sub) sup; Child child = (Child) sub; System.out.println(child.k); } }
package com.exceptions; public class NullPointerException { public static void main(String[] args) { Object obj = null; obj.toString(); // this will throw a NullPointerException } }
package com.exceptions; public class ArrayIndexOutOfBoundException { public static void main(String[] args) { int[] arr = new int[3]; for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); } } }
package com.exceptions; public class StringOutOfBoundException { public static void main(String[] args) { String[] names = { "dur", "sug", "pur" }; for (int i = 0; i <= names.length; i++) { System.out.println(names[i]); } } }
package com.exceptions; import java.io.File; public class IllegalArgumentException { public static String createRelativePath(String parent, String filename) { if (parent == null) try { throw new Exception("The parent path cannot be null!"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (filename == null) try { throw new Exception("The filename cannot be null!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return parent + File.separator + filename; } public static void main(String[] args) { // The following command will be successfully executed. System.out.println(IllegalArgumentException.createRelativePath("dir1", "file1")); System.out.println(); // The following command throws an IllegalArgumentException. System.out.println(IllegalArgumentException.createRelativePath(null, "file1")); } }
package com.exceptions; import java.util.ArrayList; public class IllegalMonitorStateException { public static IllegalMonitorStateException monitor = null; public static int num = 4; public static ArrayList<RunThread> list = null; public static void main(String[] args) { monitor = new IllegalMonitorStateException(); } IllegalMonitorStateException() { list = new ArrayList<RunThread>(num); for (int i = 0; i < num; i++) { RunThread r = new RunThread(); list.add(r); new Thread(r).start(); } System.out.println("Runners ready."); notifyAll(); } }
package com.exceptions; class RunThread implements Runnable { public void run() { try { IllegalMonitorStateException.monitor.wait(); } catch (InterruptedException e) { } System.out.println("Run thread away!"); } }
package com.exceptions; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class ConcurrentModificationException { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); Iterator<String> it = list.iterator(); while (it.hasNext()) { String value = it.next(); System.out.println("List Value:" + value); if (value.equals("3")) list.remove(value); } Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); map.put("2", "2"); map.put("3", "3"); Iterator<String> itr = map.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); System.out.println("Map Value:" + map.get(key)); if (key.equals("2")) { map.put("1", "4"); } } } }
package com.exceptions; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class UnSupportedException { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("java"); list.add("formula"); System.out.println("list: " + list); Collection<String> immutablelist = Collections.unmodifiableCollection(list); immutablelist.add("dur"); } }
package com.exceptions; import java.io.File; import java.util.Scanner; public class FileNotFoundException { public static void main(String args[]) { File file = new File("lines.txt"); System.out.println(file.exists()); try { Scanner scan = new Scanner(file); } catch (java.io.FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
CONCURRENCY
package com.atomic; import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerExample { public static class ParkingCounter extends AtomicInteger { private int maxNumber; public ParkingCounter(int maxNumber) { set(0); this.maxNumber = maxNumber; } public boolean carIn() { for (; ; ) { int value = get(); if (value == maxNumber) { System.out.printf("Parking counter: The parking lot is full.\n"); return false; } else { int newValue = value + 1; boolean changed = compareAndSet(value, newValue); if (changed) { System.out.printf("Parking counter: A car has arrived.\n"); return true; } } } } public boolean carOut() { for (; ; ) { int value = get(); if (value == 0) { System.out.printf("Parking counter: The parking lot is empty.\n"); return false; } else { int newValue = value - 1; boolean changed = compareAndSet(value, newValue); if (changed) { System.out.printf("Parking counter: A car has left.\n"); return true; } } } } } public static class Sensor1 implements Runnable { private ParkingCounter counter; public Sensor1(ParkingCounter counter) { this.counter = counter; } @Override public void run() { counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carOut(); counter.carOut(); counter.carOut(); counter.carIn(); counter.carIn(); counter.carIn(); } } public static class Sensor2 implements Runnable { private ParkingCounter counter; public Sensor2(ParkingCounter counter) { this.counter = counter; } @Override public void run() { counter.carIn(); counter.carOut(); counter.carOut(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); counter.carIn(); } } public static void main(String[] args) throws InterruptedException { ParkingCounter counter = new ParkingCounter(5); Sensor1 sensor1 = new Sensor1(counter); Sensor2 sensor2 = new Sensor2(counter); Thread thread1 = new Thread(sensor1); Thread thread2 = new Thread(sensor2); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.printf("Main: Number of cars:%d\n", counter.get()); } }
package com.blockingqueue; import java.util.concurrent.atomic.AtomicLong; public class AtomicLongExample { public static class Account { private AtomicLong balance; public long getBalance() { return balance.get(); } public void setBalance(long balance) { this.balance.set(balance); } public Account() { this.balance = new AtomicLong(); } public void addAmount(long amount) { this.balance.getAndAdd(amount); } public void subtractAmount(long amount) { this.balance.getAndAdd(-amount); } } public static class Company implements Runnable { private Account account; public Company(Account account) { this.account = account; } @Override public void run() { for (int i = 0; i < 10; i++) { account.addAmount(1000); } } } public static class Bank implements Runnable { private Account account; public Bank(Account account) { this.account = account; } @Override public void run() { for (int i = 0; i < 10; i++) { account.subtractAmount(1000); } } } public static void main(String[] args) { Account account = new Account(); account.setBalance(1000); Company company = new Company(account); Thread companyThread = new Thread(company); Bank bank = new Bank(account); Thread bankThread = new Thread(bank); System.out.printf("Account: Initial Balance: %d\n", account.getBalance()); companyThread.start(); bankThread.start(); try { companyThread.join(); bankThread.join(); System.out.printf("Account: Final Balance: %d\n", account.getBalance()); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.atomic; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*; public class ConcurrentHashMapExample { public static class TestExecutor extends ThreadPoolExecutor { private ConcurrentHashMap<String, Date> startTimes; public TestExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); this.startTimes = new ConcurrentHashMap<>(); } @Override public void shutdown() { super.shutdown(); } @Override public List<Runnable> shutdownNow() { return super.shutdownNow(); } @Override protected void beforeExecute(Thread t, Runnable r) { System.out.printf("Test executor: A task is beginning: %s : %s\n", t.getName(), r.hashCode()); startTimes.put(String.valueOf(r.hashCode()), new Date()); } @Override protected void afterExecute(Runnable r, Throwable t) { Future<?> result = (Future<?>) r; try { System.out.printf("---------------------------------------\n"); System.out.printf("Test executor: A task is finishing.\n"); System.out.printf("Test executor: Result %s\n", result.get()); Date startDate = startTimes.remove(String.valueOf(r.hashCode())); Date finishDate = new Date(); long diff = finishDate.getTime() - startDate.getTime(); System.out.printf("Test executor: Duration: %d\n", diff); System.out.printf("***************************************\n"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } public static class SleepTwoSecondsTask implements Callable<String> { @Override public String call() throws Exception { TimeUnit.SECONDS.sleep(2); return new Date().toString(); } } public static void main(String[] args) { TestExecutor myExecutor = new TestExecutor(2, 4, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>()); List<Future<String>> results = new ArrayList<>(); for (int i = 0; i < 10; i++) { SleepTwoSecondsTask task = new SleepTwoSecondsTask(); Future<String> result = myExecutor.submit(task); results.add(result); } for (int i = 0; i < 5; i++) { try { String result = results.get(i).get(); System.out.printf("Main: Result for task %d : %s\n", i, result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } myExecutor.shutdown(); for (int i = 5; i < 10; i++) { try { String result = results.get(i).get(); System.out.printf("Main: Result for Task %d : %s\n", i, result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } try { myExecutor.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main: End of the program."); } }
package com.atomic; import java.util.concurrent.*; public class ForkJoinPoolWithThreadFactory { public static class WorkerThread extends ForkJoinWorkerThread { private static ThreadLocal<Integer> taskCounter = new ThreadLocal<>(); protected WorkerThread(ForkJoinPool pool) { super(pool); } @Override protected void onStart() { super.onStart(); System.out.printf("WorkerThread %d: Initializing task counter.\n", getId()); taskCounter.set(0); } @Override protected void onTermination(Throwable throwable) { System.out.printf("WorkerThread %d: %d\n", getId(), taskCounter.get()); super.onTermination(throwable); } public void addTask() { int counter = taskCounter.get(); counter++; taskCounter.set(counter); } } public static class MyWorkerThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory { @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { return new WorkerThread(pool); } } public static class MyRecursiveTask extends RecursiveTask<Integer> { private int[] array; private int start, end; public MyRecursiveTask(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override protected Integer compute() { Integer ret; WorkerThread thread = (WorkerThread) Thread.currentThread(); thread.addTask(); if (end - start < 2) { ret = array[start]; } else { int mid = (start + end) / 2; MyRecursiveTask task1 = new MyRecursiveTask(array, start, mid); MyRecursiveTask task2 = new MyRecursiveTask(array, mid, end); invokeAll(task1, task2); ret = addResults(task1, task2); } return ret; } private Integer addResults(MyRecursiveTask task1, MyRecursiveTask task2) { int value; try { value = task1.get() + task2.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); value = 0; } try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } return value; } } public static void main(String[] args) throws Exception { MyWorkerThreadFactory factory = new MyWorkerThreadFactory(); ForkJoinPool pool = new ForkJoinPool(4, factory, null, false); int[] array = new int[1000]; for (int i = 0; i < array.length; i++) { array[i] = 1; } MyRecursiveTask task = new MyRecursiveTask(array, 0, array.length); pool.execute(task); task.join(); pool.shutdown(); pool.awaitTermination(1, TimeUnit.DAYS); System.out.printf("Main: Result: %d\n", task.get()); System.out.printf("Main: End\n"); } }
package com.atomic; import java.util.Date; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class ThreadFactoryExample { public static class TestThread extends Thread { private Date createDate; private Date startDate; private Date finishDate; public TestThread(Runnable target, String name) { super(target, name); setCreateDate(); } @Override public void run() { setStartDate(); super.run(); setFinishDate(); } public void setCreateDate() { createDate = new Date(); } public void setStartDate() { startDate = new Date(); } public void setFinishDate() { finishDate = new Date(); } public long getExecutionTime() { return finishDate.getTime() - startDate.getTime(); } @Override public String toString() { return getName() + ": Create Date: " + createDate + ", Running Time: " + getExecutionTime() + " Milliseconds."; } } public static class TestThreadFactory implements ThreadFactory { private int counter; private String prefix; public TestThreadFactory(String prefix) { this.prefix = prefix; counter = 1; } @Override public Thread newThread(Runnable r) { TestThread myThread = new TestThread(r, prefix + "-" + counter); counter++; return myThread; } } public static class MyTask implements Runnable { @Override public void run() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { TestThreadFactory myThreadFactory = new TestThreadFactory("TestThreadFactory"); MyTask task = new MyTask(); Thread thread = myThreadFactory.newThread(task); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Thread information.\n"); System.out.printf("%s\n", thread); System.out.printf("Main: End of program.\n"); } }
package com.blockingqueue; import java.util.Map; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; public class ConcurrentSkipListMapExample { public static class Contact { private String name; private String phone; public String getName() { return name; } public String getPhone() { return phone; } public Contact(String name, String phone) { this.name = name; this.phone = phone; } } public static class Task implements Runnable { private ConcurrentSkipListMap<String, Contact> map; private String id; public Task(ConcurrentSkipListMap<String, Contact> map, String id) { this.map = map; this.id = id; } @Override public void run() { for (int i = 0; i < 1000; i++) { Contact contact = new Contact(id, String.valueOf(i + 1000)); map.put(id + contact.getPhone(), contact); } } } public static void main(String[] args) { ConcurrentSkipListMap<String, Contact> map = new ConcurrentSkipListMap<>(); Thread[] threads = new Thread[25]; int counter = 0; for (char i = 'A'; i < 'Z'; i++) { Task task = new Task(map, String.valueOf(i)); threads[counter] = new Thread(task); threads[counter].start(); counter++; } for (int i = 0; i < 25; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.printf("Main: Size of the map: %d\n", map.size()); Map.Entry<String, Contact> element; Contact contact; element = map.firstEntry(); contact = element.getValue(); System.out.printf("Main: First Entry: %s: %s\n", contact.getName(), contact.getPhone()); element = map.lastEntry(); contact = element.getValue(); System.out.printf("Main: Last Entry: %s: %s\n", contact.getName(), contact.getPhone()); System.out.printf("Main: Submap from A1996 to B1002:\n"); ConcurrentNavigableMap<String, Contact> submap = map.subMap("A1996", "B1002"); do { element = submap.pollFirstEntry(); if (element != null) { contact = element.getValue(); System.out.printf("%s: %s\n", contact.getName(), contact.getPhone()); } } while (element != null); } }
package com.blockingqueue; import java.util.Date; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class LinkedBlockingQueueExample { public static class Client implements Runnable { private LinkedBlockingQueue<String> requestList; public Client(LinkedBlockingQueue<String> requestList) { this.requestList = requestList; } @Override public void run() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { try { requestList.put(String.valueOf(i) + ":" + String.valueOf(j)); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("Client: %s at %s.\n", String.valueOf(i) + ":" + String.valueOf(j), new Date()); } } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Client: End.\n"); } } public static void main(String[] args) throws Exception { LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(3); Client client = new Client(queue); Thread thread = new Thread(client); thread.start(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { String request = queue.take(); Thread.sleep(1000); System.out.printf("Main: Request: %s at %s. Size: %d\n", request, new Date(), queue.size()); } TimeUnit.MILLISECONDS.sleep(300); } System.out.printf("Main: End of the program.\n"); } }
package com.blockingqueue; import java.util.concurrent.PriorityBlockingQueue; public class PriorityBlockingQueueExample { public static class Event implements Comparable<Event> { private int thread; private int priority; public int getThread() { return thread; } public int getPriority() { return priority; } public Event(int thread, int priority) { this.thread = thread; this.priority = priority; } @Override public int compareTo(Event e) { if (this.priority > e.getPriority()) { return -1; } else if (this.priority < e.getPriority()) { return 1; } else { return 0; } } } public static class Task implements Runnable { private int id; private PriorityBlockingQueue<Event> queue; public Task(int id, PriorityBlockingQueue<Event> queue) { this.id = id; this.queue = queue; } @Override public void run() { for (int i = 0; i < 1000; i++) { Event event = new Event(id, i); queue.add(event); } } } public static void main(String[] args) { PriorityBlockingQueue<Event> queue = new PriorityBlockingQueue<>(); Thread[] taskThreads = new Thread[5]; for (int i = 0; i < taskThreads.length; i++) { Task task = new Task(i, queue); taskThreads[i] = new Thread(task); } for (Thread taskThread : taskThreads) { taskThread.start(); } for (Thread taskThread : taskThreads) { try { taskThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.printf("Main: Queue size: %d\n", queue.size()); for (int i = 0; i < taskThreads.length * 1000; i++) { Event event = queue.poll(); System.out.printf("Thread %s: Priority %d\n", event.getThread(), event.getPriority()); } System.out.printf("\nMain: Queue size: %d\n", queue.size()); System.out.println("Main: End of the program."); } }
package com.forkjoin; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; import java.util.concurrent.TimeUnit; public class ForkJoinPoolExample { public static class Product { private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } public static class ProductList { public List<Product> generateListOfProducts(int size) { List<Product> ret = new ArrayList<>(size); for (int i = 0; i < size; i++) { Product product = new Product(); product.setName("Product " + i); product.setPrice(10); ret.add(product); } return ret; } } public static class Task extends RecursiveAction { private static final long serialVersionUID = 1L; private List<Product> products; private int first; private int last; private double increment; public Task(List<Product> products, int first, int last, double increment) { this.products = products; this.first = first; this.last = last; this.increment = increment; } @Override protected void compute() { if (last - first < 10) { updatePricesInProduct(); } else { int middle = (last + first) / 2; System.out.printf("Task: Pending tasks: %s\n", getQueuedTaskCount()); Task task1 = new Task(products, first, middle + 1, increment); Task task2 = new Task(products, middle + 1, last, increment); invokeAll(task1, task2); } } private void updatePricesInProduct() { for (int i = first; i < last; i++) { Product product = products.get(i); product.setPrice(product.getPrice() * (1 + increment)); } } } public static void main(String[] args) { ProductList generator = new ProductList(); List<Product> products = generator.generateListOfProducts(10000); Task task = new Task(products, 0, products.size(), 0.20); ForkJoinPool pool = new ForkJoinPool(); pool.execute(task); do { System.out.printf("====Main: Thread count: %d\n", pool.getActiveThreadCount()); System.out.printf("====Main: Thread steal: %d\n", pool.getStealCount()); System.out.printf("====Main: Parallelism: %d\n", pool.getParallelism()); try { TimeUnit.MILLISECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } while (!task.isDone()); pool.shutdown(); if (task.isCompletedNormally()) { System.out.printf("Main: The process has completed normally.\n"); } for (Product product : products) { if (product.getPrice() != 12) { System.out.printf("!!!!!Product %s: %f\n", product.getName(), product.getPrice()); } } System.out.printf("Main: End of program.\n"); } }
package com.lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PrinterAndJobsUsingReEntrantLock { public static class PrinterQueue { private final Lock queueLock = new ReentrantLock(); public void printJob(Object document) { queueLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println(Thread.currentThread().getName() + ": PrintQueue: Printing a Job during " + duration / 1000 + " seconds."); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { queueLock.unlock(); } } } public static class Job implements Runnable { private PrinterQueue printQueue; public Job(PrinterQueue printQueue) { this.printQueue = printQueue; } @Override public void run() { System.out.printf("%s: Going to print a document\n", Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); } } public static void main(String[] args) { PrinterQueue printQueue = new PrinterQueue(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new Job(printQueue), "Thread " + i); } for (int i = 0; i < 10; i++) { threads[i].start(); } } }
package com.phaser; import java.util.concurrent.Semaphore; public class PrinterAndJobsUsingSemaphore { public static class PrinterQueue { private final Semaphore semaphore; public PrinterQueue() { this.semaphore = new Semaphore(1); } public void printJob(Object document) { try { semaphore.acquire(); long duration = (long) (Math.random() * 10); System.out.printf("%s: PrinterQueue: Printing a job during %d seconds\n", Thread.currentThread().getName(), duration); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } } public static class Job implements Runnable { private PrinterQueue printQueue; public Job(PrinterQueue printQueue) { this.printQueue = printQueue; } @Override public void run() { System.out.printf("%s: Going to print a job\n", Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); } } public static void main(String[] args) { PrinterQueue printQueue = new PrinterQueue(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new Job(printQueue), "Thread " + i); } for (int i = 0; i < 10; i++) { threads[i].start(); } } }
package com.lock; import java.util.Date; import java.util.LinkedList; import java.util.List; public class ProducerConsumerUsingSynchronized { public static class DataStorage { private int maxSize; private List<Date> storage; public DataStorage() { maxSize = 10; storage = new LinkedList<>(); } public synchronized void set() { while (storage.size() == maxSize) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } storage.add(new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("Set: %d\n", storage.size()); notifyAll(); } public synchronized void get() { while (storage.size() == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("Get: %d: %s\n", storage.size(), ((LinkedList<?>) storage).poll()); notifyAll(); } } public static class Producer implements Runnable { public Producer(DataStorage eventStorage) { this.eventStorage = eventStorage; } private DataStorage eventStorage; @Override public void run() { for (int i = 0; i < 100; i++) { eventStorage.set(); } } } public static class Consumer implements Runnable { private DataStorage eventStorage; public Consumer(DataStorage eventStorage) { this.eventStorage = eventStorage; } @Override public void run() { for (int i = 0; i < 100; i++) { eventStorage.get(); } } } public static void main(String[] args) { DataStorage eventStorage = new DataStorage(); Producer producer = new Producer(eventStorage); Thread thread1 = new Thread(producer); Consumer consumer = new Consumer(eventStorage); Thread thread2 = new Thread(consumer); thread1.start(); thread2.start(); } }
package com.lock; public class SynchronizedMethodExample { public static class Account { public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } private double balance; public synchronized void addAmount(double amount) { double tmp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } tmp += amount; balance = tmp; } public synchronized void subtractAmount(double amount) { double tmp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } tmp -= amount; balance = tmp; } } public static class Bank implements Runnable { private Account account; public Bank(Account account) { this.account = account; } @Override public void run() { for (int i = 0; i < 100; i++) { account.subtractAmount(1000); } } } public static class Company implements Runnable { private Account account; public Company(Account account) { this.account = account; } @Override public void run() { for (int i = 0; i < 100; i++) { account.addAmount(1000); } } } public static void main(String[] args) { Account account = new Account(); account.setBalance(1000); Company company = new Company(account); Thread companyThread = new Thread(company); Bank bank = new Bank(account); Thread bankThread = new Thread(bank); System.out.printf("Account: Initial balance: %f\n", account.getBalance()); companyThread.start(); bankThread.start(); try { companyThread.join(); bankThread.join(); System.out.printf("Account: Final balance: %f\n", account.getBalance()); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.phaser; import java.util.Date; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; public class ImplementExamUsingPhaser { public static class TestPhaser extends Phaser { @Override protected boolean onAdvance(int phase, int registeredParties) { switch (phase) { case 0: return studentsArrived(); case 1: return finishFirstExercise(); case 2: return finishSecondExercise(); case 3: return finishExam(); default: return true; } } private boolean studentsArrived() { System.out.printf("Phaser: The exam is going to start. The students are ready.\n"); System.out.printf("Phaser: We have %d students.\n", getRegisteredParties()); return false; } private boolean finishFirstExercise() { System.out.printf("Phaser: All the students have finished the 1st exercise.\n"); System.out.printf("Phaser: It's time for the 2nd one.\n"); return false; } private boolean finishSecondExercise() { System.out.printf("Phaser: All the students have finished the 2nd exercise.\n"); System.out.printf("Phaser: It's time for the 3rd one.\n"); return false; } private boolean finishExam() { System.out.printf("Phaser: All the students have finished the 3rd exercise.\n"); System.out.printf("Phaser: Thank you for your time.\n"); return true; } } public static class Student implements Runnable { private Phaser phaser; public Student(Phaser phaser) { this.phaser = phaser; } @Override public void run() { System.out.printf("%s has arrived to do the exam. %s\n", Thread.currentThread().getName(), new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s is going to do the 1st exercise. %s\n", Thread.currentThread().getName(), new Date()); doExercise1(); System.out.printf("%s has done the 1st exercise. %s\n", Thread.currentThread().getName(), new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s is going to do the 2nd exercise. %s\n", Thread.currentThread().getName(), new Date()); doExercise2(); System.out.printf("%s has done the 2nd exercise. %s\n", Thread.currentThread().getName(), new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s is going to do the 3rd exercise. %s\n", Thread.currentThread().getName(), new Date()); doExercise3(); System.out.printf("%s has done the 3rd exercise. %s\n", Thread.currentThread().getName(), new Date()); phaser.arriveAndAwaitAdvance(); } private void doExercise1() { try { long duration = (long) (Math.random() * 10); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } } private void doExercise2() { try { long duration = (long) (Math.random() * 10); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } } private void doExercise3() { try { long duration = (long) (Math.random() * 10); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { TestPhaser myPhaser = new TestPhaser(); Student[] students = new Student[5]; for (int i = 0; i < students.length; i++) { students[i] = new Student(myPhaser); myPhaser.register(); } Thread[] threads = new Thread[students.length]; for (int i = 0; i < students.length; i++) { threads[i] = new Thread(students[i], "Student " + i); threads[i].start(); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.printf("Main: The phaser has finished: %s.\n", myPhaser.isTerminated()); } }
package com.phaser; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class ImplementMeetingRoomUsingCountDownLatch { public static class MeetinRoom implements Runnable { private final CountDownLatch controller; public MeetinRoom(int number) { this.controller = new CountDownLatch(number); } public void arrive(String name) { System.out.printf("%s has arrived.\n", name); controller.countDown(); System.out.printf("Meeting Room: Waiting for %d participants.\n", controller.getCount()); } @Override public void run() { System.out.printf("Meeting Room: Initialization: %d participants.\n", controller.getCount()); try { controller.await(); System.out.printf("Meeting Room: All the participants have arrived.\n"); System.out.printf("Meeting Room: Let's start...\n"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static class Participant implements Runnable { private MeetinRoom conference; private String name; public Participant(MeetinRoom conference, String name) { this.conference = conference; this.name = name; } @Override public void run() { long duration = (long) (Math.random() * 10); try { TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } conference.arrive(name); } } public static void main(String[] args) { MeetinRoom conference = new MeetinRoom(10); Thread conferenceThread = new Thread(conference); conferenceThread.start(); for (int i = 0; i < 10; i++) { Participant p = new Participant(conference, "Participant " + i); Thread t = new Thread(p); t.start(); } } }
package com.phaser; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Exchanger; public class ImplementProducerConsumerUsingExchanger { public static class Producer implements Runnable { private List<String> buffer; private final Exchanger<List<String>> exchanger; public Producer(List<String> buffer, Exchanger<List<String>> exchanger) { this.exchanger = exchanger; this.buffer = buffer; } @Override public void run() { int cycle = 1; for (int i = 0; i < 10; i++) { System.out.printf("Producer: Cycle %d\n", cycle); for (int j = 0; j < 10; j++) { String message = "Event " + (i * 10 + j); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("Producer: %s\n", message); buffer.add(message); } try { buffer = exchanger.exchange(buffer); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Producer: " + buffer.size()); cycle++; } } } public static class Consumer implements Runnable { private List<String> buffer; private final Exchanger<List<String>> exchanger; public Consumer(List<String> buffer, Exchanger<List<String>> exchanger) { this.buffer = buffer; this.exchanger = exchanger; } @Override public void run() { int cycle = 1; for (int i = 0; i < 10; i++) { System.out.printf("Consumer: Cycle %d\n", cycle); try { buffer = exchanger.exchange(buffer); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Consumer: " + buffer.size()); for (int j = 0; j < 10; j++) { String message = buffer.get(0); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Consumer: " + message); buffer.remove(0); } cycle++; } } } public static void main(String[] args) { List<String> buffer1 = new ArrayList<>(); List<String> buffer2 = new ArrayList<>(); Exchanger<List<String>> exchanger = new Exchanger<>(); Producer producer = new Producer(buffer1, exchanger); Consumer consumer = new Consumer(buffer2, exchanger); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } }
package com.pool; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class FixedThreadPoolExample { public static class UserTask implements Runnable { private Date initDate; private String name; public UserTask(String name) { this.initDate = new Date(); this.name = name; } @Override public void run() { System.out.printf("%s: Task %s: Created on: %s\n", Thread.currentThread().getName(), name, initDate); System.out.printf("%s: Task %s: Started on: %s\n", Thread.currentThread().getName(), name, new Date()); try { Long duration = (long) (Math.random() * 10); System.out.printf("%s: Task %s: Doing a task during %d seconds.\n", Thread.currentThread().getName(), name, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s: Task %s: Finished on: %s\n", Thread.currentThread().getName(), name, new Date()); } } public static class Server { private ThreadPoolExecutor executor; public Server() { this.executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5); } public void executeTask(UserTask task) { System.out.printf("Server: A new task has arrived.\n"); executor.execute(task); System.out.printf("Server: Poll size: %d\n", executor.getPoolSize()); System.out.printf("Server: Active count: %d\n", executor.getActiveCount()); System.out.printf("Server: Completed tasks: %d\n", executor.getCompletedTaskCount()); System.out.printf("Server: Task count: %d\n", executor.getTaskCount()); } public void endServer() { executor.shutdown(); } } public static void main(String[] args) { Server server = new Server(); for (int i = 0; i < 10; i++) { UserTask task = new UserTask("Task " + i); server.executeTask(task); } server.endServer(); } }
package com.pool; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class CachedThreadPoolExample { public static class UserTask implements Runnable { private Date initDate; private String name; public UserTask(String name) { this.initDate = new Date(); this.name = name; } @Override public void run() { System.out.printf("%s: User Task %s: Created on: %s\n", Thread.currentThread().getName(), name, initDate); System.out.printf("%s: User Task %s: Started on: %s\n", Thread.currentThread().getName(), name, new Date()); try { Long duration = (long) (Math.random() * 10); System.out.printf("%s: User Task %s: Doing a user task during %d seconds.\n", Thread.currentThread().getName(), name, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s: User Task %s: Finished on: %s\n", Thread.currentThread().getName(), name, new Date()); } } public static class Server { private ThreadPoolExecutor executor; public Server() { this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); } public void executeTask(UserTask task) { System.out.printf("Server: A new user task has arrived.\n"); executor.execute(task); System.out.printf("Server: Poll size: %d\n", executor.getPoolSize()); System.out.printf("Server: Active user task count: %d\n", executor.getActiveCount()); System.out.printf("Server: Completed user tasks: %d\n", executor.getCompletedTaskCount()); } public void endServer() { executor.shutdown(); } } public static void main(String[] args) { Server server = new Server(); for (int i = 0; i < 10; i++) { UserTask task = new UserTask("Task " + i); server.executeTask(task); } server.endServer(); } }
package com.pool; import java.util.concurrent.*; public class CancelTaskInExecutorService { public static class Task implements Callable<String> { @Override public String call() throws Exception { while (true) { System.out.println("Task: Test"); Thread.sleep(100); } } } public static void main(String[] args) { ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); Task task = new Task(); System.out.printf("Main: Executing the task\n"); Future<String> stringFuture = executor.submit(task); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Canceling the task\n"); stringFuture.cancel(true); System.out.printf("Main: Cancelled: %s\n", stringFuture.isCancelled()); System.out.printf("Main: Done: %s\n", stringFuture.isDone()); executor.shutdown(); System.out.printf("Main: The executor has finished.\n"); } }
package com.pool; import java.util.concurrent.*; public class CompletionServiceExample { public static class ReportGenerator implements Callable<String> { private String sender; private String title; public ReportGenerator(String sender, String title) { this.sender = sender; this.title = title; } @Override public String call() throws Exception { try { long duration = (long) (Math.random() * 10); System.out.printf("%s_%s: ReportGenerator: Generating " + "a report during %d seconds\n", this.sender, this.title, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } return sender + ": " + title; } } public static class ReportRequest implements Runnable { private String name; private CompletionService<String> service; public ReportRequest(String name, CompletionService<String> service) { this.name = name; this.service = service; } @Override public void run() { ReportGenerator reportGenerator = new ReportGenerator(name, "Report"); service.submit(reportGenerator); } } public static class ReportProcessor implements Runnable { private CompletionService<String> service; private boolean end; public ReportProcessor(CompletionService<String> service) { this.service = service; end = false; } @Override public void run() { while (!end) { try { Future<String> stringFuture = service.poll(20, TimeUnit.SECONDS); if (stringFuture != null) { String report = stringFuture.get(); System.out.printf("ReportReceiver: Report Received: %s\n", report); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } System.out.printf("ReportSender: End\n"); } public void setEnd(boolean end) { this.end = end; } } public static void main(String[] args) { ExecutorService executorService = (ExecutorService) Executors.newCachedThreadPool(); CompletionService<String> service = new ExecutorCompletionService<>(executorService); ReportRequest faceRequest = new ReportRequest("Offline", service); ReportRequest onlineRequest = new ReportRequest("Online", service); Thread faceThread = new Thread(faceRequest); Thread onlineThread = new Thread(onlineRequest); ReportProcessor processor = new ReportProcessor(service); Thread senderThread = new Thread(processor); System.out.printf("Main: Starting the Threads\n"); faceThread.start(); onlineThread.start(); senderThread.start(); try { System.out.printf("Main: Waiting for the report generators.\n"); faceThread.join(); onlineThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Shutting down the executor.\n"); executorService.shutdown(); try { executorService.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } processor.setEnd(true); System.out.println("Main: Ends"); } }
package com.pool; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; public class FactorialUsingCallable { public static class Factorial implements Callable<Integer> { private Integer number; public Factorial(Integer number) { this.number = number; } @Override public Integer call() throws Exception { int result = 1; if (number == 0 || number == 1) { result = 1; } else { for (int i = 2; i <= number; i++) { result *= i; TimeUnit.MILLISECONDS.sleep(20); } } System.out.printf(">>>%s: %d! = %d\n", Thread.currentThread().getName(), number, result); return result; } } public static void main(String[] args) { ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); List<Future<Integer>> resultList = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 10; i++) { Integer number = random.nextInt(10); Factorial calculator = new Factorial(number); Future<Integer> result = executor.submit(calculator); resultList.add(result); } do { System.out.printf("Main: Number of Completed Tasks: %d\n", executor.getCompletedTaskCount()); for (int i = 0; i < resultList.size(); i++) { Future<Integer> result = resultList.get(i); System.out.printf("Main: Task %d: %s\n", i, result.isDone()); } try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } while (executor.getCompletedTaskCount() < resultList.size()); System.out.printf("------------------\n"); System.out.printf("Main: Results\n"); for (int i = 0; i < resultList.size(); i++) { Future<Integer> result = resultList.get(i); Integer number = null; try { number = result.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } System.out.printf("Main: Task %d: %d\n", i, number); } executor.shutdown(); } }
package com.pool; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class RejectedExecutionHandlerExample { public static class RejectedTaskController implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.printf(">>>RejectedTaskController: The task %s has been rejected.\n", r.toString()); System.out.printf(">>>RejectedTaskController: %s\n", executor.toString()); System.out.printf(">>>RejectedTaskController: Terminating: %s\n", executor.isTerminating()); System.out.printf(">>>RejectedTaskController: Terminated: %s\n", executor.isTerminated()); } } public static class Task implements Runnable { private String name; public Task(String name) { this.name = name; } @Override public void run() { System.out.println("Task " + name + ": Starting"); try { long duration = (long) (Math.random() * 10); System.out.printf("Task %s: ReportGenerator: Generating a report during" + " %d seconds.\n", name, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Task %s: Ending\n", name); } @Override public String toString() { return name; } } public static void main(String[] args) { RejectedTaskController controller = new RejectedTaskController(); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); executor.setRejectedExecutionHandler(controller); System.out.printf("Main: Starting.\n"); for (int i = 0; i < 3; i++) { Task task = new Task("Task " + i); executor.submit(task); } System.out.printf("Main: Shutting down the executor.\n"); executor.shutdown(); System.out.printf("Main: Sending another task.\n"); Task task = new Task("RejectedTask"); executor.submit(task); System.out.print("Main: End\n"); } }
package com.pool; import java.util.Date; import java.util.concurrent.*; public class ScheduledExecutorServiceExample { public static class Task implements Runnable { private String name; public Task(String name) { this.name = name; } @Override public void run() { System.out.printf("%s: Starting at: %s\n", name, new Date()); } } public static void main(String[] args) { ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); System.out.printf("Main: Starting at: %s\n", new Date()); Task task = new Task("Task"); ScheduledFuture<?> scheduledFuture = executorService.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS); for (int i = 0; i < 10; i++) { System.out.printf("Main: Delay: %d\n", scheduledFuture.getDelay(TimeUnit.MILLISECONDS)); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } executorService.shutdown(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Finished at: %s\n", new Date()); } }
package com.pool; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ScheduledThreadPoolExecutorExample { public static class UserTask implements Callable<String> { private String userName; public UserTask(String name) { this.userName = name; } @Override public String call() throws Exception { System.out.printf("%s: String at: %s\n", userName, new Date()); return "Hello world!"; } } public static void main(String[] args) { ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); System.out.printf("Main: Starting at: %s\n", new Date()); for (int i = 0; i < 5; i++) { UserTask task = new UserTask("User Task " + i); executor.schedule(task, i + 1, TimeUnit.SECONDS); } executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Ends at: %s\n", new Date()); } }
package com.thread; import java.util.Date; import java.util.concurrent.TimeUnit; public class DisplaySystemClockUsingThread { public static class FileClock implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.printf("%s\n", new Date()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.printf("The FileClock has been interrupted."); } } } } public static void main(String[] args) { FileClock fileClock = new FileClock(); Thread thread = new Thread(fileClock); thread.start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); } }
package com.thread; public class ImplementCalculatorUsingThread { public static class Calculator implements Runnable { private int number; public Calculator(int number) { this.number = number; } @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("%s : %d * %d = %d\n", Thread.currentThread().getName(), number, i, number * i); } } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Calculator calculator = new Calculator(i); Thread thread = new Thread(calculator); thread.start(); } } }
package com.thread; import java.io.File; import java.util.concurrent.TimeUnit; public class ImplementFileSearchUsingThread { public static class FileSearch implements Runnable { private String initPath; private String fileName; public FileSearch(String initPath, String fileName) { this.initPath = initPath; this.fileName = fileName; } @Override public void run() { File file = new File(initPath); if (file.isDirectory()) { try { directoryProcess(file); } catch (InterruptedException e) { System.out.printf("%s: The search has been interrupted", Thread.currentThread().getName()); } } } private void directoryProcess(File file) throws InterruptedException { File[] files = file.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) directoryProcess(f); else fileProcess(f); } } if (Thread.interrupted()) throw new InterruptedException(); } private void fileProcess(File file) throws InterruptedException { if (file.getName().equals(fileName)) { System.out.printf("%s : %s\n", Thread.currentThread().getName(), file.getAbsolutePath()); } if (Thread.interrupted()) { throw new InterruptedException(); } } } public static void main(String[] args) { FileSearch fileSearch = new FileSearch("C:\\Users\\HP\\JAVA_workspace\\Concurrency1\\", "test"); Thread thread = new Thread(fileSearch); thread.start(); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); } }
package com.thread; public class PrimeNumberGeneratorUsingThread { public static class PrimeGenerator extends Thread { @Override public void run() { long number = 1L; while (true) { if (isPrime(number)) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.printf("Number %d is Prime\n", number); } if (isInterrupted()) { System.out.printf("Interrupted"); return; } number++; } } private boolean isPrime(long number) { if (number < 2) return false; for (int i = 2; i < number; i++) { if (number % i == 0) { return false; } } return true; } } public static void main(String[] args) { Thread task = new PrimeGenerator(); task.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } task.interrupt(); } }
package com.thread; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class ThreadFactoryExample { public static class MyThreadFactory implements ThreadFactory { private int counter; private String name; private List<String> stats; public MyThreadFactory(String name) { this.counter = 0; this.name = name; stats = new ArrayList<>(); } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, name + "-Thread_" + counter); counter++; stats.add(String.format("Created thread %d with name %s on %s", t.getId(), t.getName(), new Date())); return t; } public String getStats() { StringBuffer buffer = new StringBuffer(); for (String stat : stats) { buffer.append(stat); buffer.append("\n"); } return buffer.toString(); } } public static class Task implements Runnable { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { MyThreadFactory factory = new MyThreadFactory("MyThreadFactory"); Task task = new Task(); Thread thread; System.out.printf("Starting the threads\n"); for (int i = 0; i < 10; i++) { thread = factory.newThread(task); thread.start(); } System.out.printf("Factory stats:\n"); System.out.printf("%s\n", factory.getStats()); } }
package com.thread; public class UncaughtExceptionHandlerExample { public static class ExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.printf("An exception has been captured.\n"); System.out.printf("Thread: %s\n", t.getId()); System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage()); System.out.printf("Stack Trace: \n"); e.printStackTrace(System.out); System.out.printf("Thread status: %s\n", t.getState()); } } public static class Task implements Runnable { @Override public void run() { int n = Integer.parseInt("TT"); } } public static void main(String[] args) { Thread thread = new Thread(new Task()); thread.setUncaughtExceptionHandler(new ExceptionHandler()); thread.start(); } }
OPERATORS
package com.basics; import java.util.Scanner; public class AddTwoNumbersWithoutOper { public static void main(String[] arg) { int x, y; Scanner in = new Scanner(System.in); System.out.print("Input first number: "); x = in.nextInt(); System.out.print("Input second number: "); y = in.nextInt(); while (y != 0) { int carry = x & y; x = x ^ y; y = carry << 1; } System.out.print("Sum: " + x); System.out.print("\n"); } }
package com.basics; public class AsciiCharToGivenInt { public static void main(String[] String) { int chr = 'G'; System.out.println("The ASCII value of G is :" + chr); } }
package com.basics; public class DivideByThree { public static void main(String args[]) { System.out.println("\nDivided by 3: "); for (int i = 1; i < 100; i++) { if (i % 3 == 0) System.out.print(i + ", "); } System.out.println("\n\nDivided by 5: "); for (int i = 1; i < 100; i++) { if (i % 5 == 0) System.out.print(i + ", "); } System.out.println("\n\nDivided by 3 & 5: "); for (int i = 1; i < 100; i++) { if (i % 3 == 0 && i % 5 == 0) System.out.print(i + ", "); } System.out.println("\n"); } }
package com.basics; public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { System.out.printf("\n%d: fizz buzz", i); } else if (i % 5 == 0) { System.out.printf("\n%d: buzz", i); } else if (i % 3 == 0) { System.out.printf("\n%d: fizz", i); } } System.out.printf("\n"); } }
package com.basics; import java.util.Scanner; public class PrintDiamond { public static void main(String[] args) { int i, j, rows; System.out.print("number of rows : "); Scanner in = new Scanner(System.in); rows = in.nextInt(); for (i = 0; i <= rows; i++) { for (j = 1; j <= rows - i; j++) System.out.print(" "); for (j = 1; j <= 2 * i - 1; j++) System.out.print("*"); System.out.print("\n"); } for (i = rows - 1; i >= 1; i--) { for (j = 1; j <= rows - i; j++) System.out.print(" "); for (j = 1; j <= 2 * i - 1; j++) System.out.print("*"); System.out.print("\n"); } } }
package com.basics; import java.util.Scanner; public class PrintPascal { public static void main(String[] args) { int row, c = 1, k, i, j; System.out.print("number of rows: "); Scanner in = new Scanner(System.in); row = in.nextInt(); for (i = 0; i < row; i++) { for (k = 1; k <= row - i; k++) System.out.print(" "); for (j = 0; j <= i; j++) { if (j == 0 || i == 0) c = 1; else c = c * (i - j + 1) / j; System.out.print(" " + c); } System.out.print("\n"); } } }
package com.basics; import java.util.Scanner; public class PrintPyramid { public static void main(String[] args) { int i, j, n, k, l; System.out.print("number of rows : "); Scanner in = new Scanner(System.in); n = in.nextInt(); k = n + 4 - 1; for (i = 1; i <= n; i++) { for (l = k; l != 0; l--) { System.out.print(" "); } for (j = 1; j <= i; j++) { System.out.print(i + " "); } System.out.println(); k--; } } }
package com.basics; import java.util.Scanner; public class RightAngle { public static void main(String[] args) { int i, j, n, k = 1; System.out.print("number of rows : "); Scanner in = new Scanner(System.in); n = in.nextInt(); for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) System.out.print(k++); System.out.println(""); } } }
Testing Hash Map using Equals and Hash Code Contract
Scenario 1-with equals and hashcode with 2 objects with same content
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; return true; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(7); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.get(p)+"--->"+m.get(p1)); } }
Scenario 2-with equals and hashcode with 2 objects with different content
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; return true; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(8); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.get(p)+"--->"+m.get(p1)); } }
Scenario 3-without equals with 2 objects
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; return result; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(8); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.get(p)+"--->"+m.get(p1)); } }
Scenario 4-without hashcode with 2 objects
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; return true; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(7); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.get(p)+"--->"+m.get(p1)); } }
Scenario 5-without equals and hashcode with 2 objects
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(8); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.get(p)+"--->"+m.get(p1)); } }
Scenario 6-Finding Hash Map size with equals and hashcode with 2 objects with same content
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; return true; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(7); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.size()); } }
Scenario 7-Finding Hash Map size without equals and hashcode with 2 objects with same content
package com.testing; import java.util.HashMap; class Person { int age; Person(int i) { this.age = i; } } public class TestingHashMap { public static void main(String[] args) { Person p = new Person(7); Person p1 = new Person(7); HashMap<Person, Integer> m = new HashMap<Person, Integer>(); m.put(p, 1); m.put(p1,2); System.out.println(m.size()); } }
SERIALIZATION
First Run the Serilization Exception class
Change the Serial Version ID in Employee class
Finally Run the Deserilization Exception Class
package com.serializable; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializationExample { public static void main(String args[]) throws IOException, ClassNotFoundException { Employee emp = new Employee(); // serialize emp.seteId(1); emp.seteName("thomas"); emp.setSal(1000); System.out.println("Serialization done."); FileOutputStream fos = new FileOutputStream("D:\\formula\\EXAMPLES\\emp1.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(emp); } }
package com.serializable; import java.io.Serializable; class Employee implements Serializable { private static final long serialVersionUID = 1L; String eName = "durga"; int eId = 7; int sal = 1000; public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public String geteName() { return eName; } public void seteName(String eName) { this.eName = eName; } public int geteId() { return eId; } public void seteId(int eId) { this.eId = eId; } }
package com.serializable; import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializationExample { public static void main(String args[]) { Employee emp = new Employee(); try { FileInputStream fis = new FileInputStream("D:\\formula\\EXAMPLES\\emp1.ser"); ObjectInputStream ois = new ObjectInputStream(fis); emp = (Employee) ois.readObject(); System.out.println(emp.eId); System.out.println(emp.eName); System.out.println(emp.sal); } catch (Exception e) { e.printStackTrace(); } } }
package com.serializable; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; class Parent { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Child extends Parent implements Serializable { Parent p = new Parent(); public void show() { p.setName("thomas"); System.out.println(p.getName()); } } public class NotSerializableExample { public static void main(String[] args) { Child child = new Child(); try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("D:\\formula\\EXAMPLES\\emp1.ser"));) { oos.writeObject(child); child.show(); } catch (IOException e) { e.printStackTrace(); } } }
package com.serializable; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; class Parent implements Serializable{ String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Child extends Parent { Parent p = new Parent(); public void show() { p.setName("thomas"); System.out.println(p.getName()); } } public class NotSerializableExample { public static void main(String[] args) { Child child = new Child(); try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("D:\\formula\\EXAMPLES\\emp1.ser"));) { oos.writeObject(child); child.show(); } catch (IOException e) { e.printStackTrace(); } } }
package com.serializable; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; class Parent{ String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Child { Parent p = new Parent(); public void show() { p.setName("thomas"); System.out.println(p.getName()); } } public class NotSerializableExample { public static void main(String[] args) { Child child = new Child(); try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("D:\\formula\\EXAMPLES\\emp1.ser"));) { oos.writeObject(child); child.show(); } catch (IOException e) { e.printStackTrace(); } } }
Values will not be serialized if you define variables with transient and it display default values while deserialization
Define Name variable with transient keyword
package com.serializable; import java.io.Serializable; class Employee implements Serializable { private static final long serialVersionUID = 1L; String eName; transient int eId; int sal; public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public String geteName() { return eName; } public void seteName(String eName) { this.eName = eName; } public int geteId() { return eId; } public void seteId(int eId) { this.eId = eId; } }
Serialize the Employee object
package com.serializable; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializationExample { public static void main(String args[]) throws IOException, ClassNotFoundException { Employee emp = new Employee(); // serialize emp.seteId(7); emp.seteName("thomas"); emp.setSal(1000); System.out.println("Serialization done."); FileOutputStream fos = new FileOutputStream("D:\\formula\\EXAMPLES\\emp1.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(emp); } }
Deserialize the Employee object
package com.serializable; import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializationExample { public static void main(String args[]) { Employee emp = new Employee(); try { FileInputStream fis = new FileInputStream("D:\\formula\\EXAMPLES\\emp1.ser"); ObjectInputStream ois = new ObjectInputStream(fis); emp = (Employee) ois.readObject(); System.out.println(emp.eId); System.out.println(emp.eName); System.out.println(emp.sal); } catch (Exception e) { e.printStackTrace(); } } }
We love music
We have created a fictional band website. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Name
Name
Name