├── .gitignore ├── .idea ├── .gitignore ├── misc.xml ├── modules.xml └── uiDesigner.xml ├── README.md ├── src ├── exception │ ├── throwss.java │ ├── throww.java │ ├── trycatch │ ├── tryCatch.java │ ├── throww │ ├── throwss │ └── exception ├── instanceoff │ ├── instanceof │ └── Instanceoff.java ├── threadd │ ├── ExtendThreadClass.java │ ├── UsingThreadString.java │ ├── ImplementRunnable.java │ └── thread ├── datastructure │ ├── map │ │ ├── Mapp.java │ │ └── map │ ├── arraylist │ │ ├── Arraylist.java │ │ └── arraylist │ ├── queue │ │ ├── Piriorityqueue.java │ │ ├── queuee │ │ ├── Queuee.java │ │ ├── dequeue │ │ ├── piriorutyqueue │ │ └── Dequeueee.java │ ├── hashset │ │ ├── Hashset.java │ │ └── hashset │ ├── list │ │ ├── list.java │ │ └── list │ ├── arrays │ │ ├── Array.java │ │ └── arrays │ └── stack │ │ ├── stack │ │ └── Stackk.java ├── oop │ ├── polymorphism │ │ ├── override │ │ │ ├── override │ │ │ └── Override.java │ │ ├── overload │ │ │ ├── overload │ │ │ └── Overload.java │ │ └── polymorphism │ ├── interfaceexample │ │ ├── Interfacee.java │ │ ├── comporator │ │ ├── ComporatorExample.java │ │ └── interface │ ├── composition │ │ ├── composition │ │ └── Compisition.java │ ├── inheritance │ │ ├── Inheritancee.java │ │ └── inheritancee │ └── abstractclass │ │ ├── Abstractclass.java │ │ └── abstractclass ├── generic │ ├── Generic.java │ └── generics ├── big │ ├── Biginteger.java │ ├── Bigdecimal.java │ ├── bigdecimal │ └── biginteger ├── string │ ├── Stringbuffer.java │ ├── string.java │ ├── Stringbuilder.java │ ├── stringbuilder │ ├── stringbuffer │ └── string ├── keywords │ ├── This.java │ ├── Superr.java │ └── super,this ├── bitset │ ├── Bitset.java │ └── bitset ├── regex │ ├── regex.java │ └── regex ├── sorting │ ├── sorting │ └── Sorting.java ├── jdbc │ ├── jdbcc.java │ └── jdbc └── iterator │ ├── Iteratorr.java │ └── iterator └── javainterviewpreperation.iml /.gitignore: -------------------------------------------------------------------------------- 1 | # Project exclude paths 2 | /out/ -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # interview 2 | 3 | main concepts in java need to be known before any interview 4 | imp + description 5 | -------------------------------------------------------------------------------- /src/exception/throwss.java: -------------------------------------------------------------------------------- 1 | package exception; 2 | 3 | public class throwss { 4 | 5 | public static void main(String[] args)throws InterruptedException 6 | { 7 | Thread.sleep(10000); 8 | System.out.println("Hello Geeks"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/instanceoff/instanceof: -------------------------------------------------------------------------------- 1 | instanceoff is a keyword that is used for checking if a reference variable is containing a given type of object reference or not. 2 | Following is a Java program to show different behaviors of instanceoff. 3 | Henceforth it is known as a comparison operator where the instance is getting compared to type returning boolean true or false as in java we do not have 0 and 1 boolean return types. 4 | 5 | -------------------------------------------------------------------------------- /src/threadd/ExtendThreadClass.java: -------------------------------------------------------------------------------- 1 | package threadd; 2 | 3 | public class ExtendThreadClass extends Thread{ 4 | 5 | public void run() 6 | { 7 | System.out.println("Thread Started Running..."); 8 | } 9 | public static void main(String[] args) 10 | { 11 | ExtendThreadClass g1 = new ExtendThreadClass(); 12 | // invoking Thread 13 | g1.start(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/datastructure/map/Mapp.java: -------------------------------------------------------------------------------- 1 | package datastructure.map; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class Mapp { 7 | 8 | public static void main(String [] args){ 9 | 10 | Map hm = new HashMap(); 11 | 12 | hm.put("a" , 100); 13 | hm.put("b" , 101); 14 | 15 | //java 8 16 | hm.forEach((key, value) -> System.out.println(key + ": " + value)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/oop/polymorphism/override/override: -------------------------------------------------------------------------------- 1 | Type 2: Runtime polymorphism 2 | 3 | It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. 4 | 5 | -------------------------------------------------------------------------------- /src/oop/polymorphism/overload/overload: -------------------------------------------------------------------------------- 1 | Type 1: Compile-time polymorphism 2 | 3 | It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. 4 | 5 | Method Overloading: When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in the number of arguments or/and a change in the type of arguments. 6 | 7 | -------------------------------------------------------------------------------- /javainterviewpreperation.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/threadd/UsingThreadString.java: -------------------------------------------------------------------------------- 1 | package threadd; 2 | 3 | public class UsingThreadString { 4 | 5 | public static void main(String args[]) 6 | { 7 | // Thread object created 8 | // and initiated with data 9 | Thread t = new Thread("Hello Geeks!"); 10 | 11 | // Thread gets started 12 | t.start(); 13 | 14 | // getting data of 15 | // Thread through String 16 | String s = t.getName(); 17 | System.out.println(s); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/exception/throww.java: -------------------------------------------------------------------------------- 1 | package exception; 2 | 3 | public class throww { 4 | 5 | static void checkAge(int age) { 6 | if (age < 18) { 7 | throw new ArithmeticException("Access denied - You must be at least 18 years old."); 8 | } 9 | else { 10 | System.out.println("Access granted - You are old enough!"); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | checkAge(15); // Set age to 15 (which is below 18...) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/threadd/ImplementRunnable.java: -------------------------------------------------------------------------------- 1 | package threadd; 2 | 3 | public class ImplementRunnable implements Runnable{ 4 | @Override 5 | public void run() { 6 | System.out.println( 7 | "Thread is Running Successfully"); 8 | } 9 | 10 | public static void main(String[] args) 11 | { 12 | ImplementRunnable g1 = new ImplementRunnable(); 13 | // initializing Thread Object 14 | Thread t1 15 | = new Thread(g1); 16 | t1.start(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/generic/Generic.java: -------------------------------------------------------------------------------- 1 | package generic; 2 | 3 | class Test{ 4 | T obj; 5 | 6 | public Test(T i) { 7 | this.obj = i; 8 | } 9 | 10 | public T getObject(){ 11 | return this.obj; 12 | } 13 | } 14 | 15 | public class Generic { 16 | 17 | public static void main(String [] args){ 18 | Test obj = new Test(15); 19 | System.out.println(obj.getObject()); 20 | 21 | 22 | Test obj2 = new Test("mai"); 23 | System.out.println(obj2.getObject()); 24 | } 25 | 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/exception/trycatch: -------------------------------------------------------------------------------- 1 | Java Exceptions 2 | When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. 3 | 4 | When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error). 5 | 6 | Java try and catch 7 | The try statement allows you to define a block of code to be tested for errors while it is being executed. 8 | 9 | The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. 10 | 11 | -------------------------------------------------------------------------------- /src/oop/interfaceexample/Interfacee.java: -------------------------------------------------------------------------------- 1 | package oop.interfaceexample; 2 | 3 | import java.io.*; 4 | 5 | // A simple interface 6 | interface In1 { 7 | 8 | // public, static and final 9 | final int a = 10; 10 | 11 | // public and abstract 12 | void display(); 13 | } 14 | public class Interfacee implements In1{ 15 | 16 | public void display(){ 17 | System.out.println("Geek"); 18 | } 19 | 20 | // Driver Code 21 | public static void main(String[] args) 22 | { 23 | Interfacee t = new Interfacee(); 24 | t.display(); 25 | System.out.println(a); 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/datastructure/arraylist/Arraylist.java: -------------------------------------------------------------------------------- 1 | package datastructure.arraylist; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Arraylist { 6 | 7 | public static void main(String []args){ 8 | 9 | int n = 5; 10 | ArrayList arrayList 11 | = new ArrayList(n); 12 | 13 | for(int i =0 ; i < n ; i++){ 14 | arrayList.add(i); 15 | } 16 | System.out.println(arrayList); 17 | 18 | arrayList.remove(3); 19 | 20 | for(int i =0 ; i pQueue = new PriorityQueue(); 10 | 11 | // Adding items to the pQueue using add() 12 | pQueue.add(10); 13 | pQueue.add(20); 14 | pQueue.add(15); 15 | 16 | // Printing the top element of PriorityQueue 17 | System.out.println(pQueue.peek()); 18 | 19 | // Printing the top element and removing it 20 | // from the PriorityQueue container 21 | System.out.println(pQueue.poll()); 22 | 23 | // Printing the top element again 24 | System.out.println(pQueue.peek()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/regex/regex.java: -------------------------------------------------------------------------------- 1 | package regex; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class regex { 7 | 8 | public static void main(String args[]) 9 | { 10 | 11 | // Creating a pattern to be searched 12 | Pattern pattern = Pattern.compile( 13 | "ge*", Pattern.CASE_INSENSITIVE); 14 | 15 | // Searching above pattern in "geeksforgeeks.org" 16 | Matcher m = pattern.matcher("GeeksforGeeks.org"); 17 | 18 | // Find th above string using find() method 19 | while (m.find()) 20 | 21 | // Printing the starting and ending indexes of 22 | // the pattern in text using class method 23 | // functionalities 24 | System.out.println("Pattern found from " 25 | + m.start() + " to " 26 | + (m.end() - 1)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/string/string.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | public class string { 4 | public static void main(String[] args) 5 | { 6 | // Declare String without using new operator 7 | String s = "GeeksforGeeks"; 8 | 9 | // Prints the String. 10 | System.out.println("String s = " + s); 11 | 12 | // Declare String using new operator 13 | String s1 = new String("GeeksforGeeks"); 14 | 15 | // Prints the String. 16 | System.out.println("String s1 = " + s1); 17 | 18 | //two refrence two the same string 19 | String s11 = "TAT"; 20 | String s2 = "TAT"; 21 | //two different strings 22 | String s3 = new String("TAT"); 23 | String s4 = new String("TAT"); 24 | System.out.println(s11); 25 | System.out.println(s2); 26 | System.out.println(s3); 27 | System.out.println(s4); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/datastructure/hashset/Hashset.java: -------------------------------------------------------------------------------- 1 | package datastructure.hashset; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | 6 | public class Hashset { 7 | 8 | public static void main(String[] args) 9 | { 10 | // Instantiate an object of HashSet 11 | HashSet set = new HashSet<>(); 12 | 13 | // create ArrayList list1 14 | ArrayList list1 = new ArrayList<>(); 15 | 16 | // create ArrayList list2 17 | ArrayList list2 = new ArrayList<>(); 18 | 19 | // Add elements using add method 20 | list1.add(1); 21 | list1.add(2); 22 | list2.add(1); 23 | list2.add(2); 24 | set.add(list1); 25 | set.add(list2); 26 | 27 | // print the set size to understand the 28 | // internal storage of ArrayList in Set 29 | System.out.println(set.size()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/datastructure/list/list.java: -------------------------------------------------------------------------------- 1 | package datastructure.list; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class list { 7 | public static void main(String[] args){ 8 | List li = new ArrayList(); 9 | 10 | li.add(0,1); 11 | li.add(1,2); 12 | 13 | System.out.println(li); 14 | 15 | List l2 = new ArrayList(); 16 | 17 | 18 | l2.add(1); 19 | l2.add(2); 20 | l2.add(3); 21 | 22 | // Will add list l2 from 1 index 23 | li.addAll(1, l2); 24 | 25 | System.out.println(li); 26 | 27 | 28 | li.remove(1); 29 | 30 | // Printing the updated List 1 31 | System.out.println(li); 32 | 33 | 34 | System.out.println(li.get(3)); 35 | 36 | // Replace 0th element with 5 37 | // in List 1 38 | li.set(0, 5); 39 | 40 | 41 | System.out.println(li); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/oop/polymorphism/polymorphism: -------------------------------------------------------------------------------- 1 | The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. 2 | 3 | Real-life Illustration: Polymorphism 4 | 5 | A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism. 6 | Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms. 7 | 8 | Types of polymorphism 9 | 10 | In Java polymorphism is mainly divided into two types: 11 | 12 | Compile-time Polymorphism 13 | Runtime Polymorphism 14 | 15 | -------------------------------------------------------------------------------- /src/datastructure/queue/queuee: -------------------------------------------------------------------------------- 1 | The Queue interface is present in java.util package and extends the Collection interface is used to hold the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with its use limited to inserting elements at the end of the list and deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out principle. 2 | 3 | Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is needed. 4 | 5 | Declaration: The Queue interface is declared as: 6 | 7 | public interface Queue extends Collection 8 | Creating Queue Objects: Since Queue is an interface, objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. 9 | 10 | -------------------------------------------------------------------------------- /src/oop/polymorphism/override/Override.java: -------------------------------------------------------------------------------- 1 | package oop.polymorphism.override; 2 | 3 | class Parent { 4 | 5 | // Method of parent class 6 | void Print() 7 | { 8 | 9 | // Print statement 10 | System.out.println("parent class"); 11 | } 12 | } 13 | 14 | // Class 2 15 | // Helper class 16 | class subclass1 extends Parent { 17 | 18 | // Method 19 | void Print() { System.out.println("subclass1"); } 20 | } 21 | 22 | // Class 3 23 | // Helper class 24 | class subclass2 extends Parent { 25 | 26 | // Method 27 | void Print() 28 | { 29 | 30 | // Print statement 31 | System.out.println("subclass2"); 32 | } 33 | } 34 | 35 | public class Override { 36 | 37 | public static void main(String[] args) 38 | { 39 | 40 | // Creating object of class 1 41 | Parent a; 42 | 43 | // Now we will be calling print methods 44 | // inside main() method 45 | 46 | a = new subclass1(); 47 | a.Print(); 48 | 49 | a = new subclass2(); 50 | a.Print(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/sorting/sorting: -------------------------------------------------------------------------------- 1 | Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use any kind of algorithms. It is as simple sorting with the help of linear and non-linear data structures present within java. So there is sorting done with the help of brute force in java with the help of loops and there are two in-built methods to sort in Java. 2 | 3 | Ways of sorting in Java 4 | 5 | Using loops 6 | Using sort() method of Arrays class 7 | Using sort method of Collections class 8 | Sorting on a subarray 9 | 10 | Note: 11 | 12 | Which sorting algorithm does Java use in sort()? 13 | Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort. 14 | Which order of sorting is done by default? 15 | It by default sorts in ascending order. 16 | How to sort array or list in descending order? 17 | It can be done with the help of Collections.reverseOrder(). 18 | -------------------------------------------------------------------------------- /src/bitset/bitset: -------------------------------------------------------------------------------- 1 | BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. 2 | 3 | Constructors: 4 | 5 | BitSet class Constructors 6 | / \ 7 | BitSet() BitSet(int no_Of_Bits) 8 | BitSet() : A no-argument constructor to create an empty BitSet object. 9 | 10 | BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of the BitSet class with an initial size of the integer argument representing the number of bits. 11 | 12 | Important Points : 13 | 14 | The size of the array is flexible and can grow to accommodate additional bit as needed. 15 | As it is an array, the index is zero-based and the bit values can be accessed only by non-negative integers as an index. 16 | The default value of the BitSet is boolean false with a representation as 0 (off). 17 | Calling the clear method makes the bit values set to false. 18 | BitSet uses about 1 bit per boolean value. 19 | To access a specific value in the BitSet, the get method is used with an integer argument as an index. 20 | What happens if the array index in bitset is set as Negative? 21 | 22 | The program will throw java.lang.NegativeArraySizeException 23 | -------------------------------------------------------------------------------- /src/datastructure/queue/Queuee.java: -------------------------------------------------------------------------------- 1 | package datastructure.queue; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class Queuee { 7 | 8 | public static void main(String[] args) 9 | { 10 | Queue q 11 | = new LinkedList<>(); 12 | 13 | // Adds elements {0, 1, 2, 3, 4} to 14 | // the queue 15 | for (int i = 0; i < 5; i++) 16 | q.add(i); 17 | 18 | // Display contents of the queue. 19 | System.out.println("Elements of queue " 20 | + q); 21 | 22 | // To remove the head of queue. 23 | int removedele = q.remove(); 24 | System.out.println("removed element-" 25 | + removedele); 26 | 27 | System.out.println(q); 28 | 29 | // To view the head of queue 30 | int head = q.peek(); 31 | System.out.println("head of queue-" 32 | + head); 33 | 34 | // Rest all methods of collection 35 | // interface like size and contains 36 | // can be used with this 37 | // implementation. 38 | int size = q.size(); 39 | System.out.println("Size of queue-" 40 | + size); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/big/Bigdecimal.java: -------------------------------------------------------------------------------- 1 | package big; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Bigdecimal { 6 | 7 | public static void main(String[] args) 8 | { 9 | // Create two new BigDecimals 10 | BigDecimal bd1 = 11 | new BigDecimal("124567890.0987654321"); 12 | BigDecimal bd2 = 13 | new BigDecimal("987654321.123456789"); 14 | 15 | // Addition of two BigDecimals 16 | bd1 = bd1.add(bd2); 17 | System.out.println("BigDecimal1 = " + bd1); 18 | 19 | // Multiplication of two BigDecimals 20 | bd1 = bd1.multiply(bd2); 21 | System.out.println("BigDecimal1 = " + bd1); 22 | 23 | // Subtraction of two BigDecimals 24 | bd1 = bd1.subtract(bd2); 25 | System.out.println("BigDecimal1 = " + bd1); 26 | 27 | // Division of two BigDecimals 28 | bd1 = bd1.divide(bd2); 29 | System.out.println("BigDecimal1 = " + bd1); 30 | 31 | // BigDecima1 raised to the power of 2 32 | bd1 = bd1.pow(2); 33 | System.out.println("BigDecimal1 = " + bd1); 34 | 35 | // Negate value of BigDecimal1 36 | bd1 = bd1.negate(); 37 | System.out.println("BigDecimal1 = " + bd1); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/datastructure/arrays/Array.java: -------------------------------------------------------------------------------- 1 | package datastructure.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Array { 6 | 7 | public static void main(String[] args){ 8 | 9 | //1d array 10 | 11 | int [] oneArray; 12 | oneArray = new int[] {1,2,3,4,5,6}; 13 | 14 | System.out.println("1d array"); 15 | for(int i =0 ; i al = new ArrayList(); 31 | al.add("Geeks For Geeks"); 32 | al.add("Friends"); 33 | al.add("Dear"); 34 | al.add("Is"); 35 | al.add("Superb"); 36 | Collections.sort(al); 37 | 38 | System.out.println(al); 39 | 40 | //subarray 41 | Arrays.sort(array, 1, 3); 42 | System.out.println(array); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/string/Stringbuilder.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | public class Stringbuilder { 4 | public static void main(String[] argv) throws Exception 5 | { 6 | // Create a StringBuilder object 7 | // using StringBuilder() constructor 8 | StringBuilder str = new StringBuilder(); 9 | 10 | str.append("GFG"); 11 | 12 | // print string 13 | System.out.println("String = " + str.toString()); 14 | 15 | // create a StringBuilder object 16 | // using StringBuilder(CharSequence) constructor 17 | StringBuilder str1 18 | = new StringBuilder("AAAABBBCCCC"); 19 | 20 | // print string 21 | System.out.println("String1 = " + str1.toString()); 22 | 23 | // create a StringBuilder object 24 | // using StringBuilder(capacity) constructor 25 | StringBuilder str2 = new StringBuilder(10); 26 | 27 | // print string 28 | System.out.println("String2 capacity = " 29 | + str2.capacity()); 30 | 31 | // create a StringBuilder object 32 | // using StringBuilder(String) constructor 33 | StringBuilder str3 34 | = new StringBuilder(str1.toString()); 35 | 36 | // print string 37 | System.out.println("String3 = " + str3.toString()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/exception/throww: -------------------------------------------------------------------------------- 1 | The throw statement allows you to create a custom error. 2 | 3 | The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc 4 | 5 | The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. 6 | 7 | Syntax: 8 | 9 | throw Instance 10 | Example: 11 | throw new ArithmeticException("/ by zero"); 12 | But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions. 13 | 14 | The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program. 15 | 16 | -------------------------------------------------------------------------------- /src/jdbc/jdbcc.java: -------------------------------------------------------------------------------- 1 | package jdbc; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.sql.Statement; 7 | 8 | public class jdbcc { 9 | public static void main(String args[]) 10 | throws SQLException, ClassNotFoundException 11 | { 12 | String driverClassName 13 | = "sun.jdbc.odbc.JdbcOdbcDriver"; 14 | String url = "jdbc:odbc:XE"; //database url 15 | String username = "scott"; //sql username 16 | String password = "tiger"; //sql password 17 | String query 18 | = "insert into students values(109, 'bhatt')"; 19 | 20 | // Load driver class 21 | Class.forName(driverClassName); 22 | 23 | // Obtain a connection 24 | Connection con = DriverManager.getConnection( 25 | url, username, password); 26 | 27 | // Obtain a statement 28 | Statement st = con.createStatement(); 29 | 30 | // Execute the query 31 | int count = st.executeUpdate(query); 32 | System.out.println( 33 | "number of rows affected by this query= " 34 | + count); 35 | 36 | // Closing the connection as per the 37 | // requirement with connection is completed 38 | con.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/oop/composition/composition: -------------------------------------------------------------------------------- 1 | The Composition is a way to design or implement the "has-a" relationship. Composition and Inheritance both are design techniques. The Inheritance is used to implement the "is-a" relationship. The "has-a" relationship is used to ensure the code reusability in our program. In Composition, we use an instance variable that refers to another object. 2 | 3 | The composition relationship of two objects is possible when one object contains another object, and that object is fully dependent on it. The contained object should not exist without the existence of its parent object. In a simple way, we can say it is a technique through which we can describe the reference between two or more classes. And for that, we use the instance variable, which should be created before it is used. 4 | 5 | Key Points 6 | The Composition represents a part-of relationship. 7 | Both entities are related to each other in the Composition. 8 | The Composition between two entities is done when an object contains a composed object, and the composed object cannot exist without another entity. For example, if a university HAS-A college-lists, then a college is a whole, and college-lists are parts of that university. 9 | Favor Composition over Inheritance. 10 | If a university is deleted, then all corresponding colleges for that university should be deleted. 11 | 12 | -------------------------------------------------------------------------------- /src/keywords/super,this: -------------------------------------------------------------------------------- 1 | In java, super keyword is used to access methods of the parent class while this is used to access methods of the current class. 2 | 3 | this keyword is a reserved keyword in java i.e, we can’t use it as an identifier. It is used to refer current class’s instance as well as static members. It can be used in various contexts as given below: 4 | 5 | to refer instance variable of current class 6 | to invoke or initiate current class constructor 7 | can be passed as an argument in the method call 8 | can be passed as argument in the constructor call 9 | can be used to return the current class instance 10 | 11 | super keyword 12 | super is a reserved keyword in java i.e, we can’t use it as an identifier. 13 | super is used to refer super-class’s instance as well as static members. 14 | super is also used to invoke super-class’s method or constructor. 15 | super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used. 16 | The most common use of super keyword is that it eliminates the confusion between the superclasses and subclasses that have methods with same name. 17 | super can be used in various contexts as given below: 18 | 19 | it can be used to refer immediate parent class instance variable 20 | it can be used to refer immediate parent class method 21 | it can be used to refer immediate parent class constructor. -------------------------------------------------------------------------------- /src/exception/throwss: -------------------------------------------------------------------------------- 1 | throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block. 2 | 3 | Syntax: 4 | 5 | type method_name(parameters) throws exception_list 6 | exception_list is a comma separated list of all the 7 | exceptions which a method might throw. 8 | In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: 9 | 10 | By using try catch 11 | By using throws keyword 12 | We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception. 13 | 14 | Important points to remember about throws keyword: 15 | 16 | throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless. 17 | throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program. 18 | By the help of throws keyword we can provide information to the caller of the method about the exception. 19 | -------------------------------------------------------------------------------- /src/datastructure/list/list: -------------------------------------------------------------------------------- 1 | The List interface in Java provides a way to store the ordered collection. 2 | It is a child interface of Collection. 3 | It is an ordered collection of objects in which duplicate values can be stored. 4 | Since List preserves the insertion order, it allows positional access and insertion of elements. 5 | 6 | The List interface is found in java.util package and inherits the Collection interface. 7 | It is a factory of ListIterator interface. 8 | Through the ListIterator, we can iterate the list in forward and backward directions. 9 | The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. 10 | ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5. 11 | 12 | Let us elaborate on creating objects or instances in a List class. 13 | Since List is an interface, objects cannot be created of the type list. 14 | We always need a class that implements this List in order to create an object. 15 | And also, after the introduction of Generics in Java 1.5, 16 | it is possible to restrict the type of object that can be stored in the List. 17 | Just like several other user-defined ‘interfaces’ implemented by user-defined ‘classes’, List is an ‘interface’, implemented by the ArrayList class, pre-defined in the java.util package. 18 | 19 | Syntax: This type of safelist can be defined as: 20 | 21 | List list = new ArrayList (); -------------------------------------------------------------------------------- /src/iterator/Iteratorr.java: -------------------------------------------------------------------------------- 1 | package iterator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | 6 | public class Iteratorr { 7 | 8 | public static void main(String[] args) 9 | { 10 | // Creating an ArrayList class object 11 | // Declaring object of integer type 12 | ArrayList al = new ArrayList(); 13 | 14 | // Iterating over the List 15 | for (int i = 0; i < 10; i++) 16 | al.add(i); 17 | 18 | // Printing the elements in the List 19 | System.out.println(al); 20 | 21 | // At the beginning itr(cursor) will point to 22 | // index just before the first element in al 23 | Iterator itr = al.iterator(); 24 | 25 | // Checking the next element where 26 | // condition holds true till there is single element 27 | // in the List using hasnext() method 28 | while (itr.hasNext()) { 29 | // Moving cursor to next element 30 | int i = itr.next(); 31 | 32 | // Getting elements one by one 33 | System.out.print(i + " "); 34 | 35 | // Removing odd elements 36 | if (i % 2 != 0) 37 | itr.remove(); 38 | } 39 | 40 | // Command for next line 41 | System.out.println(); 42 | 43 | // Printing the elements inside the object 44 | System.out.println(al); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/datastructure/queue/dequeue: -------------------------------------------------------------------------------- 1 | Deque interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports the addition or removal of elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/LIFO). Deque is the acronym for double-ended queue. 2 | 3 | Syntax: The deque interface is declared as: 4 | 5 | public interface Deque extends Queue 6 | Creating Deque Objects Since Deque is an interface, objects cannot be created of the type deque. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Deque. 7 | 8 | The class which implements the Deque interface is ArrayDeque. ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. Array deques have no capacity restrictions and they grow as necessary to support usage. They are not thread-safe which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads. ArrayDeque class is likely to be faster than Stack when used as a stack. ArrayDeque class is likely to be faster than LinkedList when used as a queue. 9 | 10 | -------------------------------------------------------------------------------- /src/big/bigdecimal: -------------------------------------------------------------------------------- 1 | The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit. 2 | A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale). 3 | 4 | Examples: 5 | 6 | Input : double a=0.03; 7 | double b=0.04; 8 | double c=b-a; 9 | System.out.println(c); 10 | Output :0.009999999999999998 11 | 12 | Input : BigDecimal _a = new BigDecimal("0.03"); 13 | BigDecimal _b = new BigDecimal("0.04"); 14 | BigDecimal _c = _b.subtract(_a); 15 | System.out.println(_c); 16 | Output :0.01 17 | 18 | Need Of BigDecimal 19 | 20 | The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and a exponent. 21 | Other primitive types(except boolean) are fixed-point numbers. Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 10^-19) This is the reason why we end up with 0.009999999999999998 as the result of 0.04-0.03 in the above example. 22 | But BigDecimal provides us with the exact answer. 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/datastructure/queue/piriorutyqueue: -------------------------------------------------------------------------------- 1 | A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. 2 | 3 | The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. 4 | 5 | The class implements Serializable, Iterable, Collection, Queue interfaces. 6 | 7 | A few important points on Priority Queue are as follows: 8 | 9 | PriorityQueue doesn’t permit null. 10 | We can’t create a PriorityQueue of Objects that are non-comparable 11 | PriorityQueue are unbound queues. 12 | The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for the least value, the head is one of those elements — ties are broken arbitrarily. 13 | Since PriorityQueue is not thread-safe, java provides PriorityBlockingQueue class that implements the BlockingQueue interface to use in a java multithreading environment. 14 | The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue. 15 | It provides O(log(n)) time for add and poll methods. 16 | It inherits methods from AbstractQueue, AbstractCollection, Collection, and Object class. 17 | -------------------------------------------------------------------------------- /src/datastructure/stack/stack: -------------------------------------------------------------------------------- 1 | Java Collection framework provides a Stack class that models and implements a Stack data structure. 2 | The class is based on the basic principle of last-in-first-out. 3 | In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. 4 | The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. 5 | The class can also be referred to as the subclass of Vector. 6 | 7 | All Implemented Interfaces: 8 | 9 | Serializable: It is a marker interface that classes must implement if they are to be serialized and deserialized. 10 | Cloneable: This is an interface in Java which needs to be implemented by a class to allow its objects to be cloned. 11 | Iterable: This interface represents a collection of objects which is iterable — meaning which can be iterated. 12 | Collection: A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. 13 | List: The List interface provides a way to store the ordered collection. It is a child interface of Collection. 14 | RandomAccess: This is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access. 15 | How to Create a Stack? 16 | In order to create a stack, we must import java.util.stack package and use the Stack() constructor of this class. The below example creates an empty Stack. 17 | 18 | Stack stack = new Stack(); 19 | 20 | -------------------------------------------------------------------------------- /src/oop/interfaceexample/comporator: -------------------------------------------------------------------------------- 1 | A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. 2 | 3 | Syntax: 4 | 5 | public int compare(Object obj1, Object obj2): 6 | 7 | Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name, address, DOB, etc, and we need to sort the array based on Roll no or name? 8 | 9 | 10 | Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No. and Name. 11 | 12 | Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. 13 | 14 | Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator. 15 | 16 | public void sort(List list, ComparatorClass c) 17 | 18 | Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for their sort. 19 | 20 | -------------------------------------------------------------------------------- /src/generic/generics: -------------------------------------------------------------------------------- 1 | Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity. 2 | 3 | Why Generics? 4 | The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature. We will discuss that type of safety feature in later examples. 5 | 6 | Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well. There are some fundamental differences between the two approaches to generic types. 7 | 8 | Types of Java Generics 9 | Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings. 10 | 11 | Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, ​are known as parameterized classes or parameterized types. 12 | 13 | -------------------------------------------------------------------------------- /src/datastructure/arraylist/arraylist: -------------------------------------------------------------------------------- 1 | ArrayList is a part of collection framework and is present in java.util package. 2 | It provides us with dynamic arrays in Java. 3 | Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. 4 | This class is found in java.util package. 5 | 6 | Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item: 7 | 8 | Creates a bigger-sized memory on heap memory (for example memory of double size). 9 | Copies the current memory elements to the new memory. 10 | New item is added now as there is bigger memory available now. 11 | Delete the old memory. 12 | Important Features: 13 | 14 | ArrayList inherits AbstractList class and implements the List interface. 15 | ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection. 16 | Java ArrayList allows us to randomly access the list. 17 | ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases. 18 | ArrayList in Java can be seen as a vector in C++. 19 | ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector. 20 | 21 | // Creating generic integer ArrayList 22 | ArrayList arrli = new ArrayList(); 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/datastructure/stack/Stackk.java: -------------------------------------------------------------------------------- 1 | package datastructure.stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class Stackk { 6 | 7 | // Pushing element on the top of the stack 8 | static void stack_push(Stack stack) 9 | { 10 | for(int i = 0; i < 5; i++) 11 | { 12 | stack.push(i); 13 | } 14 | } 15 | 16 | // Popping element from the top of the stack 17 | static void stack_pop(Stack stack) 18 | { 19 | System.out.println("Pop Operation:"); 20 | 21 | for(int i = 0; i < 5; i++) 22 | { 23 | Integer y = (Integer) stack.pop(); 24 | System.out.println(y); 25 | } 26 | } 27 | 28 | // Displaying element on the top of the stack 29 | static void stack_peek(Stack stack) 30 | { 31 | Integer element = (Integer) stack.peek(); 32 | System.out.println("Element on stack top: " + element); 33 | } 34 | 35 | // Searching element in the stack 36 | static void stack_search(Stack stack, int element) 37 | { 38 | Integer pos = (Integer) stack.search(element); 39 | 40 | if(pos == -1) 41 | System.out.println("Element not found"); 42 | else 43 | System.out.println("Element is found at position: " + pos); 44 | } 45 | 46 | 47 | public static void main (String[] args) 48 | { 49 | Stack stack = new Stack(); 50 | 51 | stack_push(stack); 52 | stack_pop(stack); 53 | stack_push(stack); 54 | stack_peek(stack); 55 | stack_search(stack, 2); 56 | stack_search(stack, 6); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/oop/composition/Compisition.java: -------------------------------------------------------------------------------- 1 | package oop.composition; 2 | 3 | 4 | import java.util.*; 5 | // class College 6 | class College { 7 | public String name; 8 | public String address; 9 | College(String name, String address) 10 | { 11 | this.name = name; 12 | this.address = address; 13 | } 14 | } 15 | // University has more than one college. 16 | class University { 17 | // reference to refer to list of college. 18 | private final List colleges; 19 | University(List colleges) 20 | { 21 | this.colleges = colleges; 22 | } 23 | // Getting total number of colleges 24 | public List getTotalCollegesInUniversity() 25 | { 26 | return colleges; 27 | } 28 | } 29 | 30 | public class Compisition { 31 | 32 | public static void main(String[] args) 33 | { 34 | // Creating the Objects of College class. 35 | College c1 36 | = new College("ABES Engineering College", "Ghaziabad"); 37 | College c2 38 | = new College("AKG Engineering College", "Ghaziabad"); 39 | College c3 = new College("ACN College of Engineering & Management Sudies", 40 | "Aligarh"); 41 | // Creating list which contains the no. of colleges. 42 | List college = new ArrayList(); 43 | college.add(c1); 44 | college.add(c2); 45 | college.add(c3); 46 | University university = new University(college); 47 | List colleges = university.getTotalCollegesInUniversity(); 48 | for (College cg : colleges) { 49 | System.out.println("Name : " + cg.name 50 | + " and " 51 | + " Address : " + cg.address); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/instanceoff/Instanceoff.java: -------------------------------------------------------------------------------- 1 | package instanceoff; 2 | 3 | // Class 1 4 | // Parent class 5 | class Parent { 6 | int value = 100; 7 | } 8 | 9 | // Class 2 10 | // Child class 11 | class Child extends Parent { 12 | 13 | int value = 10; 14 | } 15 | 16 | public class Instanceoff { 17 | 18 | public static void main(String[] args) 19 | { 20 | 21 | // Creating object of child class 22 | Child cobj = new Child(); 23 | 24 | // A simple case 25 | if (cobj instanceof Child) 26 | System.out.println("cobj is instance of Child"); 27 | else 28 | System.out.println( 29 | "cobj is NOT instance of Child"); 30 | 31 | // instanceof returning true for Parent class also 32 | if (cobj instanceof Parent) 33 | System.out.println( 34 | "cobj is instance of Parent"); 35 | else 36 | System.out.println( 37 | "cobj is NOT instance of Parent"); 38 | 39 | // instanceof returns true for all ancestors 40 | 41 | // Note : Object is ancestor of all classes in Java 42 | if (cobj instanceof Object) 43 | System.out.println( 44 | "cobj is instance of Object"); 45 | else 46 | System.out.println( 47 | "cobj is NOT instance of Object"); 48 | 49 | 50 | 51 | 52 | Parent cobj3 = new Child(); 53 | Parent par = cobj3; 54 | 55 | // Using instanceof to make sure that par 56 | // is a valid reference before typecasting 57 | if (par instanceof Child) 58 | { 59 | System.out.println("Value accessed through " + 60 | "parent reference with typecasting is " + 61 | ((Child)par).value); 62 | } 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/regex/regex: -------------------------------------------------------------------------------- 1 | Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package 2 | 3 | Pattern Class 4 | Matcher Class 5 | PatternSyntaxException Class 6 | MatchResult Interface 7 | 8 | Class 1: Pattern Class 9 | This class is a compilation of regular expressions that can be used to define various types of patterns, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returns a pattern after execution. 10 | 11 | Class 2: Matcher class 12 | This object is used to perform match operations for an input string in java, thus interpreting the previously explained patterns. This too defines no public constructors. This can be implemented by invoking a matcher() on any pattern object. 13 | 14 | Class 3: PatternSyntaxException Class 15 | This is an object of Regex which is used to indicate a syntax error in a regular expression pattern and is an unchecked exception. Following are the methods been there up in the PatternSyntaxException class as provided below in tabular format as follows. 16 | 17 | We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in Pattern class. 18 | Like above, we create a Matcher object using matcher() on objects of Pattern class. 19 | Pattern.matches() is also a static method that is used to check if given text as a whole matches pattern or not. 20 | find() is used to find multiple occurrences of patterns in the text. 21 | We can split a text based on a delimiter pattern using the split() method 22 | -------------------------------------------------------------------------------- /src/oop/inheritance/Inheritancee.java: -------------------------------------------------------------------------------- 1 | package oop.inheritance; 2 | 3 | class Bicycle { 4 | // the Bicycle class has two fields 5 | public int gear; 6 | public int speed; 7 | 8 | // the Bicycle class has one constructor 9 | public Bicycle(int gear, int speed) 10 | { 11 | this.gear = gear; 12 | this.speed = speed; 13 | } 14 | 15 | // the Bicycle class has three methods 16 | public void applyBrake(int decrement) 17 | { 18 | speed -= decrement; 19 | } 20 | 21 | public void speedUp(int increment) 22 | { 23 | speed += increment; 24 | } 25 | 26 | // toString() method to print info of Bicycle 27 | public String toString() 28 | { 29 | return ("No of gears are " + gear + "\n" 30 | + "speed of bicycle is " + speed); 31 | } 32 | } 33 | 34 | // derived class 35 | class MountainBike extends Bicycle { 36 | 37 | // the MountainBike subclass adds one more field 38 | public int seatHeight; 39 | 40 | // the MountainBike subclass has one constructor 41 | public MountainBike(int gear, int speed, 42 | int startHeight) 43 | { 44 | // invoking base-class(Bicycle) constructor 45 | super(gear, speed); 46 | seatHeight = startHeight; 47 | } 48 | 49 | // the MountainBike subclass adds one more method 50 | public void setHeight(int newValue) 51 | { 52 | seatHeight = newValue; 53 | } 54 | 55 | // overriding toString() method 56 | // of Bicycle to print more info 57 | @Override public String toString() 58 | { 59 | return (super.toString() + "\nseat height is " 60 | + seatHeight); 61 | } 62 | } 63 | 64 | public class Inheritancee { 65 | 66 | public static void main(String args[]) 67 | { 68 | 69 | MountainBike mb = new MountainBike(3, 100, 25); 70 | System.out.println(mb.toString()); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/string/stringbuilder: -------------------------------------------------------------------------------- 1 | StringBuilder in Java represents a mutable sequence of characters. 2 | Since the String Class in Java creates an immutable sequence of characters, 3 | the StringBuilder class provides an alternative to String Class, 4 | as it creates a mutable sequence of characters. 5 | The function of StringBuilder is very much similar to the StringBuffer class, 6 | as both of them provide an alternative to String Class by making a mutable sequence of characters. 7 | However, the StringBuilder class differs from the StringBuffer class on the basis of synchronization. 8 | The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. 9 | Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. String Builder is not thread-safe and high in performance compared to String buffer. 10 | 11 | java.lang.Object 12 | ↳ java.lang 13 | ↳ Class StringBuilder 14 | Syntax: 15 | 16 | public final class StringBuilder 17 | extends Object 18 | implements Serializable, CharSequence 19 | 20 | Constructors in Java StringBuilder Class 21 | StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters. 22 | StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. 23 | StringBuilder(CharSequence seq): Constructs a string builder that contains the same characters as the specified CharSequence. 24 | StringBuilder(String str): Constructs a string builder initialized to the contents of the specified string. 25 | 26 | -------------------------------------------------------------------------------- /src/datastructure/queue/Dequeueee.java: -------------------------------------------------------------------------------- 1 | package datastructure.queue; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | import java.util.LinkedList; 6 | 7 | public class Dequeueee { 8 | 9 | public static void main(String [] args){ 10 | 11 | Deque deque 12 | = new LinkedList(); 13 | 14 | // We can add elements to the queue 15 | // in various ways 16 | 17 | // Add at the last 18 | deque.add("Element 1 (Tail)"); 19 | 20 | // Add at the first 21 | deque.addFirst("Element 2 (Head)"); 22 | 23 | // Add at the last 24 | deque.addLast("Element 3 (Tail)"); 25 | 26 | // Add at the first 27 | deque.push("Element 4 (Head)"); 28 | 29 | // Add at the last 30 | deque.offer("Element 5 (Tail)"); 31 | 32 | // Add at the first 33 | deque.offerFirst("Element 6 (Head)"); 34 | 35 | System.out.println(deque + "\n"); 36 | 37 | // We can remove the first element 38 | // or the last element. 39 | deque.removeFirst(); 40 | deque.removeLast(); 41 | System.out.println("Deque after removing " 42 | + "first and last: " 43 | + deque); 44 | 45 | 46 | // Initializing an deque 47 | Deque de_que 48 | = new ArrayDeque(10); 49 | 50 | // add() method to insert 51 | de_que.add(10); 52 | de_que.add(20); 53 | de_que.add(30); 54 | de_que.add(40); 55 | de_que.add(50); 56 | 57 | System.out.println(de_que); 58 | 59 | // clear() method 60 | de_que.clear(); 61 | 62 | // addFirst() method to insert the 63 | // elements at the head 64 | de_que.addFirst(564); 65 | de_que.addFirst(291); 66 | 67 | // addLast() method to insert the 68 | // elements at the tail 69 | de_que.addLast(24); 70 | de_que.addLast(14); 71 | 72 | System.out.println(de_que); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/big/biginteger: -------------------------------------------------------------------------------- 1 | BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types. 2 | 3 | In this way, BigInteger class is very handy to use because of its large method library and it is also used a lot in competitive programming. 4 | Now below is given a list of simple statements in primitive arithmetic and its analogous statement in terms of BigInteger objects. 5 | 6 | Example: 7 | 8 | int a, b; 9 | BigInteger A, B; 10 | Initialization is as follows: 11 | 12 | a = 54; 13 | b = 23; 14 | A = BigInteger.valueOf(54); 15 | B = BigInteger.valueOf(37); 16 | And for Integers available as strings you can initialize them as follows: 17 | 18 | A = new BigInteger(“54”); 19 | B = new BigInteger(“123456789123456789”); 20 | Some constants are also defined in BigInteger class for ease of initialization as follows: 21 | 22 | A = BigInteger.ONE; 23 | // Other than this, available constant are BigInteger.ZERO 24 | // and BigInteger.TEN 25 | Mathematical operations are as follows: 26 | 27 | int c = a + b; 28 | BigInteger C = A.add(B); 29 | Other similar functions are subtract(), multiply(), divide(), remainder(), but all these functions take BigInteger as their argument so if we want this operation with integers or string convert them to BigInteger before passing them to functions as shown below: 30 | 31 | String str = “123456789”; 32 | BigInteger C = A.add(new BigInteger(str)); 33 | int val = 123456789; 34 | BigInteger C = A.add(BigInteger.valueOf(val)); 35 | Extraction of value from BigInteger is as follows: 36 | 37 | int x = A.intValue(); // value should be in limit of int x 38 | long y = A.longValue(); // value should be in limit of long y 39 | String z = A.toString(); 40 | Comparison 41 | 42 | if (a < b) {} // For primitive int 43 | if (A.compareTo(B) < 0) {} // For BigInteger 44 | Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values. For equality we can also use: 45 | 46 | if (A.equals(B)) {} // A is equal to B 47 | 48 | -------------------------------------------------------------------------------- /src/oop/abstractclass/Abstractclass.java: -------------------------------------------------------------------------------- 1 | package oop.abstractclass; 2 | 3 | abstract class Shape { 4 | String color; 5 | 6 | // these are abstract methods 7 | abstract double area(); 8 | public abstract String toString(); 9 | 10 | // abstract class can have the constructor 11 | public Shape(String color) 12 | { 13 | System.out.println("Shape constructor called"); 14 | this.color = color; 15 | } 16 | 17 | // this is a concrete method 18 | public String getColor() { return color; } 19 | } 20 | class Circle extends Shape { 21 | double radius; 22 | 23 | public Circle(String color, double radius) 24 | { 25 | 26 | // calling Shape constructor 27 | super(color); 28 | System.out.println("Circle constructor called"); 29 | this.radius = radius; 30 | } 31 | 32 | @Override double area() 33 | { 34 | return Math.PI * Math.pow(radius, 2); 35 | } 36 | 37 | @Override public String toString() 38 | { 39 | return "Circle color is " + super.getColor() 40 | + "and area is : " + area(); 41 | } 42 | } 43 | class Rectangle extends Shape { 44 | 45 | double length; 46 | double width; 47 | 48 | public Rectangle(String color, double length, 49 | double width) 50 | { 51 | // calling Shape constructor 52 | super(color); 53 | System.out.println("Rectangle constructor called"); 54 | this.length = length; 55 | this.width = width; 56 | } 57 | 58 | @Override double area() { return length * width; } 59 | 60 | @Override public String toString() 61 | { 62 | return "Rectangle color is " + super.getColor() 63 | + "and area is : " + area(); 64 | } 65 | } 66 | 67 | public class Abstractclass { 68 | 69 | public static void main(String[] args) 70 | { 71 | Shape s1 = new Circle("Red", 2.2); 72 | Shape s2 = new Rectangle("Yellow", 2, 4); 73 | 74 | System.out.println(s1.toString()); 75 | System.out.println(s2.toString()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/oop/abstractclass/abstractclass: -------------------------------------------------------------------------------- 1 | Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components. 2 | 3 | Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. 4 | 5 | Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is. 6 | 7 | In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces. 8 | 9 | Abstract classes and Abstract methods : 10 | 11 | An abstract class is a class that is declared with an abstract keyword. 12 | An abstract method is a method that is declared without implementation. 13 | An abstract class may or may not have all abstract methods. Some of them can be concrete methods 14 | A method-defined abstract must always be redefined in the subclass, thus making overriding compulsory or making the subclass itself abstract. 15 | Any class that contains one or more abstract methods must also be declared with an abstract keyword. 16 | There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator. 17 | An abstract class can have parameterized constructors and the default constructor is always present in an abstract class. 18 | When to use abstract classes and abstract methods with an example 19 | 20 | There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. Sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. 21 | 22 | -------------------------------------------------------------------------------- /src/datastructure/arrays/arrays: -------------------------------------------------------------------------------- 1 | An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. 2 | 3 | In Java, all arrays are dynamically allocated. (discussed below) 4 | Arrays are stored in contagious memory [consecutive memory locations]. 5 | Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof. 6 | A Java array variable can also be declared like other variables with [] after the data type. 7 | The variables in the array are ordered, and each has an index beginning from 0. 8 | Java array can also be used as a static field, a local variable, or a method parameter. 9 | The size of an array must be specified by int or short value and not long. 10 | The direct superclass of an array type is Object. 11 | Every array type implements the interfaces Cloneable and java.io.Serializable. 12 | This storage of arrays helps us in randomly accessing the elements of an array [Support Random Access]. 13 | The size of the array cannot be altered(once initialized). However, an array reference can be made to point to another array. 14 | An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. 15 | In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment. 16 | 17 | An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class). 18 | Thus, the element type for the array determines what type of data the array will hold. 19 | 20 | Although the first declaration establishes that intArray is an array variable, no actual array exists. It merely tells the compiler that this variable (intArray) will hold an array of the integer type. 21 | To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray. 22 | 23 | -------------------------------------------------------------------------------- /src/iterator/iterator: -------------------------------------------------------------------------------- 1 | A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one. There are three cursors in Java. 2 | 3 | Iterator 4 | Enumeration 5 | ListIterator 6 | Note: SplitIterator can also be considered as a cursor as it is a type of Iterator only. 7 | 8 | Iterators in Java are used in the Collection framework to retrieve elements one by one. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an element. 9 | 10 | Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map interface. Iterator is the only cursor available for the entire collection framework. 11 | Iterator object can be created by calling iterator() method present in Collection interface. 12 | 13 | Syntax: 14 | 15 | Iterator itr = c.iterator(); 16 | Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”. 17 | Methods of Iterator Interface in Java 18 | Iterator interface defines three methods as listed below: 19 | 20 | 1. hasNext(): Returns true if the iteration has more elements. 21 | 22 | public boolean hasNext(); 23 | 2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present. 24 | 25 | public Object next(); 26 | 3. remove(): Removes the next element in the iteration. This method can be called only once per call to next(). 27 | 28 | public void remove(); 29 | Note: remove() method can throw two exceptions namely as follows: 30 | 31 | UnsupportedOperationException : If the remove operation is not supported by this iterator 32 | IllegalStateException : If the next method has not yet been called, or the remove method has already been called after the last call to the next method. 33 | 34 | Here Iterator’s Cursor is pointing before the first element of the List. 35 | 36 | As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns a false value. 37 | 38 | Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also known as Uni-Directional Cursor. 39 | 40 | -------------------------------------------------------------------------------- /src/string/stringbuffer: -------------------------------------------------------------------------------- 1 | StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. 2 | 3 | Some Interesting Facts about the StringBuffer class 4 | 5 | Do keep the following points in the back of your mind: 6 | 7 | java.lang.StringBuffer extends (or inherits from) Object class. 8 | All Implemented Interfaces of StringBuffer class: Serializable, Appendable, CharSequence. 9 | public final class StringBuffer extends Object implements Serializable, CharSequence, Appendable. 10 | String buffers are safe for use by multiple threads. The methods can be synchronized wherever necessary so that all the operations on any particular instance behave as if they occur in some serial order. 11 | Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source. 12 | It inherits some of the methods from the Object class which such as clone(), equals(), finalize(), getClass(), hashCode(), notifies(), notifyAll(). 13 | Remember: StringBuilder, J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are using multithreading, you must use StringBuffer rather than StringBuilder. 14 | 15 | Constructors of StringBuffer class 16 | 17 | 1. StringBuffer(): It reserves room for 16 characters without reallocation 18 | 19 | StringBuffer s = new StringBuffer(); 20 | 2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer. 21 | 22 | StringBuffer s = new StringBuffer(20); 23 | 3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. 24 | 25 | StringBuffer s = new StringBuffer("GeeksforGeeks"); 26 | 27 | -------------------------------------------------------------------------------- /src/datastructure/map/map: -------------------------------------------------------------------------------- 1 | The map interface is present in java.util package represents a mapping between a key and a value. 2 | The Map interface is not a subtype of the Collection interface. 3 | Therefore it behaves a bit differently from the rest of the collection types. 4 | A map contains unique keys. 5 | 6 | Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to perform lookups by keys or when someone wants to retrieve and update elements by keys. Some common scenarios are as follows: 7 | 8 | A map of error codes and their descriptions. 9 | A map of zip codes and cities. 10 | A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages. 11 | A map of classes and students. Each class (key) is associated with a list of students (value) 12 | 13 | Since Map is an interface, objects cannot be created of the type map. We always need a class that extends this map in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Map. 14 | 15 | Syntax: Defining Type-safe Map 16 | 17 | Map hm = new HashMap(); 18 | // Obj is the type of the object to be stored in Map 19 | 20 | A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null values like the HashMap and LinkedHashMap, but some do not like the TreeMap. 21 | The order of a map depends on the specific implementations. For example, TreeMap and LinkedHashMap have predictable orders, while HashMap does not. 22 | There are two interfaces for implementing Map in java. They are Map and SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap. 23 | 24 | Class 1: HashMap 25 | HashMap is a part of Java’s collection since Java 1.2. 26 | It provides the basic implementation of the Map interface of Java. 27 | It stores the data in (Key, Value) pairs. To access a value one must know its key. 28 | This class uses a technique called Hashing. 29 | Hashing is a technique of converting a large String to a small String that represents the same String. 30 | A shorter value helps in indexing and faster searches. Let’s see how to create a map object using this class. 31 | 32 | Class 2: LinkedHashMap 33 | LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. 34 | HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. 35 | 36 | Class 3: TreeMap 37 | The TreeMap in Java is used to implement the Map interface and NavigableMap along with the Abstract Class. 38 | The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. 39 | This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators 40 | 41 | -------------------------------------------------------------------------------- /src/datastructure/hashset/hashset: -------------------------------------------------------------------------------- 1 | The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. 2 | No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. 3 | This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets, 4 | 5 | Implements Set Interface. 6 | The underlying data structure for HashSet is Hashtable. 7 | As it implements the Set Interface, duplicate values are not allowed. 8 | Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects are inserted based on their hash code. 9 | NULL elements are allowed in HashSet. 10 | HashSet also implements Serializable and Cloneable interfaces 11 | 12 | HashSet extends Abstract Set class and implements Set, Cloneable, and Serializable interfaces where E is the type of elements maintained by this set. 13 | The directly known subclass of HashSet is LinkedHashSet. 14 | 15 | Now for the maintenance of constant time performance, 16 | iterating over HashSet requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. 17 | 18 | Initial Capacity: The initial capacity means the number of buckets when hashtable (HashSet internally uses hashtable data structure) is created. The number of buckets will be automatically increased if the current size gets full. 19 | 20 | Load Factor: The load factor is a measure of how full the HashSet is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. 21 | 22 | Internal working of a HashSet: All the classes of Set interface are internally backed up by Map. HashSet uses HashMap for storing its object internally. You must be wondering that to enter a value in HashMap we need a key-value pair, but in HashSet, we are passing only one value. 23 | 24 | Storage in HashMap: Actually the value we insert in HashSet acts as a key to the map Object and for its value, java uses a constant variable. So in the key-value pair, all the values will be the same. 25 | 26 | Note: The implementation in a HashSet is not synchronized, in the sense that if multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set as shown below: 27 | 28 | Set s = Collections.synchronizedSet(new HashSet(...)); 29 | -------------------------------------------------------------------------------- /src/oop/interfaceexample/ComporatorExample.java: -------------------------------------------------------------------------------- 1 | package oop.interfaceexample; 2 | 3 | import java.io.*; 4 | import java.lang.*; 5 | import java.util.*; 6 | 7 | // Class 1 8 | // A class to represent a Student 9 | class Student { 10 | 11 | // Attributes of a student 12 | int rollno; 13 | String name, address; 14 | 15 | // Constructor 16 | public Student(int rollno, String name, String address) 17 | { 18 | 19 | // This keyword refers to current instance itself 20 | this.rollno = rollno; 21 | this.name = name; 22 | this.address = address; 23 | } 24 | 25 | // Method of Student class 26 | // To print student details in main() 27 | public String toString() 28 | { 29 | 30 | // Returning attributes of Student 31 | return this.rollno + " " + this.name + " " 32 | + this.address; 33 | } 34 | } 35 | 36 | // Class 2 37 | // Helper class implementing Comparator interface 38 | class Sortbyroll implements Comparator { 39 | 40 | // Method 41 | // Sorting in ascending order of roll number 42 | public int compare(Student a, Student b) 43 | { 44 | 45 | return a.rollno - b.rollno; 46 | } 47 | } 48 | 49 | // Class 3 50 | // Helper class implementing Comparator interface 51 | class Sortbyname implements Comparator { 52 | 53 | // Method 54 | // Sorting in ascending order of name 55 | public int compare(Student a, Student b) 56 | { 57 | 58 | return a.name.compareTo(b.name); 59 | } 60 | } 61 | public class ComporatorExample { 62 | public static void main(String[] args) 63 | { 64 | 65 | // Creating an empty ArrayList of Student type 66 | ArrayList ar = new ArrayList(); 67 | 68 | // Adding entries in above List 69 | // using add() method 70 | ar.add(new Student(111, "Mayank", "london")); 71 | ar.add(new Student(131, "Anshul", "nyc")); 72 | ar.add(new Student(121, "Solanki", "jaipur")); 73 | ar.add(new Student(101, "Aggarwal", "Hongkong")); 74 | 75 | // Display message on console for better readability 76 | System.out.println("Unsorted"); 77 | 78 | // Iterating over entries to print them 79 | for (int i = 0; i < ar.size(); i++) 80 | System.out.println(ar.get(i)); 81 | 82 | // Sorting student entries by roll number 83 | Collections.sort(ar, new Sortbyroll()); 84 | 85 | // Display message on console for better readability 86 | System.out.println("\nSorted by rollno"); 87 | 88 | // Again iterating over entries to print them 89 | for (int i = 0; i < ar.size(); i++) 90 | System.out.println(ar.get(i)); 91 | 92 | // Sorting student entries by name 93 | Collections.sort(ar, new Sortbyname()); 94 | 95 | // Display message on console for better readability 96 | System.out.println("\nSorted by name"); 97 | 98 | // // Again iterating over entries to print them 99 | for (int i = 0; i < ar.size(); i++) 100 | System.out.println(ar.get(i)); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/string/string: -------------------------------------------------------------------------------- 1 | Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. 2 | 3 | Memory allotment of String 4 | 5 | Whenever a String Object is created as a literal, the object will be created in String constant pool. This allows JVM to optimize the initialization of String literal. 6 | 7 | For example: 8 | 9 | String str = "Geeks"; 10 | The string can also be declared using new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in heap. This string will not be added to String constant pool. 11 | 12 | For example: 13 | 14 | String str = new String("Geeks"); 15 | If you want to store this string in the constant pool then you will need to “intern” it. 16 | 17 | For example: 18 | 19 | String internedString = str.intern(); 20 | // this will add the string to string constant pool. 21 | It is preferred to use String literals as it allows JVM to optimize memory allocation. 22 | 23 | Interfaces and Classes in Strings in Java 24 | 25 | CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex. 26 | 27 | String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. 28 | 29 | StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. 30 | 31 | Syntax: 32 | 33 | StringBuffer s = new StringBuffer("GeeksforGeeks"); 34 | StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternate to String Class, as it creates a mutable sequence of characters. 35 | 36 | Syntax: 37 | 38 | StringBuilder str = new StringBuilder(); 39 | str.append("GFG"); 40 | StringTokenizer class in Java is used to break a string into tokens. 41 | 42 | A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. 43 | 44 | StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write. 45 | Syntax: 46 | 47 | public StringJoiner(CharSequence delimiter) 48 | 49 | Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache which stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area. 50 | 51 | All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also. 52 | -------------------------------------------------------------------------------- /src/jdbc/jdbc: -------------------------------------------------------------------------------- 1 | JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write programs required to access databases. JDBC, along with the database driver, can access databases and spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the help of JDBC APIs. 2 | 3 | Definition of JDBC(Java Database Connectivity) 4 | 5 | JDBC is an API(Application programming interface) used in java programming to interact with databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified database. 6 | 7 | Purpose of JDBC 8 | 9 | Enterprise applications created using the JAVA EE technology need to interact with databases to store application-specific information. So, interacting with a database requires efficient database connectivity, which can be achieved by using the ODBC(Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various kinds of databases such as Oracle, MS Access, Mysql, and SQL server database. 10 | 11 | Components of JDBC 12 | There are generally four main components of JDBC through which it can interact with a database. They are as mentioned below: 13 | 14 | 1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run everywhere) capabilities. 15 | 16 | java.sql.*; 17 | 2. It also provides a standard to connect a database to a client application. 18 | 19 | 3. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a database. It is used to make a database-specific call to the database to process the user request. 20 | 21 | 4. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC Drivers. 22 | 23 | 5. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library to access ODBC characteristics. 24 | 25 | architecture of jdbc: 26 | Description: 27 | 28 | Application: It is a java applet or a servlet that communicates with a data source. 29 | The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of the important classes and interfaces defined in JDBC API are as follows: 30 | DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively connect enterprise applications to databases. 31 | JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently communicates with the respective data source. 32 | JDBC Drivers 33 | JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers: 34 | 35 | Type-1 driver or JDBC-ODBC bridge driver 36 | Type-2 driver or Native-API driver 37 | Type-3 driver or Network Protocol driver 38 | Type-4 driver or Thin driver 39 | 40 | Interfaces of JDBC API 41 | 42 | A list of popular interfaces of JDBC API is given below: 43 | 44 | Driver interface 45 | Connection interface 46 | Statement interface 47 | PreparedStatement interface 48 | CallableStatement interface 49 | ResultSet interface 50 | ResultSetMetaData interface 51 | DatabaseMetaData interface 52 | RowSet interface 53 | Classes of JDBC API 54 | A list of popular classes of JDBC API is given below: 55 | 56 | DriverManager class 57 | Blob class 58 | Clob class 59 | Types class 60 | 61 | Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be added in java application for JDBC support which can be done dynamically at run time. This JDBC driver intelligently communicates the respective data source. 62 | 63 | -------------------------------------------------------------------------------- /src/oop/inheritance/inheritancee: -------------------------------------------------------------------------------- 1 | Inheritance is an important pillar of OOP(Object-Oriented Programming). 2 | It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. 3 | 4 | Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class). 5 | Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. 6 | Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. 7 | How to use inheritance in Java 8 | 9 | The keyword used for inheritance is extends. 10 | 11 | Syntax : 12 | 13 | class derived-class extends base-class 14 | { 15 | //methods and fields 16 | } 17 | Types of Inheritance in Java 18 | 19 | Below are the different types of inheritance which are supported by Java. 20 | 21 | 1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B. 22 | 2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. 23 | 3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D. 24 | 4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from interface A and B. 25 | 26 | Important facts about inheritance in Java 27 | 28 | Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class. 29 | Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by java. 30 | Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. 31 | Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass. 32 | 33 | What all can be done in a Subclass? 34 | 35 | In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members: 36 | 37 | The inherited fields can be used directly, just like any other fields. 38 | We can declare new fields in the subclass that are not in the superclass. 39 | The inherited methods can be used directly as they are. 40 | We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in the example above, toString() method is overridden). 41 | We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. 42 | We can declare new methods in the subclass that are not in the superclass. 43 | We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/oop/interfaceexample/interface: -------------------------------------------------------------------------------- 1 | An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods. 2 | 3 | The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. 4 | 5 | Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). 6 | 7 | Interfaces specify what a class must do and not how. It is the blueprint of the class. 8 | An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. 9 | If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. 10 | A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection. 11 | Syntax: 12 | 13 | interface { 14 | 15 | // declare constant fields 16 | // declare methods that abstract 17 | // by default. 18 | } 19 | To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword. 20 | 21 | Why do we use an Interface? 22 | It is used to achieve total abstraction. 23 | Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. 24 | It is also used to achieve loose coupling. 25 | Interfaces are used to implement abstraction. So the question arises why use interfaces when we have abstract classes? 26 | The reason is, abstract classes may contain non-final variables, whereas variables in the interface are final, public and static. 27 | 28 | // A simple interface 29 | 30 | interface Player 31 | { 32 | final int id = 10; 33 | int move(); 34 | } 35 | 36 | Difference Between Class and Interface 37 | The major differences between a class and an interface are: 38 | 39 | S. No. Class Interface 40 | 1. In class, you can instantiate variables and create an object. In an interface, you can’t instantiate variables and create an object. 41 | 2. Class can contain concrete(with implementation) methods The interface cannot contain concrete(with implementation) methods 42 | 3. The access specifiers used with classes are private, protected, and public. In Interface only one specifier is used- Public. 43 | 44 | New Features Added in Interfaces in JDK 8 45 | 1. Prior to JDK 8, the interface could not define the implementation. We can now add default implementation for interface methods. This default implementation has a special use and does not affect the intention behind interfaces. 46 | 47 | Suppose we need to add a new function in an existing interface. Obviously, the old code will not work as the classes have not implemented those new functions. So with the help of default implementation, we will give a default body for the newly added functions. Then the old codes will still work. 48 | 49 | 2. Another feature that was added in JDK 8 is that we can now define static methods in interfaces that can be called independently without an object. Note: these methods are not inherited. 50 | 51 | Important Points About Interface : 52 | We can’t create an instance(interface can’t be instantiated) of the interface but we can make the reference of it that refers to the Object of its implementing class. 53 | A class can implement more than one interface. 54 | An interface can extend to another interface or interface (more than one interface). 55 | A class that implements the interface must implement all the methods in the interface. 56 | All the methods are public and abstract. And all the fields are public, static, and final. 57 | It is used to achieve multiple inheritances. 58 | It is used to achieve loose coupling. -------------------------------------------------------------------------------- /src/exception/exception: -------------------------------------------------------------------------------- 1 | Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. 2 | 3 | Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred. 4 | 5 | Major reasons why an exception Occurs 6 | Invalid user input 7 | Device failure 8 | Loss of network connection 9 | Physical limitations (out of disk memory) 10 | Code errors 11 | Opening an unavailable file 12 | Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors. 13 | 14 | Let us discuss the most important part which is the differences between Error and Exception that is as follows: 15 | 16 | Error: An Error indicates a serious problem that a reasonable application should not try to catch. 17 | Exception: Exception indicates conditions that a reasonable application might try to catch. 18 | Exception Hierarchy 19 | All exception and error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error. 20 | 21 | Exceptions can be categorized in two ways: 22 | 23 | Built-in Exceptions 24 | Checked Exception 25 | Unchecked Exception 26 | User-Defined Exceptions 27 | Let us discuss the above-defined listed exception that is as follows: 28 | 29 | A. Built-in Exceptions: 30 | Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. 31 | 32 | Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. 33 | 34 | Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error. 35 | 36 | B. User-Defined Exceptions: 37 | Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’. 38 | 39 | The advantages of Exception Handling in Java are as follows: 40 | 41 | Provision to Complete Program Execution 42 | Easy Identification of Program Code and Error-Handling Code 43 | Propagation of Errors 44 | Meaningful Error Reporting 45 | Identifying Error Types 46 | 47 | How Does JVM handle an Exception? 48 | Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. Creating the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of the methods is called Call Stack. Now the following procedure will happen. 49 | 50 | The run-time system searches the call stack to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an Exception handler. 51 | The run-time system starts searching from the method in which the exception occurred, and proceeds through the call stack in the reverse order in which methods were called. 52 | If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle. 53 | If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate handler, then the run-time system handover the Exception Object to the default exception handler, which is part of the run-time system. This handler prints the exception information in the following format and terminates the program abnormally. 54 | 55 | How Programmer Handles an Exception? 56 | Customized Exception Handling: Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block. 57 | 58 | -------------------------------------------------------------------------------- /src/threadd/thread: -------------------------------------------------------------------------------- 1 | Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that do not affect the working of other threads despite them sharing the same memory. 2 | 3 | a thread runs inside the process and there will be context-based switching between threads there can be multiple processes running in OS, and each process again can have multiple threads running simultaneously. The Multithreading concept is popularly applied in games, animation…etc. 4 | 5 | The Concept Of Multitasking 6 | To help users Operating System accommodates users the privilege of multitasking, where users can perform multiple actions simultaneously on the machine. This Multitasking can be enabled in two ways: 7 | 8 | Process-Based Multitasking 9 | Thread-Based Multitasking 10 | 1. Process-Based Multitasking (Multiprocessing) 11 | 12 | In this type of Multitasking, processes are heavyweight and each process was allocated by a separate memory area. And as the process is heavyweight the cost of communication between processes is high and it takes a long time for switching between processes as it involves actions such as loading, saving in registers, updating maps, lists, etc. 13 | 14 | 2. Thread-Based Multitasking 15 | 16 | As we discussed above Threads are provided with lightweight nature and share the same address space, and the cost of communication between threads is also low. 17 | 18 | Why Threads are used? 19 | Now, we can understand why threads are being used as they had the advantage of being lightweight and can provide communication between multiple threads at a Low Cost contributing to effective multi-tasking within a shared memory environment. 20 | 21 | Life Cycle Of Thread 22 | There are different states Thread transfers into during its lifetime, let us know about those states in the following lines: in its lifetime, a thread undergoes the following states, namely: 23 | 24 | New State 25 | Active State 26 | Waiting/Blocked State 27 | Timed Waiting State 28 | Terminated State 29 | 30 | We can see the working of different states in a Thread in the above Diagram, let us know in detail each and every state: 31 | 32 | 1. New State 33 | 34 | By Default, a Thread will be a new state, in this state, code has not yet been run and the execution process is not yet initiated. 35 | 36 | 2. Active State 37 | 38 | A Thread that is a new state by default gets transferred to Active state when it invokes the start() method, his Active state contains two sub-states namely : 39 | 40 | Runnable State: In This State, The Thread is ready to run at any given time and it’s the job of the Thread Scheduler to provide the thread time for the runnable state preserved threads. A program that has obtained Multithreading shares slices of time intervals which are shared between threads hence, these threads run for some short span of time and wait in the runnable state to get their schedules slice of a time interval. 41 | Running State: When The Thread Receives CPU allocated by Thread Scheduler, it transfers from “Runnable” state to “Running” state. and after the expiry of its given time slice session, it again moves back to the “Runnable” state and waits for its next time slice. 42 | 3. Waiting/Blocked State 43 | 44 | If a Thread is inactive but on a temporary time, then either it is at waiting or blocked state, for example, if there are two threads, T1 and T2 where T1 need to communicate to the camera and other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its work, at this state T1 is parked in waiting for the state, and in another scenario, the user called two Threads T2 and T3 with the same functionality and both had same time slice given by Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple threads parked in Blocked/Waiting state Thread Scheduler clears Queue by rejecting unwanted Threads and allocating CPU on a priority basis. 45 | 46 | 4. Timed Waiting State 47 | 48 | Sometimes the longer duration of waiting for threads causes starvation, if we take an example like there are two threads T1, T2 waiting for CPU and T1 is undergoing Critical Coding operation and if it does not exit CPU until its operation gets executed then T2 will be exposed to longer waiting with undetermined certainty, In order to avoid this starvation situation, we had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting, each thread has a time period for which sleep() method is invoked and after the time expires the Threads starts executing its task. 49 | 50 | 5. Terminated State 51 | 52 | A thread will be in Terminated State, due to the below reasons: 53 | 54 | Termination is achieved by a Thread when it finishes its task Normally. 55 | Sometimes Threads may be terminated due to unusual events like segmentation faults, exceptions…etc. and such kind of Termination can be called Abnormal Termination. 56 | A terminated Thread means it is dead and no longer available. 57 | What is Main Thread? 58 | As we are familiar that, we create Main Method in each and every Java Program, which acts as an entry point for the code to get executed by JVM, Similarly in this Multithreading Concept, Each Program has one Main Thread which was provided by default by JVM, hence whenever a program is being created in java, JVM provides the Main Thread for its Execution. 59 | 60 | How to Create Threads using Java Programming Language? 61 | We can create Threads in java using two ways, namely : 62 | 63 | By extending Thread Class 64 | By Implementing a Runnable interface 65 | 1. By Extending Thread Class 66 | 67 | We can run Threads in Java by using Thread Class, which provides constructors and methods for creating and performing operations on a Thread, which extends a Thread class that can implement Runnable Interface. We use the following constructors for creating the Thread: 68 | 69 | Thread 70 | Thread(Runnable r) 71 | Thread(String name) 72 | Thread(String name, Runnable r) 73 | 74 | There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started. 75 | 76 | The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. 77 | 78 | Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it. 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | --------------------------------------------------------------------------------