├── JDBC-questions.md ├── README.md ├── _config.yml ├── assets ├── aggregation.png ├── collection-class.png ├── collection.png ├── exception.png ├── jdk.jpg ├── jpa_class_level_architecture.png ├── map-interface.png ├── recursive.png ├── shorted-path-dijkstras.png └── star.png ├── collections-questions.md ├── core-java ├── arrays │ ├── ArrayListSpliterator.java │ ├── ArrayListToArrayConversion.java │ ├── ArrayVsArrayList.java │ ├── Arrays.java │ ├── ArraysBinarySearch.java │ ├── ArraysBinarySearch2.java │ ├── ArraysClass.java │ ├── ArraysCloning.java │ ├── ArraysComparision.java │ ├── ArraysComparisionDeepEquals.java │ ├── ArraysCopyOf.java │ ├── ClassObjectsArrays.java │ ├── JaggedArray.java │ ├── MergeArrays.java │ ├── MultidimensionalArray.java │ ├── ParallelSort.java │ ├── ParallelSortUsingSeries.java │ ├── ReflectionArrayClass.java │ └── package-info.java ├── basics │ ├── ArrayBlockingQueueAdd.java │ ├── ArrayBlockingQueuePut.java │ ├── BinarySearch.java │ ├── BinarySearchCollections.java │ ├── BlankFinal.java │ ├── BoundedTypesGenerics.java │ ├── BoundedTypesGenerics02.java │ ├── CurryingFunctions.java │ ├── EnumConstructorExample.java │ ├── EnumDemo01.java │ ├── EnumDemo02.java │ ├── EnumDemo03.java │ ├── EnumDemo04.java │ ├── InstanceVariables.java │ ├── InstanceofOperator.java │ ├── JVMDemo01.java │ ├── JVMDemo02.java │ ├── NestedSwitchCase.java │ ├── NullExample.java │ ├── NullReferenceVariable.java │ ├── Number.java │ ├── OutOfMemoryException.java │ ├── ShutDownHook.java │ ├── SortSubarray.java │ ├── SortUsingCollections.java │ ├── SortingInJava.java │ ├── StaticVsNonStaticMethods.java │ ├── StrictMathLog.java │ ├── StringBufferAppendCodePoint01.java │ ├── StringBuilderAppend01.java │ ├── TreeSetComparator.java │ ├── UnderscoreAs_Variable.java │ ├── UnderscoreInNumeric.java │ ├── VariablesScope01.java │ ├── VariablesScope02.java │ └── WideningPrimitiveConversion.java ├── collections │ ├── AbstractCollectionExample.java │ ├── AbstractListExample.java │ ├── AbstractQueueExample.java │ ├── AbstractSetExample.java │ ├── ArrayBlockingQueueExample.java │ ├── ArrayDequeExample.java │ ├── ArrayListExample.java │ ├── ArrayListSynchronization.java │ ├── ConcurrentLinkedDequeExample.java │ ├── ConcurrentLinkedQueueExample.java │ ├── CopyOnWriteArrayListExample.java │ ├── CopyOnWriteArraySetExample.java │ ├── DictionaryExample.java │ ├── EnumSetExample.java │ ├── EnumerationExample.java │ ├── HashMapExample.java │ ├── HashSetExample.java │ ├── HashSetMerge.java │ ├── HashtableExample.java │ ├── IdentityHashMapExample.java │ ├── ImmutableListEample.java │ ├── IterableToCollectionConversion.java │ ├── IteratorExample.java │ ├── LinkedBlockingDequeExample.java │ ├── LinkedBlockingQueueExample.java │ ├── LinkedHashMapExample.java │ ├── LinkedHashSetExample.java │ ├── LinkedListExample.java │ ├── LinkedTransferQueueExample.java │ ├── ListIteratorExample.java │ ├── SortedMapExample.java │ ├── StackExample.java │ └── WeakHashMapExample.java ├── concurrent │ └── ConcurrentSemaphore.java ├── constructors │ ├── CopyConstructor.java │ └── PrivateConstructors.java ├── exceptionhandling │ ├── ChainedExceptions.java │ ├── OutOfMemoryErrorException.java │ └── PrintException.java ├── filehandling │ └── RemoveDuplicates.java ├── inheritance │ ├── AccessingGrandparentMember.java │ ├── Inheritance01.java │ ├── Inheritance02.java │ ├── ObjectSerializationInInheritance.java │ ├── OverloadingInInheritance.java │ ├── OverridePrivateMethods.java │ ├── ParentChildHavingSameDataMember.java │ └── RestrictiveAccessDerivedClass.java ├── input │ └── output │ │ ├── ByteStream.java │ │ ├── CharacterStream.java │ │ ├── CommandLineArguments.class │ │ ├── CommandLineArguments.java │ │ ├── DoubleStreamExample01.java │ │ ├── DoubleStreamExample02.java │ │ ├── ScannerClass.java │ │ ├── ScannerNextChar.java │ │ └── ScannerVsBufferReader.java ├── interfaces │ ├── NestedClasses.java │ └── NestedInterface.java ├── keywords │ ├── ReferenceFinalVariable.java │ ├── StaticBlocks.java │ ├── StaticMethod.java │ ├── StrictfpKeyword.java │ └── TransientKeyword.java ├── methods │ ├── DeepCopy.java │ ├── FillInStackTraceMethod.java │ ├── PassByValue.java │ ├── ReturnListObjectClass.java │ └── ShallowCopy.java ├── multithreading │ ├── CallableExample.java │ ├── CountDownLatchExample.java │ ├── DaemonThread.java │ ├── InterThreadCommunication.java │ ├── JoinExample.java │ ├── JoinMethod.java │ ├── MultithreadingUsingRunnable.java │ ├── MultithreadingUsingThread.java │ ├── RuntimeClass.java │ ├── SemaphoreMethod.java │ ├── SleepExample.java │ ├── StartExample.java │ ├── ThreadNaming.java │ ├── ThreadPools.java │ ├── ThreadPriority.java │ └── YieldExample.java ├── oopsconcepts │ ├── Aggregation.java │ ├── Association.java │ ├── ClassesAndObjects.java │ ├── Composition.java │ ├── CovariantReturnTypes.java │ ├── CreateObjectsUsingClone.java │ ├── CreateObjectsUsingDeserialization.java │ ├── CreateObjectsUsingNew.java │ ├── CreateObjectsUsingNewInstance.java │ ├── DynamicBinding.java │ ├── Finalize.java │ ├── InstanceVariableHiding.java │ ├── JavaLangObject.java │ ├── ObjectCreationOfInheritedClass.java │ ├── OverloadMain.java │ ├── OverloadingTest.java │ ├── OverrideStaticMethods.java │ ├── Overriding01.java │ ├── OverridingEquals.java │ ├── OverridingExceptionHandling.java │ ├── OverridingToString.java │ ├── ReflectionExample.java │ ├── RuntimePolymorphism.java │ ├── StaticBinding.java │ ├── StaticClass.java │ ├── SwapObjectsUsingWrapperClass.java │ ├── thisAsMethodParameter.java │ ├── thisToInvokeCurrentClassConstructor.java │ ├── thisToInvokeCurrentClassMethod.java │ ├── thisToReferCurrentClassInstanceVariables.java │ └── thisToReturnCurrentClassInstance.java ├── operators │ ├── AdditionAndConcatenation.java │ └── AutoboxedIntegerObjects.java ├── strings │ ├── CharactersSearch.java │ ├── CheckAlphabetsInString.java │ ├── CompareStrings.java │ ├── IntegerToStringConversions.java │ ├── ListExample01.java │ ├── ListRemoveIf.java │ ├── ListUsingLambdas.java │ ├── ListUsingRemoveAll.java │ ├── ReadTextFile.java │ ├── RemoveLeadingZeros.java │ ├── SplitMethod.java │ ├── StringBufferAppendCodePoint.java │ ├── StringBufferDeleteCharAt.java │ ├── StringBufferMethods.java │ ├── StringBuilderAndStringBufferClass.java │ ├── StringBuilderAndStringBufferClass02.java │ ├── StringBuilderAndStringBufferClass03.java │ ├── StringCompare.java │ ├── StringContainsAlphabets.java │ ├── StringContainsAlphabetsRegx.java │ ├── StringJoinerClass.java │ ├── StringMethods.java │ ├── StringToLowerCase.java │ ├── StringTokenizerClass.java │ ├── StringsToIntegerConversions.java │ ├── SwapTwoStrings.java │ └── ToStringMethod.java └── wrapperclasses │ ├── NumberClass.java │ └── PrimitiveWrapperClasse.java ├── java-multiple-choice-questions-answers.md ├── java-programs.md ├── java-programs ├── AddTwoNumbersRepresentedByLinkedList.java ├── ArrayListToArray.java ├── ArraySort.java ├── BinarySearchTreeImpl.java ├── BubbleSort.java ├── BucketSort.java ├── CheckNumberInString.java ├── CollectionSort.java ├── ConvertArrayListToStringArray.java ├── ConvertCollectionToSynchronizedCollection.java ├── ConvertLowerToUpperCase.java ├── CountCharactersInFile.java ├── CountingSort.java ├── CreateDeadlockBetweenTwoThreads.java ├── DynamicProgramming │ ├── CoinChange.java │ ├── KnapSack.java │ ├── PrintingLCS.java │ ├── editDistance.java │ ├── editDistanceOptimized.java │ ├── eggDroppingPuzzle.java │ ├── equalSumSubset.java │ ├── findPathExistence.java │ ├── getMinimumSquares.java │ ├── integerPartition.java │ ├── knapsack01.java │ ├── largestNumberWithKSwaps.java │ ├── lcsReeatedKtimes.java │ ├── longestPallindromicSubsequence.java │ ├── longestValidParanthesis.java │ ├── lpsString.java │ ├── maxPath.java │ ├── maxSumByRemovingOneEle.java │ ├── maximumCut.java │ ├── minimumCostPath.java │ ├── n_stairs.java │ ├── ncr.java │ ├── numberOfCoins.java │ ├── numberOfUniqueWays.java │ ├── optimalGameStartegy.java │ ├── pallindromicPartition.java │ ├── playerWithMaxScore.java │ └── stepsByKnight.java ├── FindDuplicateCharacter.java ├── FindMiddleIndex.java ├── Hashcode_Equals.java ├── InsertionSort.java ├── LCM_GCD.java ├── LaunchingExternalApps.java ├── LeadersInArray.java ├── LinkListSort.java ├── LinkedListCheckCyclic.java ├── LinkedListCheckPalindrome.java ├── LinkedListFindMiddleNode.java ├── LinkedListFindNodeFromEnd.java ├── LongestPalindromeSubstring.java ├── LongestSubstring.java ├── MaxTwoNumbersInArrays.java ├── MaximalSubarray.java ├── MergeSort.java ├── MissingNumber_01.java ├── MissingNumber_02.java ├── MostRepeatedWord.java ├── MoveZerosInArrays.java ├── PairSum.java ├── PairsWithGivenSum.java ├── Permutation.java ├── PrintAllSubstring.java ├── PrintEvenOddUsingThread.java ├── ProducerConsumerWaitNotify.java ├── QuickSort.java ├── RandomNumberGenerator.java ├── RemoveCharacter.java ├── RemoveCharactersFromString.java ├── RemoveDuplicate.java ├── RemoveDuplicateInArraylist.java ├── ReverseWordInString.java ├── SelectionSort.java ├── SingletonClass.java ├── SingletonClassMain.java ├── SinglyLinkedListReverse.java ├── SortATextFile.java ├── SquarerootOfNumber.java ├── StackSort.java ├── StringReverse.java ├── StringRotation.java ├── StringSwap.java ├── SumOfPrimeNumbers.java ├── UserDefinedException.java └── UserDefinedExceptionMain.java ├── java-string-methods.md ├── jsp-questions.md ├── multithreading-questions.md └── servlets-questions.md /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /assets/aggregation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/aggregation.png -------------------------------------------------------------------------------- /assets/collection-class.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/collection-class.png -------------------------------------------------------------------------------- /assets/collection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/collection.png -------------------------------------------------------------------------------- /assets/exception.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/exception.png -------------------------------------------------------------------------------- /assets/jdk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/jdk.jpg -------------------------------------------------------------------------------- /assets/jpa_class_level_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/jpa_class_level_architecture.png -------------------------------------------------------------------------------- /assets/map-interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/map-interface.png -------------------------------------------------------------------------------- /assets/recursive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/recursive.png -------------------------------------------------------------------------------- /assets/shorted-path-dijkstras.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/shorted-path-dijkstras.png -------------------------------------------------------------------------------- /assets/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/assets/star.png -------------------------------------------------------------------------------- /core-java/arrays/ArrayListSpliterator.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.*; 4 | import java.util.ArrayList; 5 | import java.lang.String; 6 | 7 | public class ArrayListSpliterator { 8 | 9 | public static void main(String[] args) { 10 | ArrayList list = new ArrayList(); 11 | 12 | list.add("abc@gmail.com"); 13 | list.add("xyz@gmail.com"); 14 | list.add("user@gmail.com"); 15 | list.add("mno@gmail.com"); 16 | list.add("random@gmail.com"); 17 | 18 | Spliterator emails = list.spliterator(); 19 | 20 | System.out.println("List of Emails: "); 21 | emails.forEachRemaining((n) -> System.out.println(n)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/arrays/ArrayListToArrayConversion.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ArrayListToArrayConversion { 7 | 8 | public static void main(String[] args) { 9 | List al = new ArrayList(); 10 | al.add(10); 11 | al.add(20); 12 | al.add(30); 13 | al.add(40); 14 | al.add(50); 15 | 16 | Integer[] arr = new Integer[al.size()]; 17 | arr = al.toArray(arr); 18 | 19 | for(Integer x: arr) { 20 | System.out.print(x + " "); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/arrays/ArrayVsArrayList.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | 7 | public class ArrayVsArrayList { 8 | 9 | public static void main(String[] args) { 10 | int[] arr = new int[3]; 11 | arr[0] = 1; 12 | arr[1] = 2; 13 | arr[2] = 3; 14 | // We can't add more elements to array arr[] 15 | 16 | /**....... ArrayList.........*/ 17 | ArrayList arrList = new ArrayList(); 18 | arrList.add(1); 19 | arrList.add(2); 20 | arrList.add(3); 21 | arrList.add(4); 22 | arrList.add(5); 23 | // We can add more elements to arrList 24 | 25 | System.out.println(arrList); 26 | System.out.println(Arrays.toString(arr)); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /core-java/arrays/Arrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Collection; 4 | 5 | public class Arrays { 6 | 7 | public static void main(String[] args) { 8 | int[] arr = new int[2]; 9 | arr[0] = 10; 10 | arr[1] = 20; 11 | 12 | try { 13 | for(int i = 0; i <= arr.length; i++ ){ 14 | System.out.println(arr[i]); 15 | } 16 | 17 | } catch (Exception e) { 18 | System.out.println("Exception: "+ e); 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysBinarySearch.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | 4 | public class ArraysBinarySearch { 5 | 6 | public static void main(String[] args) { 7 | 8 | int arr[] = {5, 1, 100, 50, 75, 12, 89, 51, 11, 28, 99}; 9 | int key = 99; 10 | 11 | System.out.println("Array: " + Arrays.toString(arr)); 12 | Arrays.sort(arr); 13 | System.out.println("Arrays after sort: "+Arrays.toString(arr)); 14 | System.out.println(key + " found at index: " + Arrays.binarySearch(arr, key)); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysBinarySearch2.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | 4 | public class ArraysBinarySearch2 { 5 | 6 | public static void main(String[] args) { 7 | int arr[] = {29, 3, 50, 9, 12, 73, 5, 89, 5, 34, 8, 97}; 8 | int key = 12; 9 | 10 | Arrays.sort(arr); 11 | System.out.println("Arrays after sort: "+Arrays.toString(arr)); 12 | 13 | System.out.println(key + " found at index: "+ Arrays.binarySearch(arr, 0, 10, key)); 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysClass.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | import org.apache.commons.lang.ArrayUtils; 6 | 7 | public class ArraysClass { 8 | 9 | public static void main(String[] args) { 10 | int arr[] = {4, 6, 5, 8, 3, 9, 7, 3, 2, 8}; 11 | 12 | System.out.println("Arrays: " + Arrays.toString(arr)); 13 | 14 | /* Arrays.sort(arr, 0, 5); 15 | System.out.println("Half Sorted Arrays: " + Arrays.toString(arr)); 16 | 17 | Arrays.sort(arr); 18 | int index = Arrays.binarySearch(arr, 1); 19 | System.out.println("Position of 9 in sorted arrays is: " + index); 20 | 21 | int[] copyArr = Arrays.copyOf(arr, arr.length); 22 | System.out.println("Copies arrays: " + Arrays.toString(copyArr)); 23 | 24 | Arrays.fill(arr, 0, 3, 5); 25 | System.out.println("Arrays filled with 5 from 0 to 3: "+ Arrays.toString(arr));*/ 26 | 27 | Integer[] newArr = ArrayUtils.toObject(arr); 28 | 29 | List al = Arrays.asList(newArr); 30 | System.out.println("As a List() :" + al); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysCloning.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/core-java/arrays/ArraysCloning.java -------------------------------------------------------------------------------- /core-java/arrays/ArraysComparision.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | 4 | public class ArraysComparision { 5 | 6 | public static void main(String[] args) { 7 | int arr1[] = {1, 2, 3}; 8 | int arr2[] = {1, 2, 3}; 9 | if(Arrays.equals(arr1, arr2)){ 10 | System.out.println("Both are Equal Arrays"); 11 | } else { 12 | System.out.println("Not Equals"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysComparisionDeepEquals.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | 4 | public class ArraysComparisionDeepEquals { 5 | 6 | public static void main(String[] args) { 7 | int intArray1[] = {1, 2, 3}; 8 | int intArray2[] = {1, 2, 3}; 9 | Object[] arr1 = {intArray1}; 10 | Object[] arr2 = {intArray2}; 11 | 12 | if(Arrays.deepEquals(arr1, arr2)) { 13 | System.out.println("Both are Equal Arrays"); 14 | } else { 15 | System.out.println("Not Equals"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/arrays/ArraysCopyOf.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArraysCopyOf { 6 | 7 | public static void main(String[] args) { 8 | int[] arr = new int[] {1, 2, 3}; 9 | 10 | System.out.println("Arrays: "+ Arrays.toString(arr)); 11 | 12 | int[] copy = Arrays.copyOf(arr, 5); 13 | copy[3] = 10; 14 | copy[4] = 20; 15 | System.out.println("Copied Arrays: " + Arrays.toString(copy)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/arrays/ClassObjectsArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class ClassObjectsArrays { 4 | 5 | public static void main(String[] args) { 6 | int intArray[] = new int[3]; 7 | byte byteArray[] = new byte[3]; 8 | short shortArray[] = new short[3]; 9 | String[] srtArray = new String[3]; 10 | 11 | System.out.println(intArray.getClass()); 12 | System.out.println(intArray.getClass().getSuperclass()); 13 | System.out.println(byteArray.getClass()); 14 | System.out.println(shortArray.getClass()); 15 | System.out.println(srtArray.getClass()); 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /core-java/arrays/JaggedArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class JaggedArray { 4 | 5 | public static void main(String[] args) { 6 | int r = 4; 7 | int arr[][] = new int[r][]; 8 | 9 | for(int i = 0; i < arr.length; i++) { 10 | arr[i] = new int[i+1]; 11 | } 12 | int count = 0; 13 | for(int i = 0; i < arr.length; i++) { 14 | for(int j = 0; j < arr[i].length; j++) { 15 | arr[i][j] = count++; 16 | } 17 | } 18 | 19 | System.out.println("Countents of 2D Array"); 20 | for(int i = 0; i < arr.length; i++) { 21 | for(int j = 0; j < arr[i].length; j++){ 22 | System.out.print(arr[i][j] + " "); 23 | } 24 | System.out.println(); 25 | } 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /core-java/arrays/MergeArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.*; 4 | 5 | public class MergeArrays { 6 | 7 | public static List concatenate(T[] a, T[] b) { 8 | // Create an empty List of type Object 9 | List n = new ArrayList<>(); 10 | 11 | // Add the array a into n 12 | Collections.addAll(n, a); 13 | 14 | // Add the array b into n 15 | Collections.addAll(n, b); 16 | 17 | return n; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Integer[] a = new Integer[]{1, 2, 3}; 22 | Integer[] b = new Integer[]{4, 5, 6}; 23 | 24 | List c = concatenate(a, b); 25 | 26 | System.out.println("Merged object array: " + c); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /core-java/arrays/MultidimensionalArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.Arrays; 3 | 4 | public class MultidimensionalArray { 5 | 6 | public static void main(String[] args) { 7 | int [][] arr = new int[2][2]; 8 | arr[0][0] = 10; 9 | arr[0][1] = 20; 10 | arr[1][0] = 30; 11 | arr[1][1] = 40; 12 | 13 | System.out.println(Arrays.deepToString(arr)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /core-java/arrays/ParallelSort.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ParallelSort { 6 | 7 | public static void main(String[] args) { 8 | int num[] = { 0, 9, 3, 8, 6, 1, 7, 5 }; 9 | 10 | System.out.print("Unsorted Arrays: "); 11 | Arrays.stream(num).forEach(n -> System.out.print(n + " ")); 12 | System.out.println(); 13 | 14 | Arrays.parallelSort(num); 15 | System.out.print("Sorted Array: "); 16 | Arrays.stream(num).forEach(n -> System.out.print(n + " ")); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/arrays/ParallelSortUsingSeries.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Random; 4 | import java.util.Arrays; 5 | 6 | public class ParallelSortUsingSeries { 7 | 8 | public static void main(String[] args) { 9 | int num[] = new int[100]; 10 | 11 | for(int i = 0; i < 1000; i += 10 ) { 12 | System.out.println("\nFor Iteration number: " + (i / 10 + 1)); 13 | 14 | Random rand = new Random(); 15 | for(int j = 0; j < 100; j++) { 16 | num[j] = rand.nextInt(); 17 | } 18 | // Start and End Time of Arrays.sort() 19 | long startTime = System.nanoTime(); 20 | 21 | // Preforming Serial Sort 22 | Arrays.sort(num); 23 | 24 | long endTime = System.nanoTime(); 25 | 26 | System.out.println("Start and End time in Serial: " + startTime + " : " + endTime); 27 | System.out.println("Time taken by Serial Sort:" + (endTime - startTime)); 28 | 29 | // Start and End Time of Arrays.parallelSort() 30 | startTime = System.nanoTime(); 31 | 32 | // Performing Parallel Sort 33 | Arrays.parallelSort(num); 34 | 35 | endTime = System.nanoTime(); 36 | 37 | // Printing result of Paralle Sort 38 | System.out.println("Start and End Time in Parallel: "+ startTime + ":" + endTime); 39 | System.out.println("Time taken by Parallel Sort: " + (endTime - startTime)); 40 | System.out.println(); 41 | 42 | } 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /core-java/arrays/ReflectionArrayClass.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.lang.reflect.Array; 3 | import java.util.Arrays; 4 | 5 | public class ReflectionArrayClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | int sizeOfArray = 3; 10 | 11 | // Create an integer array using 12 | // reflection.Array class 13 | int[] intArray = (int[])Array.newInstance(int.class, sizeOfArray); 14 | 15 | Array.setInt(intArray, 0, 10); 16 | Array.setInt(intArray, 1, 20); 17 | Array.setInt(intArray, 2, 30); 18 | 19 | System.out.println(Arrays.toString(intArray)); 20 | System.out.println("Element at index 0: " + Array.getInt(intArray, 0)); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/arrays/package-info.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | @author U6044324 4 | Nov 5, 2018 5 | */ 6 | package arrays; 7 | -------------------------------------------------------------------------------- /core-java/basics/ArrayBlockingQueueAdd.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.concurrent.ArrayBlockingQueue; 3 | 4 | public class ArrayBlockingQueueAdd { 5 | 6 | public static void main(String[] args) { 7 | // define capacity of ArrayBlockingQueue 8 | int capacity = 3; 9 | 10 | try { 11 | // Create object of ArrayBlockingQueue 12 | ArrayBlockingQueue queue = new ArrayBlockingQueue(capacity); 13 | 14 | // Add element to ArrayBlockingQueue 15 | queue.add(766); 16 | queue.add(432); 17 | queue.add(456); 18 | System.out.println("Added elements are: " + queue); 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/basics/ArrayBlockingQueuePut.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/core-java/basics/ArrayBlockingQueuePut.java -------------------------------------------------------------------------------- /core-java/basics/BinarySearch.java: -------------------------------------------------------------------------------- 1 | // Java implementation of iterative Binary Search 2 | 3 | import java.io.*; 4 | 5 | class BinarySearch { 6 | 7 | // Returns index of x if it is present in arr[]. 8 | int binarySearch(int arr[], int x) 9 | { 10 | int l = 0, r = arr.length - 1; 11 | while (l <= r) { 12 | int m = l + (r - l) / 2; 13 | 14 | // Check if x is present at mid 15 | if (arr[m] == x) 16 | return m; 17 | 18 | // If x greater, ignore left half 19 | if (arr[m] < x) 20 | l = m + 1; 21 | 22 | // If x is smaller, ignore right half 23 | else 24 | r = m - 1; 25 | } 26 | 27 | // If we reach here, then element was 28 | // not present 29 | return -1; 30 | } 31 | 32 | // Driver code 33 | public static void main(String args[]) 34 | { 35 | BinarySearch ob = new BinarySearch(); 36 | int arr[] = { 2, 3, 4, 10, 40 }; 37 | int n = arr.length; 38 | int x = 10; 39 | int result = ob.binarySearch(arr, x); 40 | if (result == -1) 41 | System.out.println( 42 | "Element is not present in array"); 43 | else 44 | System.out.println("Element is present at " 45 | + "index " + result); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /core-java/basics/BinarySearchCollections.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.List; 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class BinarySearchCollections { 7 | 8 | public static void main(String[] args) { 9 | List al = new ArrayList(); 10 | 11 | al.add(10); 12 | al.add(22); 13 | al.add(45); 14 | al.add(57); 15 | al.add(98); 16 | 17 | int key = 57; 18 | int res = Collections.binarySearch(al, key); 19 | if(res >= 0){ 20 | System.out.println(key + " found at index: "+res); 21 | } else { 22 | System.out.println(key + " not found"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/basics/BlankFinal.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class BlankFinal { 4 | 5 | final public int i; 6 | 7 | BlankFinal(int val) { 8 | this.i = val; 9 | } 10 | 11 | BlankFinal(){ 12 | this(10); 13 | } 14 | 15 | public static void main(String[] args) { 16 | BlankFinal obj1 = new BlankFinal(); 17 | System.out.println(obj1.i); 18 | 19 | BlankFinal obj2 = new BlankFinal(20); 20 | System.out.println(obj2.i); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core-java/basics/BoundedTypesGenerics.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | class Bound { 4 | private T objRef; 5 | 6 | public Bound(T obj){ 7 | this.objRef = obj; 8 | } 9 | 10 | public void doRunTest(){ 11 | this.objRef.displayClass(); 12 | } 13 | } 14 | 15 | class A { 16 | public void displayClass() { 17 | System.out.println("Inside super class A"); 18 | } 19 | } 20 | 21 | class B extends A { 22 | public void displayClass() { 23 | System.out.println("Inside sub class B"); 24 | } 25 | } 26 | 27 | class C extends A { 28 | public void displayClass() { 29 | System.out.println("Inside sub class C"); 30 | } 31 | } 32 | 33 | public class BoundedTypesGenerics { 34 | 35 | public static void main(String[] args) { 36 | 37 | Bound objc = new Bound(new C()); 38 | objc.doRunTest(); 39 | 40 | Bound objb = new Bound(new B()); 41 | objb.doRunTest(); 42 | 43 | Bound obja = new Bound(new A()); 44 | obja.doRunTest(); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /core-java/basics/BoundedTypesGenerics02.java: -------------------------------------------------------------------------------- 1 | interface SampleInterface { 2 | void displayClass(); 3 | } 4 | 5 | class BoundTest { 6 | private T objRef; 7 | 8 | public BoundTest(T obj) { 9 | this.objRef = obj; 10 | } 11 | 12 | public void doRunTest() { 13 | objRef.displayClass(); 14 | } 15 | } 16 | 17 | class SampleClass implements SampleInterface { 18 | public void displayClass() { 19 | System.out.println("Inside super Class A"); 20 | } 21 | } 22 | 23 | public class BoundedTypesGenerics02 { 24 | public static void main(String[] args) { 25 | BoundTest b = new BoundTest<>(new SampleClass()); 26 | b.doRunTest(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /core-java/basics/CurryingFunctions.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.function.Function; 3 | 4 | public class CurryingFunctions { 5 | 6 | public static void main(String[] args) { 7 | /** 8 | * Using Java 8 Functions 9 | * to create lambda expressions for functions 10 | * and with this, applying function Currying 11 | */ 12 | 13 | // Curried Function for Adding u & v 14 | Function> 15 | curryAdder = u -> v -> u + v; 16 | 17 | // Calling the curried functions 18 | System.out.println("Addition of 2 & 3 is: " + curryAdder 19 | .apply(2) 20 | .apply(3)); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/basics/EnumConstructorExample.java: -------------------------------------------------------------------------------- 1 | enum TrafficSignal { 2 | RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN"); 3 | 4 | private final String action; 5 | 6 | TrafficSignal(String action) { 7 | this.action = action; 8 | } 9 | 10 | public String getAction() { 11 | return action; 12 | } 13 | } 14 | 15 | public class EnumConstructorExample { 16 | public static void main(String[] args) { 17 | for (TrafficSignal signal : TrafficSignal.values()) { 18 | System.out.println("name: " + signal.name() + " action: " + signal.getAction()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/basics/EnumDemo01.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class EnumDemo01 { 4 | 5 | enum Color { 6 | RED, GREEN, BLUE; 7 | } 8 | public static void main(String[] args) { 9 | Color c1 = Color.RED; 10 | System.out.println("Enum value: "+c1); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /core-java/basics/EnumDemo02.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | enum Day { 4 | SUNDAY, MONDAY, TUESDAY, THURSDAY, FRIDAY, SATURDAY; 5 | } 6 | public class EnumDemo02 { 7 | 8 | Day day; 9 | 10 | public EnumDemo02(Day day) { 11 | this.day = day; 12 | } 13 | 14 | public void dayIsLike() { 15 | switch(day){ 16 | 17 | case MONDAY: System.out.println("Today is Monday"); break; 18 | 19 | case FRIDAY: System.out.println("Friday is better"); break; 20 | 21 | default: System.out.println("Weekends are best"); break; 22 | 23 | } 24 | } 25 | public static void main(String[] args) { 26 | 27 | String str = "FRIDAY"; 28 | EnumDemo02 t = new EnumDemo02(Day.valueOf(str)); 29 | t.dayIsLike(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-java/basics/EnumDemo03.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public enum EnumDemo03 { 4 | 5 | RED, GREEN, BLUE; 6 | 7 | public static void main(String[] args){ 8 | EnumDemo03 val = EnumDemo03.RED; 9 | System.out.println(val); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /core-java/basics/EnumDemo04.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | enum Color { 4 | RED, GREEN, BLUE; 5 | 6 | private Color() { 7 | System.out.println("Constructor called for: " + this.toString()); 8 | } 9 | 10 | public void colorInfo() { 11 | System.out.println("Universal Color"); 12 | } 13 | } 14 | public class EnumDemo04 { 15 | 16 | public static void main(String[] args) { 17 | Color c1 = Color.RED; 18 | System.out.println(c1); 19 | c1.colorInfo(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/basics/InstanceVariables.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | class Marks { 3 | int mathMarks; 4 | } 5 | public class InstanceVariables { 6 | 7 | public static void main(String[] args) { 8 | //First Object 9 | Marks obj1 = new Marks(); 10 | obj1.mathMarks = 99; 11 | 12 | //Second Object 13 | Marks obj2 = new Marks(); 14 | obj2.mathMarks = 90; 15 | 16 | System.out.println("Marks for first Object:" +obj1.mathMarks); 17 | System.out.println("Marks for second Object:" +obj2.mathMarks); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/basics/InstanceofOperator.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class InstanceofOperator { 4 | 5 | public static void main(String[] args) { 6 | Integer i = null; 7 | Integer j = 10; 8 | 9 | System.out.println(i instanceof Integer); 10 | System.out.println(j instanceof Integer); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /core-java/basics/JVMDemo01.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.lang.reflect.Field; 3 | import java.lang.reflect.Method; 4 | 5 | public class JVMDemo01 { 6 | 7 | public static void main(String[] args) { 8 | Employee s1 = new Employee(); 9 | 10 | // Getting hold of class object created by JVM 11 | Class c1 = s1.getClass(); 12 | System.out.println("Class Name: "+c1.getName()); 13 | 14 | // getting all methods in array 15 | Method m[] = c1.getDeclaredMethods(); 16 | for (Method method : m) 17 | System.out.println("Method Name: "+method.getName()); 18 | 19 | // getting all fields in array 20 | Field f[] = c1.getDeclaredFields(); 21 | for(Field field: f) 22 | System.out.println("Field Name: "+field.getName()); 23 | } 24 | } 25 | 26 | // A Sample class whose information is fetched above using its Class Object. 27 | class Employee{ 28 | private String name; 29 | private int emp_id; 30 | public String getName() { return name; } 31 | public void setName(String name) { this.name = name; } 32 | public int getEmp_id() { return emp_id; } 33 | public void setEmp_id(int emp_id) { 34 | this.emp_id = emp_id; 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /core-java/basics/JVMDemo02.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class JVMDemo02 { 4 | 5 | public static void main(String[] args) { 6 | // String class is loaded by bootstrap loader and 7 | // bootstrap loader is not Java Object, hence null 8 | System.out.println(String.class.getClassLoader()); 9 | 10 | // JVMDemo class is loaded by Application loader 11 | System.out.println(JVMDemo02.class.getClassLoader()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core-java/basics/NestedSwitchCase.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class NestedSwitchCase { 4 | 5 | public static void main(String[] args) { 6 | String Branch = "CSE"; 7 | int year = 2; 8 | 9 | switch(year) { 10 | case 1: 11 | System.out.println("Elective cources: Algebra"); break; 12 | case 2: 13 | switch(Branch) { 14 | case "CSE": 15 | case "CCE": 16 | System.out.println("elective courses : Machine Learning, Big Data"); break; 17 | case "ECE": 18 | System.out.println("elective courses : Antenna Engineering"); break; 19 | default: 20 | System.out.println("Elective courses : Optimization"); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core-java/basics/NullExample.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class NullExample { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(null == null); 7 | System.out.println(null != null); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /core-java/basics/NullReferenceVariable.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class NullReferenceVariable { 4 | 5 | private static Object obj; 6 | public static void main(String[] args) { 7 | System.out.println("Value of Object: "+ obj); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /core-java/basics/Number.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class Number { 4 | 5 | public static void main(String[] args) { 6 | byte n = 126; 7 | 8 | System.out.println("Sum: "+ n); 9 | n++; 10 | System.out.println("Sum: "+ n); 11 | n++; 12 | System.out.println("Sum: "+ n); 13 | n++; 14 | System.out.println("Sum: "+ n); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/basics/OutOfMemoryException.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.ArrayList; 3 | 4 | public class OutOfMemoryException { 5 | 6 | public static void main(String[] args) { 7 | ArrayList arr = new ArrayList<>(); 8 | 9 | for(int i = 0; i < Integer.MAX_VALUE; i++){ 10 | arr.add(i); 11 | 12 | if(i >= 10){ 13 | break; 14 | } 15 | } 16 | System.out.println("Value: "+ arr); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/basics/ShutDownHook.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class ShutDownHook { 4 | 5 | public static void main(String[] args) { 6 | 7 | Runtime.getRuntime().addShutdownHook(new Thread() { 8 | 9 | public void run() { 10 | System.out.println("Shutdown Hook is running !"); 11 | } 12 | }); 13 | System.out.println("Application Terminating ..."); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /core-java/basics/SortSubarray.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class SortSubarray { 7 | 8 | public static void main(String[] args) { 9 | 10 | int arr[] = { 13, 7, 6, 45, 21, 9, 2, 100 }; 11 | Arrays.sort(arr, 0, 5); 12 | System.out.printf("Sorted Array: %s ", Arrays.toString(arr)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/basics/SortUsingCollections.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | public class SortUsingCollections { 7 | 8 | public static void main(String[] args) { 9 | List al = new ArrayList(); 10 | 11 | al.add("Red"); 12 | al.add("Green"); 13 | al.add("Yellow"); 14 | 15 | Collections.sort(al, Collections.reverseOrder()); 16 | System.out.println("Sorted List Array: " + al ); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/basics/SortingInJava.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.Arrays; 3 | public class SortingInJava { 4 | 5 | public static void main(String[] args) { 6 | int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; 7 | Arrays.sort(arr); 8 | System.out.printf("Sorted Array: %s", Arrays.toString(arr)); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /core-java/basics/StaticVsNonStaticMethods.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class StaticVsNonStaticMethods { 4 | 5 | public static void main(String[] args) { 6 | StaticVsNonStaticMethods obj = null; 7 | obj.staticMethod(); 8 | obj.nonStaticMethod(); 9 | } 10 | 11 | private static void staticMethod() { 12 | System.out.println("Static method, can be called by null reference"); 13 | } 14 | 15 | private void nonStaticMethod() { 16 | System.out.println("Non-static method- "); 17 | System.out.println("Cannot be called by null reference"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/basics/StrictMathLog.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class StrictMathLog { 4 | 5 | public static void main(String[] args) { 6 | double num = 10; 7 | 8 | // It returns natural logarithm(base e) 9 | double log_value = StrictMath.log(num); 10 | System.out.print("Log value of: " + num + " = " + log_value); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /core-java/basics/StringBufferAppendCodePoint01.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class StringBufferAppendCodePoint01 { 4 | 5 | public static void main(String[] args) { 6 | StringBuffer sbf = new StringBuffer("Pradee"); 7 | System.out .println("String buffer: " +sbf); 8 | 9 | sbf.appendCodePoint(112); //p 10 | System.out.println("After appending CodePoint: "+sbf); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /core-java/basics/StringBuilderAppend01.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class StringBuilderAppend01 { 4 | 5 | public static void main(String[] args) { 6 | StringBuilder sb = new StringBuilder("StringBuilder Append boolean value:- "); 7 | 8 | // Appending the boolean value 9 | sb.append(36.47); 10 | System.out.println("Output: " + sb); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /core-java/basics/TreeSetComparator.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | import java.util.Comparator; 3 | import java.util.TreeSet; 4 | 5 | public class TreeSetComparator { 6 | 7 | public static void main(String[] args) { 8 | // Creating an empty TreeSet 9 | TreeSet tree_set = new TreeSet(); 10 | 11 | // Adding elements to the set 12 | tree_set.add(45); 13 | tree_set.add(24); 14 | tree_set.add(30); 15 | tree_set.add(35); 16 | tree_set.add(20); 17 | tree_set.add(50); 18 | 19 | System.out.println("Tree Set values are: " + tree_set); 20 | 21 | // Creating a comparator 22 | Comparator comp = tree_set.comparator(); 23 | 24 | // Displaying the comparator values 25 | System.out.println("Is it follows natural ordering?: " + comp); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /core-java/basics/UnderscoreAs_Variable.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class UnderscoreAs_Variable { 4 | 5 | public static void main(String[] args) { 6 | int _ = 10; 7 | System.out.println(_); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /core-java/basics/UnderscoreInNumeric.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class UnderscoreInNumeric { 4 | 5 | public static void main(String[] args) { 6 | int num = 1_00_00_000; 7 | System.out.println("Inum: "+num); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /core-java/basics/VariablesScope01.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class VariablesScope01 { 4 | 5 | static int x = 10; 6 | private int y = 20; 7 | 8 | public void method(int x){ 9 | VariablesScope01 v = new VariablesScope01(); 10 | this.x = 30; 11 | y = 40; 12 | 13 | System.out.println("Local value of x: "+ v.x); 14 | System.out.println("Global value of y: "+ v.y); 15 | System.out.println("Local value of y: "+ y); 16 | 17 | } 18 | 19 | public static void main(String[] args) { 20 | VariablesScope01 v = new VariablesScope01(); 21 | v.method(5); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/basics/VariablesScope02.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class VariablesScope02 { 4 | 5 | public static void main(String[] args) { 6 | { 7 | int x = 5; { 8 | int y = 10; 9 | System.out.println(x); 10 | } 11 | } 12 | 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /core-java/basics/WideningPrimitiveConversion.java: -------------------------------------------------------------------------------- 1 | package basics; 2 | 3 | public class WideningPrimitiveConversion { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("Y" + "O"); 7 | System.out.println('A'); 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /core-java/collections/AbstractCollectionExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | import java.util.AbstractCollection; 5 | 6 | public class AbstractCollectionExample { 7 | 8 | public static void main(String[] args) { 9 | AbstractCollection abs1 = new TreeSet(); 10 | 11 | abs1.add("One"); 12 | abs1.add("Two"); 13 | abs1.add("Three"); 14 | 15 | System.out.println("AbstractCollection 1: " + abs1); 16 | 17 | AbstractCollection abs2 = new TreeSet(); 18 | 19 | abs2.addAll(abs1); 20 | 21 | System.out.println("Abstract Collection 2: " + abs2); 22 | 23 | abs1.clear(); 24 | 25 | System.out.println("AbstractCollection 1: " + abs1); 26 | 27 | System.out.println("Is the collection empty ? " + abs1.isEmpty()); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /core-java/collections/AbstractListExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | public class AbstractListExample { 5 | 6 | public static void main(String[] args) { 7 | AbstractList list = new LinkedList(); 8 | 9 | // Using add() method to add elements in the list 10 | list.add("Apple"); 11 | list.add("Banana"); 12 | list.add("Orange"); 13 | 14 | System.out.println("Abstract List: "+list); 15 | 16 | list.remove(2); 17 | System.out.println("Final AbstractList: " + list); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/collections/AbstractQueueExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.LinkedBlockingQueue; 5 | 6 | public class AbstractQueueExample { 7 | 8 | public static void main(String[] args) throws Exception { 9 | AbstractQueue AQ = new LinkedBlockingQueue(); 10 | 11 | AQ.add(10); 12 | AQ.add(20); 13 | AQ.add(30); 14 | 15 | System.out.println("AbstractQueue contains: " + AQ); 16 | System.out.println("Head: "+ AQ.element()); 17 | AQ.clear(); 18 | System.out.println("AbstractQueue: " + AQ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /core-java/collections/AbstractSetExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | public class AbstractSetExample { 6 | 7 | public static void main(String[] args) throws Exception { 8 | try { 9 | AbstractSet abs_set = new TreeSet(); 10 | 11 | abs_set.add(10); 12 | abs_set.add(20); 13 | abs_set.add(30); 14 | abs_set.add(40); 15 | abs_set.add(50); 16 | 17 | System.out.println("AbstractSet: " + abs_set); 18 | 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/collections/ArrayBlockingQueueExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | 5 | public class ArrayBlockingQueueExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | int capacity = 20; 10 | 11 | // Create object of ArrayBlockingQueue 12 | ArrayBlockingQueue BQ = new ArrayBlockingQueue(capacity); 13 | 14 | BQ.add(10); 15 | BQ.add(20); 16 | BQ.add(30); 17 | System.out.println("ArrayBlockingQueue: " + BQ); 18 | 19 | BQ.clear(); 20 | System.out.println("ArrayBlockingQueue: " + BQ); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /core-java/collections/ArrayDequeExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | public class ArrayDequeExample { 6 | 7 | public static void main(String[] args) { 8 | Deque de_que = new ArrayDeque(10); 9 | 10 | de_que.add(10); 11 | de_que.add(20); 12 | de_que.add(30); 13 | 14 | System.out.println("Elements: " + de_que); 15 | 16 | de_que.clear(); 17 | de_que.addFirst(100); 18 | de_que.addFirst(200); 19 | de_que.addLast(400); 20 | de_que.addLast(500); 21 | 22 | System.out.print("Using Iterator: "); 23 | for(Iterator itr = de_que.iterator(); itr.hasNext();){ 24 | System.out.print(itr.next() + ", "); 25 | } 26 | System.out.print("\nUsing Decending Iterator: "); 27 | for(Iterator ditr = de_que.descendingIterator(); ditr.hasNext();){ 28 | System.out.print(ditr.next() + ", "); 29 | } 30 | 31 | System.out.println("\nHead Element using element(): " + de_que.element()); 32 | System.out.println("Head Element using getFirst(): " + de_que.getFirst()); 33 | System.out.println("Last Element using getLast(): " + de_que.getLast()); 34 | System.out.println("Array Size: " + de_que.size()); 35 | System.out.println("Head Element using peek(): " + de_que.peek()); 36 | System.out.println("Head Element using poll(): " + de_que.poll()); 37 | System.out.println("Head Element remove: " + de_que.remove()); 38 | System.out.println("Final Arrays: " + de_que); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /core-java/collections/ArrayListExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class ArrayListExample { 7 | 8 | public static void main(String[] args) throws IOException { 9 | int size = 5; 10 | 11 | ArrayList arrlt = new ArrayList(size); 12 | 13 | for(int i = 1; i < size; i++){ 14 | arrlt.add(i); 15 | } 16 | 17 | System.out.println(arrlt); 18 | 19 | arrlt.remove(3); 20 | System.out.println(arrlt); 21 | 22 | for(int i = 0; i < arrlt.size(); i++){ 23 | System.out.println(arrlt.get(i) + " "); 24 | } 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /core-java/collections/ArrayListSynchronization.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | 8 | public class ArrayListSynchronization { 9 | 10 | public static void main(String[] args) { 11 | List list = Collections.synchronizedList(new ArrayList()); 12 | 13 | list.add("One"); 14 | list.add("Two"); 15 | list.add("Three"); 16 | 17 | synchronized(list) { 18 | Iterator itr = list.iterator(); 19 | System.out.println("Synchronized List: "); 20 | while(itr.hasNext()) { 21 | System.out.print(itr.next() + ", "); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/collections/ConcurrentLinkedDequeExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.*; 4 | 5 | public class ConcurrentLinkedDequeExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | ConcurrentLinkedDeque cld = new ConcurrentLinkedDeque(); 10 | 11 | cld.addFirst(100); 12 | cld.add(200); 13 | cld.addLast(300); 14 | 15 | System.out.println("ConcurrentLinedDeque: " + cld); 16 | System.out.println("The last element is: " + cld.getLast()); 17 | System.out.println("The first element is: " + cld.getFirst()); 18 | cld.removeLast(); 19 | System.out.println("ConcurrentLinedDeque: " + cld); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/collections/ConcurrentLinkedQueueExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.*; 4 | 5 | public class ConcurrentLinkedQueueExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue(); 10 | 11 | clq.add(10); 12 | clq.add(20); 13 | clq.add(30); 14 | clq.add(40); 15 | clq.add(50); 16 | 17 | // Display the existing LinkedQueue 18 | System.out.println("ConcurrentLinkedQueue: " + clq); 19 | 20 | // Display the first element 21 | System.out.println("First element is: "+ clq.peek()); 22 | 23 | // Remove the first element 24 | System.out.println("Head Element is: " + clq.poll()); 25 | 26 | // Display the existing LinkedQueue 27 | System.out.println("ConcurrentLinkedQueue: " + clq); 28 | 29 | // Get the size 30 | System.out.println("Size: " + clq.size()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/collections/CopyOnWriteArrayListExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.CopyOnWriteArrayList; 4 | import java.util.*; 5 | 6 | public class CopyOnWriteArrayListExample extends Thread { 7 | 8 | static CopyOnWriteArrayList l = new CopyOnWriteArrayList(); 9 | 10 | public void run() { 11 | // Child thread trying to add new element 12 | // in the Collection object 13 | l.add("D"); 14 | } 15 | 16 | public static void main(String[] args) throws InterruptedException { 17 | l.add("A"); 18 | l.add("B"); 19 | l.add("C"); 20 | 21 | // Create a child thread that modify ArrayList 22 | CopyOnWriteArrayListExample obj = new CopyOnWriteArrayListExample(); 23 | 24 | obj.start(); 25 | Thread.sleep(1000); 26 | 27 | Iterator itr = l.iterator(); 28 | while(itr.hasNext()) { 29 | String s = (String)itr.next(); 30 | System.out.print(s + " "); 31 | Thread.sleep(1000); 32 | } 33 | 34 | System.out.println(); 35 | System.out.println(l); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /core-java/collections/CopyOnWriteArraySetExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.*; 4 | import java.util.*; 5 | 6 | import com.lowagie.text.pdf.hyphenation.TernaryTree.Iterator; 7 | public class CopyOnWriteArraySetExample extends Thread { 8 | 9 | static CopyOnWriteArraySet l = new CopyOnWriteArraySet(); 10 | 11 | public void run() { 12 | l.add("D"); 13 | } 14 | public static void main(String[] args) { 15 | l.add("A"); 16 | l.add("B"); 17 | l.add("C"); 18 | 19 | // Child Thread 20 | CopyOnWriteArraySetExample t = new CopyOnWriteArraySetExample(); 21 | t.start(); 22 | 23 | try { 24 | Thread.sleep(2000); 25 | 26 | } catch (InterruptedException e) { 27 | System.out.println("Child is Going to add element"); 28 | } 29 | 30 | System.out.println(l); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/collections/DictionaryExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Dictionary; 4 | import java.util.Enumeration; 5 | import java.util.Hashtable; 6 | 7 | public class DictionaryExample { 8 | 9 | public static void main(String[] args) { 10 | Dictionary dictionary = new Hashtable(); 11 | 12 | dictionary.put(100, "Hello"); 13 | dictionary.put(101, "World"); 14 | 15 | // elements() method 16 | for(Enumeration i = dictionary.elements(); i.hasMoreElements();) { 17 | System.out.println("Value in Dictionary: " + i.nextElement()); 18 | } 19 | 20 | System.out.println("Value at key = 100: " + dictionary.get(100)); 21 | System.out.println("There is no key-value pair: " + dictionary.isEmpty()); 22 | 23 | // keys() method 24 | for(Enumeration k = dictionary.keys(); k.hasMoreElements();) { 25 | System.out.println("Keys in Dictionary: " + k.nextElement()); 26 | } 27 | 28 | System.out.println("Remove: " + dictionary.remove(100)); 29 | System.out.println("The value of remove key 100: " + dictionary.get(100)); 30 | System.out.println("Size of Dictionary: " + dictionary.size()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/collections/EnumSetExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.EnumSet; 4 | 5 | enum COLORS { 6 | RED, YELLOW, GREEN, BLUE, PINK, ORANGE 7 | }; 8 | public class EnumSetExample { 9 | 10 | public static void main(String[] args) { 11 | 12 | EnumSet set1, set2, set3, set4; 13 | 14 | set1 = EnumSet.of(COLORS.RED, COLORS.GREEN, COLORS.YELLOW); 15 | set2 = EnumSet.complementOf(set1); 16 | set3 = EnumSet.range(COLORS.RED, COLORS.BLUE); 17 | set4 = EnumSet.allOf(COLORS.class); 18 | 19 | System.out.println("Set 1: "+set1); 20 | System.out.println("Set 2: "+set2); 21 | System.out.println("Set 3: "+set3); 22 | System.out.println("Set 4: "+set4); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core-java/collections/EnumerationExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Enumeration; 4 | import java.util.Vector; 5 | 6 | public class EnumerationExample { 7 | 8 | public static void main(String[] args) { 9 | Vector v = new Vector(); 10 | for(int i = 0; i< 10; i++) { 11 | v.addElement(i); 12 | } 13 | System.out.println(v); 14 | 15 | Enumeration e = v.elements(); 16 | while(e.hasMoreElements()) { 17 | int i = (Integer)e.nextElement(); 18 | 19 | System.out.print(i + " "); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core-java/collections/HashMapExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.HashMap; 4 | 5 | class Key { 6 | String key; 7 | Key(String key) { 8 | this.key = key; 9 | } 10 | 11 | @Override 12 | public int hashCode() { 13 | int hash = (int)key.charAt(0); 14 | System.out.println("HashCode for Key: " + key + " = " + hash); 15 | return hash; 16 | } 17 | 18 | @Override 19 | public boolean equals(Object obj) { 20 | return key.equals(((Key)obj).key); 21 | } 22 | } 23 | 24 | public class HashMapExample { 25 | 26 | public static void main(String[] args) { 27 | HashMap map = new HashMap(); 28 | map.put(new Key("One"), 10); 29 | map.put(new Key("Two"), 20); 30 | map.put(new Key("Three"), 30); 31 | 32 | System.out.println("Value for key One: " + map.get(new Key("One"))); 33 | System.out.println("Value for key Two: " + map.get(new Key("Two"))); 34 | System.out.println("Value for key Three: " + map.get(new Key("Three"))); 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /core-java/collections/HashSetExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | public class HashSetExample { 6 | 7 | public static void main(String[] args) { 8 | HashSet hs = new HashSet(); 9 | 10 | hs.add("AAA"); 11 | hs.add("BBB"); 12 | hs.add("CCC"); 13 | hs.add("AAA"); 14 | hs.add("DDD"); 15 | 16 | System.out.println("HashSet: " + hs); 17 | System.out.println("List contains AAA? : " + hs.contains("AAA")); 18 | hs.remove("AAA"); 19 | System.out.print("Iterating over list: "); 20 | Iterator itr = hs.iterator(); 21 | 22 | while(itr.hasNext()){ 23 | System.out.print(itr.next() + " "); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /core-java/collections/HashSetMerge.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | public class HashSetMerge { 5 | 6 | public static Set mergeSet(Set a, Set b) { 7 | //Creating an empty set 8 | Set mergedSet = new HashSet(); 9 | mergedSet.addAll(a); 10 | mergedSet.addAll(b); 11 | 12 | return mergedSet; 13 | } 14 | public static void main(String[] args) { 15 | //First Set 16 | Set a = new HashSet(); 17 | a.addAll(Arrays.asList(new Integer[] {1, 3, 5, 7, 9})); 18 | 19 | //Second Set 20 | Set b = new HashSet(); 21 | b.addAll(Arrays.asList(new Integer[] {0, 2, 4, 6, 8})); 22 | 23 | System.out.println("Set a: "+ a); 24 | System.out.println("Set b: "+ b); 25 | System.out.println("Merged Set: "+ mergeSet(a, b)); 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /core-java/collections/HashtableExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | public class HashtableExample { 6 | 7 | public static void main(String[] args) { 8 | Map h = new Hashtable<>(); 9 | 10 | h.put(10, "One"); 11 | h.put(20, "Two"); 12 | h.put(30, "Three"); 13 | 14 | h.putIfAbsent(100, "Ten"); 15 | 16 | 17 | System.out.println("Hashtable: "+ h); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /core-java/collections/IdentityHashMapExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.HashMap; 4 | import java.util.IdentityHashMap; 5 | import java.util.Map; 6 | 7 | public class IdentityHashMapExample { 8 | 9 | public static void main(String[] args) { 10 | Map hm = new HashMap(); 11 | Map ihm = new IdentityHashMap(); 12 | 13 | hm.put(1, "Sunday"); 14 | hm.put(new String("Two"), "Monday"); 15 | ihm.put(3, "Tuesday"); 16 | ihm.put(new String("Four"), "Wednesday"); 17 | 18 | System.out.println("HashMap: "+ hm); 19 | System.out.println("IdentityHashMap: "+ ihm); 20 | System.out.println("Size of HashMap: "+ hm.size()); 21 | System.out.println("Size of IdentityHashMap: "+ ihm.size()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/collections/ImmutableListEample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | public class ImmutableListEample { 4 | 5 | public static void main(String[] args) { 6 | 7 | 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /core-java/collections/IterableToCollectionConversion.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | import java.util.Iterator; 7 | 8 | public class IterableToCollectionConversion { 9 | 10 | // function to convert Iterator into Collection 11 | public static Collection getCollectionFromIterable(Iterable itr) { 12 | Collection items = new ArrayList(); 13 | 14 | Iterator iterator = itr.iterator(); 15 | while(iterator.hasNext()) { 16 | items.add(iterator.next()); 17 | } 18 | 19 | return items; 20 | } 21 | public static void main(String[] args) { 22 | Iterable itr = Arrays.asList(1, 2, 3, 4, 5); 23 | System.out.println("Iterable List: " + itr); 24 | 25 | Collection cn = getCollectionFromIterable(itr); 26 | System.out.println("Collection List: " + cn); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /core-java/collections/IteratorExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | 6 | public class IteratorExample { 7 | 8 | public static void main(String[] args) { 9 | ArrayList al = new ArrayList(); 10 | 11 | for(int i = 0; i < 10; i++){ 12 | al.add(i); 13 | } 14 | System.out.println(al); 15 | 16 | Iterator itr = al.iterator(); 17 | 18 | while(itr.hasNext()) { 19 | int i = (Integer)itr.next(); 20 | 21 | System.out.print(i + ""); 22 | 23 | if(i % 2 != 0) itr.remove(); 24 | } 25 | System.out.println(); 26 | System.out.println(al); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /core-java/collections/LinkedBlockingDequeExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.LinkedBlockingDeque; 4 | 5 | public class LinkedBlockingDequeExample { 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | LinkedBlockingDeque LBD = new LinkedBlockingDeque(); 9 | 10 | LBD.add(11111); 11 | LBD.add(22222); 12 | LBD.add(33333); 13 | LBD.add(44444); 14 | LBD.add(55555); 15 | 16 | System.out.println("LinkedBlockingDeque: " + LBD); 17 | System.out.println("Size of Linked Blocking Deque: " + LBD.size()); 18 | System.out.println("First Element: " + LBD.removeFirst()); 19 | System.out.println("LinkedBlockingDeque: " + LBD); 20 | LBD.offer(66666); 21 | System.out.println("LinkedBlockingDeque: " + LBD); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/collections/LinkedBlockingQueueExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.LinkedBlockingQueue; 4 | 5 | public class LinkedBlockingQueueExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | LinkedBlockingQueue lbq = new LinkedBlockingQueue(); 10 | 11 | // add numbers 12 | lbq.add(10); 13 | lbq.add(20); 14 | lbq.add(30); 15 | 16 | System.out.println("LinkedBlockingQueue: " + lbq); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /core-java/collections/LinkedHashMapExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.LinkedHashMap; 4 | 5 | public class LinkedHashMapExample { 6 | 7 | public static void main(String[] args) { 8 | LinkedHashMap lhm = new LinkedHashMap(); 9 | 10 | lhm.put(1, "One"); 11 | lhm.put(2, "Two"); 12 | lhm.put(3, "Three"); 13 | lhm.put(4, "Four"); 14 | lhm.put(5, "Five"); 15 | 16 | System.out.println("LinedHashMap: " +lhm); 17 | System.out.println("Value of Key 1: " +lhm.get(1)); 18 | System.out.println("Size of LinedHashMap: " +lhm.size()); 19 | System.out.println("Is map empty: " +lhm.isEmpty()); 20 | System.out.println("Contains key 5: " +lhm.containsKey(5)); 21 | System.out.println("Delete element one: " +lhm.remove(1)); 22 | System.out.println("Final LinedHashMap: " +lhm); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core-java/collections/LinkedHashSetExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.LinkedHashSet; 4 | 5 | public class LinkedHashSetExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | LinkedHashSet linkedset = new LinkedHashSet(); 10 | 11 | linkedset.add("A"); 12 | linkedset.add("B"); 13 | linkedset.add("C"); 14 | linkedset.add("D"); 15 | linkedset.add("A"); //Duplicate element 16 | linkedset.add("E"); 17 | 18 | System.out.println("LinkedHashSet: " + linkedset); 19 | System.out.println("LinkedHashSet size: " + linkedset.size()); 20 | System.out.println("Removing D from LinkedHashSet: " + linkedset.remove("D")); 21 | System.out.println("Removing Z from LinkedHashSet: " + linkedset.remove("Z")); 22 | System.out.println("Checking if A is present in LinkedHashSet: " + linkedset.contains("A")); 23 | System.out.println("Final LinkedHashSet: " + linkedset); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/collections/LinkedListExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | 6 | public class LinkedListExample { 7 | 8 | public static void main(String[] args) { 9 | 10 | // Creating object of class linked list 11 | LinkedList object = new LinkedList(); 12 | 13 | // Adding elements to the linked list 14 | object.add("A"); 15 | object.add("B"); 16 | object.addLast("C"); 17 | object.addFirst("D"); 18 | object.add(2, "E"); 19 | object.add("F"); 20 | object.add("G"); 21 | object.add("H"); 22 | System.out.println("Linked List: "+ object); 23 | 24 | 25 | // Removing elements from the linked list 26 | object.remove("B"); 27 | object.remove(3); 28 | object.removeFirst(); 29 | object.removeLast(); 30 | System.out.println("Linked list after deletion: " + object); 31 | 32 | // Finding elements in the linked list 33 | boolean status = object.contains("E"); 34 | 35 | System.out.println("List contains the element E: " + status); 36 | 37 | // Number of elements in the linked list 38 | int size = object.size(); 39 | System.out.println("Size of linked list: " + size); 40 | 41 | // Get and set elements from linked list 42 | Object element = object.get(2); 43 | System.out.println("Element returned by get(): " + element); 44 | object.set(2, "Y"); 45 | System.out.println("Linked list after change: " + object); 46 | 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /core-java/collections/LinkedTransferQueueExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.concurrent.LinkedTransferQueue; 4 | public class LinkedTransferQueueExample { 5 | 6 | public static void main(String[] args) throws InterruptedException { 7 | 8 | LinkedTransferQueue LTQ = new LinkedTransferQueue(); 9 | 10 | LTQ.add(123456); 11 | LTQ.add(289537); 12 | LTQ.add(789239); 13 | LTQ.add(234298); 14 | LTQ.add(873928); 15 | 16 | System.out.println("Linked Tranfer Queue: " + LTQ); 17 | 18 | System.out.println("Size of Linked Transfer Queue: " + LTQ.size()); 19 | //Removes the front elements and prints it 20 | System.out.println("First element: " + LTQ.poll()); 21 | 22 | System.out.println("Linked Tranfer Queue: " + LTQ); 23 | 24 | // Add numbers to end 25 | LTQ.offer(20000); 26 | System.out.println("Linked Tranfer Queue: " + LTQ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /core-java/collections/ListIteratorExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.ArrayList; 4 | import java.util.ListIterator; 5 | 6 | public class ListIteratorExample { 7 | 8 | public static void main(String[] args) { 9 | ArrayList al = new ArrayList(); 10 | 11 | for(int i = 0; i < 10; i++) { 12 | al.add(i); 13 | } 14 | 15 | System.out.print(al); 16 | 17 | ListIterator itr = al.listIterator(); 18 | 19 | while(itr.hasNext()){ 20 | int i = (Integer)itr.next(); 21 | 22 | System.out.print(i + " "); 23 | 24 | if(i % 2 == 0) { 25 | i++; 26 | itr.set(i); 27 | itr.add(i); 28 | } 29 | } 30 | 31 | System.out.println(); 32 | System.out.println(al); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /core-java/collections/SortedMapExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Iterator; 4 | import java.util.Map; 5 | import java.util.Set; 6 | import java.util.SortedMap; 7 | import java.util.TreeMap; 8 | 9 | public class SortedMapExample { 10 | 11 | public static void main(String[] args) { 12 | SortedMap sm = new TreeMap(); 13 | 14 | sm.put(new Integer(2), "A"); 15 | sm.put(new Integer(3), "B"); 16 | sm.put(new Integer(5), "C"); 17 | sm.put(new Integer(4), "D"); 18 | sm.put(new Integer(1), "E"); 19 | 20 | Set s = sm.entrySet(); 21 | Iterator itr = s.iterator(); 22 | while(itr.hasNext()) { 23 | Map.Entry m = (Map.Entry)itr.next(); 24 | 25 | int key = (Integer)m.getKey(); 26 | String value = (String)m.getValue(); 27 | 28 | System.out.println("Key: " + key + " Value: " + value); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-java/collections/StackExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackExample { 6 | 7 | // Pushing element on the top of stack 8 | static void stack_push(Stack stack) { 9 | System.out.println("Push: "); 10 | for(int i = 0; i < 5; i++){ 11 | stack.push(i); 12 | System.out.print(i + ", "); 13 | } 14 | } 15 | // Popping element from the top of the stack 16 | static void stack_pop(Stack stack) { 17 | System.out.println("\nPop: "); 18 | 19 | for(int i = 0; i < 5; i++) { 20 | Integer y = (Integer) stack.pop(); 21 | System.out.print(y + ", "); 22 | } 23 | } 24 | 25 | // Displaying element on the top of the stack 26 | static void stack_peek(Stack stack) { 27 | Integer element = (Integer) stack.peek(); 28 | System.out.println("\nElement on stack top: " + element); 29 | } 30 | // Searching element in the stack 31 | static void stack_search(Stack stack, int element) { 32 | Integer pos = (Integer) stack.search(element); 33 | 34 | if(pos == -1){ 35 | System.out.println(element + " not found in stack " ); 36 | } else { 37 | System.out.println(element + " found at position: " + pos); 38 | } 39 | } 40 | public static void main(String[] args) { 41 | Stack stack = new Stack(); 42 | 43 | stack_push(stack); 44 | stack_pop(stack); 45 | stack_push(stack); 46 | stack_peek(stack); 47 | stack_search(stack, 2); 48 | stack_search(stack, 6); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /core-java/collections/WeakHashMapExample.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | import java.util.Set; 6 | import java.util.WeakHashMap; 7 | 8 | public class WeakHashMapExample { 9 | 10 | public static void main(String[] args) { 11 | Map weak = new WeakHashMap(); 12 | weak.put(1, "A"); 13 | weak.put(2, "B"); 14 | weak.put(3, "C"); 15 | 16 | Set set1 = weak.entrySet(); 17 | System.out.println("Set: "+set1); 18 | 19 | // Creating set for key 20 | Set keySet = weak.keySet(); 21 | System.out.println("Key Set: " + keySet); 22 | 23 | Collection value = weak.values(); 24 | System.out.println("Map Values: " + value); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-java/constructors/CopyConstructor.java: -------------------------------------------------------------------------------- 1 | package constructors; 2 | 3 | class Complex { 4 | private double re, im; 5 | 6 | public Complex(double re, double im) { 7 | this.re = re; 8 | this.im = im; 9 | } 10 | 11 | //copy constructor 12 | Complex(Complex c) { 13 | System.out.println("Copy constructor called"); 14 | re = c.re; 15 | im = c.im; 16 | } 17 | //Overrding the toString of Object class 18 | @Override 19 | public String toString() { 20 | return "(" + re + " + " + im + "i)"; 21 | } 22 | } 23 | 24 | public class CopyConstructor { 25 | 26 | public static void main(String[] args) { 27 | Complex c1 = new Complex(10, 20); 28 | 29 | // Following involves a copy constructor call 30 | Complex c2 = new Complex(c1); 31 | 32 | Complex c3 = c2; 33 | System.out.println(c2); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /core-java/constructors/PrivateConstructors.java: -------------------------------------------------------------------------------- 1 | package constructors; 2 | 3 | class MySingleton { 4 | 5 | static MySingleton instance = null; 6 | public int x = 10; 7 | 8 | // private constructor can't be accessed outside the class 9 | private MySingleton() { } 10 | 11 | // Factory method to provide the uses with instances 12 | static public MySingleton getInstance() { 13 | if(instance == null){ 14 | instance = new MySingleton(); 15 | } 16 | return instance; 17 | } 18 | } 19 | public class PrivateConstructors { 20 | 21 | public static void main(String[] args) { 22 | MySingleton a = MySingleton.getInstance(); 23 | MySingleton b = MySingleton.getInstance(); 24 | 25 | a.x = a.x + 10; 26 | System.out.println("Value of a.x = " + a.x); 27 | System.out.println("Value of b.x = " + b.x); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /core-java/exceptionhandling/ChainedExceptions.java: -------------------------------------------------------------------------------- 1 | package exceptionhandling; 2 | 3 | public class ChainedExceptions { 4 | 5 | public static void main(String[] args) { 6 | 7 | try { 8 | // Creating an expension 9 | NumberFormatException ex = new NumberFormatException("Exception"); 10 | 11 | // Setting a cause of the exception 12 | ex.initCause(new NullPointerException("This is actual cause of the exception")); 13 | 14 | // Throwing an exception with cause 15 | throw ex; 16 | } catch (NumberFormatException ex) { 17 | System.out.println("Exception: "+ex); 18 | 19 | // Getting the actual cause of the exception 20 | System.out.println(ex.getCause()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/exceptionhandling/OutOfMemoryErrorException.java: -------------------------------------------------------------------------------- 1 | package exceptionhandling; 2 | import java.util.*; 3 | 4 | public class OutOfMemoryErrorException { 5 | 6 | static List list = new ArrayList(); 7 | 8 | public static void main(String[] args) { 9 | Integer[] array = new Integer[10000 * 10000]; 10 | 11 | System.out.println(array); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /core-java/exceptionhandling/PrintException.java: -------------------------------------------------------------------------------- 1 | package exceptionhandling; 2 | 3 | public class PrintException { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | int n = 1; 8 | System.out.println(n/0); 9 | }catch (Exception e) { 10 | System.out.println(e.getMessage()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core-java/filehandling/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | package filehandling; 2 | 3 | /** 4 | * use HashSet to store each line of input.txt. 5 | * As set ignores duplicate values, so while storing a line, 6 | * check if it already present in hashset. Write it to output.txt 7 | * only if not present in hashset. 8 | */ 9 | 10 | import java.io.*; 11 | import java.util.HashSet; 12 | 13 | public class RemoveDuplicates { 14 | 15 | public static void main(String[] args) throws IOException { 16 | 17 | try ( 18 | PrintWriter pw = new PrintWriter("Output.txt"); 19 | BufferedReader br = new BufferedReader(new FileReader("file.txt"));) { 20 | String line = br.readLine(); 21 | 22 | // Set store unique values 23 | HashSet hs = new HashSet<>(); 24 | while(line != null) { 25 | if(hs.add(line)) { 26 | pw.println(line); 27 | } 28 | line = br.readLine(); 29 | } 30 | 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | 35 | System.out.println("File operation performed successfully"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /core-java/inheritance/AccessingGrandparentMember.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Grandparent { 4 | public void Print() { 5 | System.out.println("Grandparent's Print"); 6 | } 7 | } 8 | 9 | class Parent extends Grandparent { 10 | @Override 11 | public void Print() { 12 | super.Print(); 13 | System.out.println("Parent's Print"); 14 | } 15 | } 16 | 17 | class Child extends Parent { 18 | @Override 19 | public void Print() { 20 | super.Print(); 21 | System.out.println("Child Print"); 22 | } 23 | } 24 | 25 | public class AccessingGrandparentMember { 26 | 27 | public static void main(String[] args) { 28 | Child c = new Child(); 29 | c.Print(); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/inheritance/Inheritance01.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Base02 { 4 | private final void message() { 5 | System.out.println("Base Class Message"); 6 | } 7 | } 8 | public class Inheritance01 extends Base02 { 9 | 10 | public final void message() { 11 | System.out.println("Child Class Message"); 12 | } 13 | public static void main(String[] args) { 14 | new Inheritance01().message(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/inheritance/Inheritance02.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Base03 { 4 | static String s = ""; 5 | protected Base03() { 6 | s += " Base Class Message!\n"; 7 | } 8 | } 9 | 10 | class Child02 extends Base03 { 11 | private Child02() { 12 | s += " Child Class Message!\n"; 13 | } 14 | } 15 | 16 | public class Inheritance02 extends Base03 { 17 | 18 | private Inheritance02() { 19 | s += " Grand Child Class Message!\n"; 20 | } 21 | public static void main(String[] args) { 22 | new Inheritance02(); 23 | System.out.println(s); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/inheritance/OverloadingInInheritance.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Base01 { 4 | public int fun(int i) { 5 | System.out.println("Base Class fun"); 6 | return i + 3; 7 | } 8 | } 9 | class Derived01 extends Base01 { 10 | public double fun(double i) { 11 | System.out.println("Derived Class fun"); 12 | return i + 3.3; 13 | } 14 | } 15 | public class OverloadingInInheritance { 16 | 17 | public static void main(String[] args) { 18 | Derived01 obj = new Derived01(); 19 | System.out.println(obj.fun(3)); 20 | System.out.println(obj.fun(3.3)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core-java/inheritance/OverridePrivateMethods.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | 4 | public class OverridePrivateMethods { 5 | 6 | private String msg = "Hello World"; 7 | private void fun() { 8 | System.out.println("Outer function"); 9 | } 10 | 11 | class Inner extends OverridePrivateMethods { 12 | private void fun() { 13 | System.out.println("Accessing Private Member of Outer: "+ msg); 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | /** 19 | * In Order to create instance of Inner Class, we need an Outer 20 | * class instance. So, first create Outer class instance and then 21 | * Inner class instance. 22 | */ 23 | OverridePrivateMethods o = new OverridePrivateMethods(); 24 | Inner i = o.new Inner(); 25 | 26 | /** 27 | * This will call Inner's fun(), the purpose of this call is to 28 | * show that private members of Outer can be accessed in Inner 29 | */ 30 | i.fun(); 31 | // o.fun() calls Outer's fun 32 | o = i; 33 | o.fun(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /core-java/inheritance/ParentChildHavingSameDataMember.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Parent01 { 4 | int value = 10; 5 | Parent01() { 6 | System.out.println("Parent Constructor"); 7 | } 8 | } 9 | 10 | class Child01 extends Parent01 { 11 | int value = 20; 12 | Child01() { 13 | System.out.println("Child Constructor"); 14 | } 15 | } 16 | 17 | public class ParentChildHavingSameDataMember { 18 | 19 | public static void main(String[] args) { 20 | Child01 obj = new Child01(); 21 | System.out.println("Reference of Child type: " +obj.value); 22 | 23 | Parent01 par = obj; 24 | System.out.println("Reference of Parent Type: "+par.value); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-java/inheritance/RestrictiveAccessDerivedClass.java: -------------------------------------------------------------------------------- 1 | package inheritance; 2 | 3 | class Base { 4 | private void foo() { 5 | System.out.print("Base Class Method"); 6 | } 7 | } 8 | 9 | class Derived extends Base { 10 | public void foo() { 11 | System.out.print("Derived Class Method"); 12 | } 13 | } 14 | 15 | public class RestrictiveAccessDerivedClass { 16 | 17 | public static void main(String[] args) { 18 | Derived d = new Derived(); 19 | d.foo(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/input/output/ByteStream.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | public class ByteStream { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | try ( 12 | FileInputStream sourceStream = new FileInputStream("file.txt"); 13 | FileOutputStream targetStream = new FileOutputStream("target.txt"); ) { 14 | 15 | int temp; 16 | while((temp = sourceStream.read()) != -1) { 17 | targetStream.write((byte)temp); 18 | System.out.println("Writing into a file: " + (char)temp); 19 | } 20 | 21 | } catch(Exception e) { 22 | System.out.println("Exception: "+ e); 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-java/input/output/CharacterStream.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.io.FileReader; 4 | import java.io.IOException; 5 | 6 | /** 7 | * @author U6044324 8 | * Oct 31, 2018 9 | * 10 | * Java Program to read a file in a human readable 11 | * format using FileReader 12 | */ 13 | public class CharacterStream { 14 | 15 | public static void main(String[] args) throws IOException { 16 | 17 | try ( 18 | FileReader sourceStream = new FileReader("file.txt"); ) { 19 | 20 | // Readind sourcefile and writing content to 21 | // target file character by character. 22 | int temp; 23 | while((temp = sourceStream.read()) != -1){ 24 | System.out.print((char)temp); 25 | } 26 | } catch( Exception e) { 27 | System.out.println("Exception: " + e); 28 | e.printStackTrace(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-java/input/output/CommandLineArguments.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/core-java/input/output/CommandLineArguments.class -------------------------------------------------------------------------------- /core-java/input/output/CommandLineArguments.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | public class CommandLineArguments { 4 | 5 | public static void main(String[] args) { 6 | if(args.length > 0){ 7 | System.out.println("The Command line arguments are: "); 8 | for(String val: args) { 9 | System.out.println(val); 10 | } 11 | } else { 12 | System.out.println("No command line arguments found !"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /core-java/input/output/DoubleStreamExample01.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.util.*; 4 | import java.util.stream.*; 5 | import java.util.stream.DoubleStream; 6 | 7 | /** 8 | * 9 | * @author U6044324 10 | * Oct 31, 2018 11 | * 12 | * Using DoubleStream mapToObj(DoubleFunction mapper) 13 | * and displaying an object-value stream consisting 14 | * of the results of applying the given function 15 | */ 16 | public class DoubleStreamExample01 { 17 | 18 | public static void main(String[] args) { 19 | // Create a DoubleStream 20 | DoubleStream stream = DoubleStream.of(2, 3, 4, 5); 21 | 22 | stream.mapToObj(num ->{return num * num * num;}) 23 | .forEach(System.out::println); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/input/output/DoubleStreamExample02.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.stream.DoubleStream; 5 | import java.util.stream.Stream; 6 | 7 | public class DoubleStreamExample02 { 8 | 9 | public static void main(String[] args) { 10 | DoubleStream stream = DoubleStream.of(2, 3, 4, 5); 11 | 12 | Stream obj = stream.mapToObj(BigDecimal::valueOf); 13 | 14 | obj.forEach(num -> System.out.println(num.add(BigDecimal.TEN))); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/input/output/ScannerClass.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ScannerClass { 6 | 7 | public static void main(String[] args) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | 11 | // String input 12 | String name = sc.nextLine(); 13 | 14 | // Character Input 15 | char gender = sc.next().charAt(0); 16 | int age = sc.nextInt(); 17 | long mobileNo = sc.nextLong(); 18 | double cgpa = sc.nextDouble(); 19 | 20 | System.out.println("Name: " +name); 21 | System.out.println("Gender: " +gender); 22 | System.out.println("Age: "+age); 23 | System.out.println("Mobile Number: "+mobileNo); 24 | System.out.println("CGPA: "+cgpa); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-java/input/output/ScannerNextChar.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ScannerNextChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | 10 | char c = sc.next().charAt(0); 11 | 12 | System.out.println("First Character: " + c); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/input/output/ScannerVsBufferReader.java: -------------------------------------------------------------------------------- 1 | package input.output; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | 8 | public class ScannerVsBufferReader { 9 | 10 | public static void main(String[] args) throws IOException { 11 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 | System.out.println("Enter an integer: "); 13 | int a = Integer.parseInt(br.readLine()); 14 | System.out.println("Enter a String: "); 15 | String b = br.readLine(); 16 | System.out.println("You have entered integer: " + a + " and name: "+ b); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/interfaces/NestedClasses.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | class OuterClass { 4 | static int outer_x = 10; 5 | int outer_y = 20; 6 | 7 | private static int outer_private = 30; 8 | 9 | static class StaticNestedClass { 10 | void display(){ 11 | System.out.println("outer_x = " + outer_x); 12 | System.out.println("Outer_private = " + outer_private); 13 | } 14 | } 15 | } 16 | 17 | public class NestedClasses { 18 | 19 | public static void main(String[] args) { 20 | OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); 21 | nestedObject.display(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/interfaces/NestedInterface.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | 3 | class Test { 4 | interface nested { 5 | void show(); 6 | } 7 | } 8 | 9 | class Testing implements Test.nested { 10 | public void show() { 11 | System.out.println("Show method of interface"); 12 | } 13 | } 14 | 15 | public class NestedInterface { 16 | 17 | public static void main(String[] args) { 18 | Test.nested obj; 19 | Testing t = new Testing(); 20 | obj = t; 21 | obj.show(); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /core-java/keywords/ReferenceFinalVariable.java: -------------------------------------------------------------------------------- 1 | package keywords; 2 | 3 | public class ReferenceFinalVariable { 4 | 5 | public static void main(String[] args) { 6 | final StringBuilder sb = new StringBuilder("Hello "); 7 | 8 | System.out.println(sb); 9 | 10 | // Changing internal state of object 11 | sb.append("World !"); 12 | System.out.println(sb); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/keywords/StaticBlocks.java: -------------------------------------------------------------------------------- 1 | package keywords; 2 | 3 | public class StaticBlocks { 4 | 5 | // static varibales 6 | static int a = 10; 7 | static int b; 8 | 9 | static { 10 | System.out.println("Static block initialized."); 11 | b = a * 4; 12 | } 13 | public static void main(String[] args) { 14 | System.out.println("Value of a: " + a); 15 | System.out.println("Value of b: " + b); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/keywords/StaticMethod.java: -------------------------------------------------------------------------------- 1 | package keywords; 2 | 3 | public class StaticMethod { 4 | 5 | static void display() { 6 | System.out.println("Static Method called !"); 7 | } 8 | public static void main(String[] args) { 9 | // Calling method without creating any object of class 10 | display(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /core-java/keywords/StrictfpKeyword.java: -------------------------------------------------------------------------------- 1 | package keywords; 2 | 3 | public class StrictfpKeyword { 4 | 5 | public double calculate() { 6 | double num1 = 10e+102; 7 | double num2 = 6e+08; 8 | 9 | return (num1 * num2); 10 | } 11 | 12 | public static void main(String[] args) { 13 | StrictfpKeyword obj = new StrictfpKeyword(); 14 | System.out.println(obj.calculate()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/keywords/TransientKeyword.java: -------------------------------------------------------------------------------- 1 | package keywords; 2 | import java.io.*; 3 | 4 | public class TransientKeyword implements Serializable { 5 | 6 | int i = 10, j = 20; 7 | transient int k = 30; 8 | transient static int l = 40; 9 | transient final int m = 50; 10 | 11 | 12 | public static void main(String[] args) throws Exception { 13 | TransientKeyword input = new TransientKeyword(); 14 | 15 | //Serialization 16 | FileOutputStream fos = new FileOutputStream("file.txt"); 17 | ObjectOutputStream oos = new ObjectOutputStream(fos); 18 | oos.writeObject(input); 19 | 20 | //deserialization 21 | FileInputStream fis = new FileInputStream("file.txt"); 22 | ObjectInputStream ois = new ObjectInputStream(fis); 23 | TransientKeyword output = (TransientKeyword)ois.readObject(); 24 | System.out.println("i = " + output.i); 25 | System.out.println("j = " + output.j); 26 | System.out.println("k = " + output.k); 27 | System.out.println("l = " + output.l); 28 | System.out.println("m = " + output.m); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /core-java/methods/DeepCopy.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | /** 4 | * In the deep copy, we create a clone which is independent of original object and making changes in the cloned object should not affect original object. 5 | * So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class. 6 | */ 7 | import java.util.ArrayList; 8 | 9 | class DeepCopy1 { 10 | int x, y; 11 | } 12 | 13 | class DeepCopy2 implements Cloneable { 14 | int a, b; 15 | DeepCopy1 c = new DeepCopy1(); 16 | public Object clone() throws CloneNotSupportedException { 17 | DeepCopy2 t = (DeepCopy2)super.clone(); 18 | t.c = new DeepCopy1(); 19 | 20 | return t; 21 | } 22 | } 23 | 24 | public class DeepCopy { 25 | 26 | public static void main(String[] args) throws CloneNotSupportedException { 27 | DeepCopy2 t1 = new DeepCopy2(); 28 | t1.a = 10; 29 | t1.b = 20; 30 | t1.c.x = 30; 31 | t1.c.y = 40; 32 | 33 | DeepCopy2 t3 = (DeepCopy2)t1.clone(); 34 | t3.a = 100; 35 | t3.c.x = 300; 36 | 37 | System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " +t1.c.y); 38 | System.out.println(t3.a + " " + t3.b + " " + t3.c.x + " " + t3.c.y); 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /core-java/methods/FillInStackTraceMethod.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | public class FillInStackTraceMethod { 4 | 5 | public static void main(String[] args) throws Throwable { 6 | FillInStackTraceMethod obj = new FillInStackTraceMethod(); 7 | try { 8 | obj.showResult(); 9 | } catch (Exception e) { 10 | System.out.println("Exception: "+e); 11 | e.printStackTrace(); 12 | 13 | } 14 | 15 | } 16 | 17 | public void showResult() throws Throwable { 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /core-java/methods/PassByValue.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | class Test { 4 | int x; 5 | Test(int i) { x = i; } 6 | Test() { x = 0; } 7 | } 8 | public class PassByValue { 9 | 10 | 11 | public static void main(String[] args) { 12 | Test t = new Test(10); 13 | 14 | change(t); 15 | System.out.println("New Value :" + t.x); 16 | } 17 | 18 | public static void change(Test t) { 19 | t.x = 10; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/methods/ReturnListObjectClass.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ReturnListObjectClass { 7 | 8 | public static List getDetails() { 9 | String name = "Pradeep"; 10 | int age = 22; 11 | char gender = 'M'; 12 | 13 | return Arrays.asList(name, age, gender); 14 | } 15 | public static void main(String[] args) { 16 | List person = getDetails(); 17 | System.out.println(person); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/methods/ShallowCopy.java: -------------------------------------------------------------------------------- 1 | package methods; 2 | 3 | /** 4 | * Whenever we use default implementation of clone method we get shallow copy of 5 | * object means it creates new instance and copies all the field of object to that 6 | * new instance and returns it as object type, we need to explicitly cast it back 7 | * to our original object. This is shallow copy of the object. 8 | * 9 | */ 10 | 11 | import java.util.ArrayList; 12 | 13 | class ShallowCopy1 { 14 | int x, y; 15 | } 16 | 17 | class ShallowCopy2 implements Cloneable { 18 | int a, b; 19 | ShallowCopy1 c = new ShallowCopy1(); 20 | public Object clone() throws CloneNotSupportedException { 21 | return super.clone(); 22 | } 23 | } 24 | public class ShallowCopy { 25 | 26 | public static void main(String[] args) throws CloneNotSupportedException { 27 | ShallowCopy2 t1 = new ShallowCopy2(); 28 | t1.a = 10; 29 | t1.b = 20; 30 | t1.c.x = 30; 31 | t1.c.y = 40; 32 | 33 | ShallowCopy2 t2 = (ShallowCopy2)t1.clone(); 34 | 35 | t2.a = 100; 36 | t2.c.x = 300; 37 | 38 | System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y); 39 | System.out.println(t2.a + " " + t2.b + " " + t2.c.x + " " +t2.c.y); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /core-java/multithreading/CallableExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.FutureTask; 6 | 7 | public class CallableExample implements Callable { 8 | 9 | public Object call() throws Exception { 10 | Random generator = new Random(); 11 | Integer randomNumber = generator.nextInt(5); 12 | Thread.sleep(randomNumber * 100); 13 | 14 | return randomNumber; 15 | } 16 | 17 | public static void main(String args[]) throws Exception { 18 | FutureTask[] randomNumberTasks = new FutureTask[5]; 19 | 20 | for(int i = 0; i < 5; i++) { 21 | Callable callable = new CallableExample(); 22 | randomNumberTasks[i] = new FutureTask(callable); 23 | Thread t = new Thread(randomNumberTasks[i]); 24 | t.start(); 25 | } 26 | for(int i = 0; i < 5; i++){ 27 | System.out.println("FutureTask: "+randomNumberTasks[i].get()); 28 | } 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /core-java/multithreading/CountDownLatchExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | 5 | public class CountDownLatchExample { 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | 9 | CountDownLatch latch = new CountDownLatch(4); 10 | 11 | Worker first = new Worker(1000, latch, "WORKER-1"); 12 | Worker second = new Worker(2000, latch, "WORKER-2"); 13 | Worker third = new Worker(3000, latch, "WORKER-3"); 14 | Worker fourth = new Worker(4000, latch, "WORKER-4"); 15 | 16 | first.start(); 17 | second.start(); 18 | third.start(); 19 | fourth.start(); 20 | 21 | latch.wait(); // The main task waits for four threads 22 | System.out.println(Thread.currentThread().getName() + " has finised"); 23 | } 24 | } 25 | 26 | class Worker extends Thread { 27 | private int delay; 28 | private CountDownLatch latch; 29 | 30 | public Worker(int delay, CountDownLatch latch, String name) { 31 | super(name); 32 | this.delay = delay; 33 | this.latch = latch; 34 | } 35 | @Override 36 | public void run() { 37 | try { 38 | Thread.sleep(delay); 39 | latch.countDown(); 40 | System.out.println(Thread.currentThread().getName() + " finished"); 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /core-java/multithreading/DaemonThread.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class DaemonThread extends Thread { 4 | 5 | public DaemonThread(String name) { 6 | super(name); 7 | } 8 | 9 | public void run() { 10 | if(Thread.currentThread().isDaemon()) { 11 | System.out.println(getName() + " is Daemon thread"); 12 | } else { 13 | System.out.println(getName() + " is User Thread" ); 14 | } 15 | } 16 | public static void main(String[] args) { 17 | DaemonThread t1 = new DaemonThread("t1"); 18 | DaemonThread t2 = new DaemonThread("t2"); 19 | DaemonThread t3 = new DaemonThread("t3"); 20 | 21 | t1.setDaemon(true); 22 | t1.start(); 23 | t2.start(); 24 | t3.setDaemon(true); 25 | t3.start(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /core-java/multithreading/JoinExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class JoinExample implements Runnable { 4 | 5 | public void run() { 6 | Thread t = Thread.currentThread(); 7 | System.out.println("Current Thread: " + t.getName()); 8 | 9 | System.out.println("Is Alive? " + t.isAlive()); 10 | } 11 | public static void main(String[] args) { 12 | Thread t = new Thread(new JoinExample()); 13 | t.start(); 14 | 15 | try { 16 | // Waits for 1000ms this thread to die 17 | t.join(1000); 18 | } catch (Exception e) { 19 | System.out.print(e); 20 | } 21 | 22 | System.out.println("Current Thread: " + t.getName()); 23 | System.out.println("Is Alive? " + t.isAlive()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/multithreading/JoinMethod.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | import java.io.*; 4 | 5 | public class JoinMethod extends Thread { 6 | 7 | @Override 8 | public void run() { 9 | for(int i = 0; i < 5; i++) { 10 | try { 11 | Thread.sleep(500); 12 | System.out.println("Thread Start: " + Thread.currentThread().getName()); 13 | } catch (Exception e) { 14 | System.out.println("Exception: " + e); 15 | } 16 | } 17 | } 18 | public static void main(String[] args) { 19 | JoinMethod t1 = new JoinMethod(); 20 | JoinMethod t2 = new JoinMethod(); 21 | 22 | 23 | t1.start(); 24 | try { 25 | System.out.println("Thread Ends: " + Thread.currentThread().getName()); 26 | t1.join(); 27 | } catch (Exception e) { 28 | System.out.println("Exception: " + e); 29 | } 30 | 31 | t2.start(); 32 | try { 33 | System.out.println("Thread Ends: " + Thread.currentThread().getName()); 34 | t2.join(); 35 | } catch (Exception e) { 36 | System.out.println("Exception: " + e); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /core-java/multithreading/MultithreadingUsingRunnable.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class MultithreadingUsingRunnable implements Runnable { 4 | 5 | public void run() { 6 | try { 7 | System.out.println("Thread " +Thread.currentThread().getId() + " is running"); 8 | } catch (Exception e) { 9 | System.out.println("Exception is caught"); 10 | } 11 | } 12 | public static void main(String[] args) { 13 | 14 | for(int i = 0; i < 5; i++) { 15 | Thread obj = new Thread(new MultithreadingUsingRunnable()); 16 | obj.start(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/multithreading/MultithreadingUsingThread.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class MultithreadingUsingThread extends Thread { 4 | 5 | public void run() { 6 | try { 7 | sleep(1000); 8 | System.out.println("Thread " + Thread.currentThread().getId() + " is running"); 9 | 10 | } catch (Exception e) { 11 | System.out.println("Exception is caught"); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | 17 | for(int i = 0; i < 5; i++){ 18 | MultithreadingUsingThread obj = new MultithreadingUsingThread(); 19 | obj.start(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core-java/multithreading/RuntimeClass.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class RuntimeClass { 4 | 5 | public static void main(String[] args) { 6 | Runtime run = Runtime.getRuntime(); 7 | System.out.println("Current free Memory: " + run.freeMemory()); 8 | System.out.println("Total Memory in bytes: " + run.totalMemory()); 9 | System.out.println("Number of processors available: " + run.availableProcessors()); 10 | 11 | 12 | 13 | try { 14 | // Process process = Runtime.getRuntime().exec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"); 15 | System.out.println("Google Chrome successfully started "); 16 | } catch (Exception e) { 17 | e.printStackTrace(); 18 | } 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /core-java/multithreading/SleepExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class SleepExample implements Runnable { 4 | 5 | Thread t; 6 | public void run() { 7 | for(int i = 0; i < 5; i++) { 8 | System.out.println(Thread.currentThread().getName() + " " + i); 9 | 10 | try { 11 | Thread.sleep(1000); 12 | } catch (Exception e) { 13 | System.out.println(e); 14 | } 15 | } 16 | } 17 | public static void main(String[] args) { 18 | Thread t = new Thread(new SleepExample()); 19 | t.start(); 20 | 21 | Thread t2 = new Thread(new SleepExample()); 22 | t2.start(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core-java/multithreading/StartExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class StartExample extends Thread { 4 | 5 | public void run() { 6 | try { 7 | System.out.println("Thread " + Thread.currentThread().getId() + " is running"); 8 | } catch (Exception e) { 9 | System.out.println("Exception is caught: " + e); 10 | } 11 | } 12 | public static void main(String[] args) { 13 | 14 | for (int i = 0; i < 5; i++) { 15 | StartExample obj = new StartExample(); 16 | obj.start(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/multithreading/ThreadNaming.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class ThreadNaming extends Thread { 4 | 5 | @Override 6 | public void run() { 7 | System.out.println("Thread is running..."); 8 | } 9 | 10 | public static void main(String[] args) { 11 | 12 | ThreadNaming t1 = new ThreadNaming(); 13 | ThreadNaming t2 = new ThreadNaming(); 14 | 15 | System.out.println("Thread 1: "+ t1.getName()); 16 | System.out.println("Thread 2: "+ t2.getName()); 17 | 18 | t1.start(); 19 | t2.start(); 20 | 21 | t1.setName("One"); 22 | t2.setName("Two"); 23 | 24 | System.out.println("Thread 1 after change: " + t1.getName()); 25 | System.out.println("Thread 2 after change: " + t2.getName()); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /core-java/multithreading/ThreadPools.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | 8 | public class ThreadPools implements Runnable { 9 | 10 | private String name; 11 | 12 | public ThreadPools(String s) { 13 | name = s; 14 | } 15 | 16 | public void run() { 17 | try { 18 | for(int i = 0; i < 3; i++) { 19 | if(i == 0) { 20 | Date d = new Date(); 21 | SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); 22 | System.out.println("Initialization Time for task name: " + name + " = " + ft.format(d)); 23 | } else { 24 | Date d = new Date(); 25 | SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); 26 | System.out.println("Executing Time for task name: " + name + " = " + ft.format(d)); 27 | } 28 | Thread.sleep(1000); 29 | } 30 | System.out.println(name + " completed"); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | final int MAX_T = 3; 38 | 39 | Runnable r1 = new ThreadPools("task 1"); 40 | Runnable r2 = new ThreadPools("task 2"); 41 | Runnable r3 = new ThreadPools("task 3"); 42 | 43 | // Create a thread pool 44 | ExecutorService pool = Executors.newFixedThreadPool(MAX_T); 45 | 46 | pool.execute(r1); 47 | pool.execute(r2); 48 | pool.execute(r3); 49 | pool.shutdown(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /core-java/multithreading/ThreadPriority.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class ThreadPriority extends Thread { 4 | 5 | public void run() { 6 | System.out.println("Inside run method"); 7 | } 8 | public static void main(String[] args) { 9 | ThreadPriority t1 = new ThreadPriority(); 10 | ThreadPriority t2 = new ThreadPriority(); 11 | ThreadPriority t3 = new ThreadPriority(); 12 | 13 | System.out.println("Default t1 thread priority: " + t1.getPriority()); 14 | System.out.println("Default t2 thread priority: " + t2.getPriority()); 15 | System.out.println("Default t3 thread priority: " + t3.getPriority()); 16 | 17 | t1.setPriority(2); 18 | t2.setPriority(5); 19 | t3.setPriority(8); 20 | 21 | System.out.println("t1 thread priority: " + t1.getPriority()); 22 | System.out.println("t2 thread priority: " + t2.getPriority()); 23 | System.out.println("t3 thread priority: " + t3.getPriority()); 24 | System.out.println("Main thread priority: " + Thread.currentThread().getPriority()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-java/multithreading/YieldExample.java: -------------------------------------------------------------------------------- 1 | package multithreading; 2 | 3 | public class YieldExample extends Thread { 4 | 5 | public void run() { 6 | for(int i = 0; i < 5; i++) { 7 | System.out.println(Thread.currentThread().getName() + " in control"); 8 | } 9 | } 10 | 11 | public static void main(String[] args) { 12 | YieldExample t = new YieldExample(); 13 | t.start(); 14 | 15 | for(int i = 0; i < 5; i++){ 16 | // Control passes to child thread 17 | Thread.yield(); 18 | 19 | // After execution of child thread main thread execute 20 | System.out.println(Thread.currentThread().getName() + " in control"); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/Association.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Bank { 4 | private String name; 5 | Bank(String name) { 6 | this.name = name; 7 | } 8 | public String getBankName() { 9 | return this.name; 10 | } 11 | } 12 | 13 | class Employee { 14 | private String name; 15 | Employee(String name) { 16 | this.name = name; 17 | } 18 | public String getEmployee() { 19 | return this.name; 20 | } 21 | } 22 | 23 | public class Association { 24 | 25 | public static void main(String[] args) { 26 | Bank bank = new Bank("Axis Bank"); 27 | Employee emp = new Employee("Neha"); 28 | System.out.println(emp.getEmployee() + " is employee of " + bank.getBankName()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/ClassesAndObjects.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class ClassesAndObjects { 4 | 5 | String name; 6 | String breed; 7 | int age; 8 | String color; 9 | 10 | // Constructor Declaration of class 11 | public ClassesAndObjects(String name, String breed, int age, String color) { 12 | this.name = name; 13 | this.breed = breed; 14 | this.age = age; 15 | this.color = color; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public String getBreed() { 23 | return breed; 24 | } 25 | 26 | public int getAge() { 27 | return age; 28 | } 29 | 30 | public String getColor() { 31 | return color; 32 | } 33 | @Override 34 | public String toString() { 35 | return ("Hi my name is "+ this.getName() + "\nMy breed, age and color are: "+ this.getBreed()+ ", "+this.getAge()+ ", "+this.getColor()); 36 | } 37 | 38 | public static void main(String[] args) { 39 | ClassesAndObjects tuffy = new ClassesAndObjects("tuffy", "Papillon", 5, "White"); 40 | System.out.println(tuffy.toString()); 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/Composition.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class Book { 7 | public String title; 8 | public String author; 9 | 10 | Book(String title, String author) { 11 | this.title = title; 12 | this.author = author; 13 | } 14 | } 15 | 16 | class Library { 17 | private final List books; 18 | 19 | Library(List books){ 20 | this.books = books; 21 | } 22 | 23 | public List getTotalBooksInLibrary() { 24 | return books; 25 | } 26 | } 27 | 28 | public class Composition { 29 | 30 | public static void main(String[] args) { 31 | Book b1 = new Book("Effective Java", "Joshua Bloch"); 32 | Book b2 = new Book("Thinking in Java", "Bruce Eckel"); 33 | Book b3 = new Book("Java: The Complete Reference", "Herbet Schildt"); 34 | 35 | // Creating the list which contains the no of books. 36 | List books = new ArrayList(); 37 | books.add(b1); 38 | books.add(b2); 39 | books.add(b3); 40 | 41 | Library library = new Library(books); 42 | List bks = library.getTotalBooksInLibrary(); 43 | for(Book bk: bks) { 44 | System.out.println("Title: "+bk.title + " and "+ "Author: "+bk.author); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/CovariantReturnTypes.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | //Java program to demonstrate that we can have 4 | //different return types if return type in 5 | //overridden method is sub-type 6 | 7 | class X {} 8 | class Y extends X {} 9 | 10 | class BaseX { 11 | X fun() { 12 | System.out.println("Base fun()"); 13 | return new X(); 14 | } 15 | } 16 | class DerivedY extends BaseX { 17 | Y fun() { 18 | System.out.println("Derived fun()"); 19 | return new Y(); 20 | } 21 | } 22 | 23 | public class CovariantReturnTypes { 24 | 25 | public static void main(String[] args) { 26 | BaseX base = new BaseX(); 27 | base.fun(); 28 | 29 | DerivedY derived = new DerivedY(); 30 | derived.fun(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/CreateObjectsUsingClone.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class CreateObjectsUsingClone implements Cloneable { 4 | 5 | @Override 6 | protected Object clone() throws CloneNotSupportedException { 7 | return super.clone(); 8 | } 9 | String name = "Hello world!"; 10 | public static void main(String[] args) { 11 | CreateObjectsUsingClone obj1 = new CreateObjectsUsingClone(); 12 | try { 13 | CreateObjectsUsingClone obj2 = (CreateObjectsUsingClone) obj1.clone(); 14 | System.out.println(obj2.name); 15 | } catch (CloneNotSupportedException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/CreateObjectsUsingDeserialization.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.ObjectOutputStream; 5 | import java.io.Serializable; 6 | 7 | public class CreateObjectsUsingDeserialization implements Serializable { 8 | 9 | private String name; 10 | CreateObjectsUsingDeserialization(String name) { 11 | this.name = name; 12 | } 13 | 14 | public static void main(String[] args) { 15 | 16 | try ( 17 | FileOutputStream fos = new FileOutputStream("file.txt"); 18 | ObjectOutputStream oos = new ObjectOutputStream(fos); 19 | ) { 20 | CreateObjectsUsingDeserialization d = new CreateObjectsUsingDeserialization("Hello World!"); 21 | oos.writeObject(d); 22 | } catch ( Exception e) { 23 | e.printStackTrace(); 24 | } 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/CreateObjectsUsingNew.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class CreateObjectsUsingNew { 4 | 5 | String name = "Hello World!"; 6 | public static void main(String[] args) { 7 | CreateObjectsUsingNew obj = new CreateObjectsUsingNew(); 8 | System.out.println("Message: "+obj.name); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/CreateObjectsUsingNewInstance.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class CreateObjectsUsingNewInstance { 4 | 5 | String name = "Hello World!"; 6 | public static void main(String[] args) { 7 | try { 8 | Class cls = Class.forName("oopsconcepts.CreateObjectsUsingNewInstance"); 9 | CreateObjectsUsingNewInstance obj = (CreateObjectsUsingNewInstance) cls.newInstance(); 10 | System.out.println(obj.name); 11 | } catch (ClassNotFoundException e) { 12 | e.printStackTrace(); 13 | } catch (InstantiationException e) { 14 | e.printStackTrace(); 15 | } catch (IllegalAccessException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/DynamicBinding.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class DynamicBinding { 4 | 5 | public static class SupperClass { 6 | void print() { 7 | System.out.println("Print in Super Class"); 8 | } 9 | } 10 | public static class SubClass extends SupperClass { 11 | @Override 12 | void print() { 13 | System.out.println("Print in Sub Class"); 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | SupperClass A = new SupperClass(); 19 | SupperClass B = new SubClass(); 20 | A.print(); 21 | B.print(); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/Finalize.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class Finalize { 4 | 5 | public static void main(String[] args) { 6 | Finalize f = new Finalize(); 7 | System.out.println(f.hashCode()); 8 | f = null; 9 | // Calling garbage collector 10 | System.gc(); 11 | System.out.println("End"); 12 | } 13 | @Override 14 | protected void finalize() { 15 | System.out.println("Finalize method called"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/InstanceVariableHiding.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class InstanceClass { 4 | private int value = 10; 5 | void method() { 6 | int value = 40; 7 | System.out.println("Value of Instance varibale: "+this.value); 8 | System.out.println("Value of Local varibale: "+ value); 9 | } 10 | } 11 | 12 | public class InstanceVariableHiding { 13 | 14 | public static void main(String[] args) { 15 | InstanceClass obj = new InstanceClass(); 16 | obj.method(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/JavaLangObject.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class JavaLangObject { 4 | 5 | public static void main(String[] args) { 6 | Object y; 7 | 8 | y = 'A'; 9 | System.out.println(y.getClass().getName()); 10 | 11 | y = "Hello"; 12 | System.out.println(y.getClass().getName()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/ObjectCreationOfInheritedClass.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Fruit { 4 | public Fruit() { 5 | System.out.println("Super Class Constructor"); 6 | System.out.println("Super Class object hascode: " + this.hashCode()); 7 | System.out.println(this.getClass().getName()); 8 | } 9 | } 10 | 11 | class Apple extends Fruit { 12 | public Apple() { 13 | System.out.println("Subclass Constructor invoked"); 14 | System.out.println("Sub Class Object hascode: "+ this.hashCode()); 15 | System.out.println(this.hashCode() + " "+ super.hashCode()); 16 | System.out.println(this.getClass().getName() + " "+ super.getClass().getName()); 17 | } 18 | } 19 | 20 | public class ObjectCreationOfInheritedClass { 21 | 22 | public static void main(String[] args) { 23 | Apple obj = new Apple(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverloadMain.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class OverloadMain { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("Normal Main()"); 7 | OverloadMain.main("Hi"); 8 | } 9 | public static void main(String arg1) { 10 | System.out.println(arg1); 11 | OverloadMain.main("Hello", "Hello World!"); 12 | } 13 | public static void main(String arg1, String arg2){ 14 | System.out.println(arg1 +", "+ arg2); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverloadingTest.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class OverloadingTest { 4 | private String function(String temp, int data) { 5 | return "Hi"; 6 | } 7 | public final static String function(int data, String temp) { 8 | return "Hello"; 9 | } 10 | public static void main(String[] args) { 11 | OverloadingTest obj = new OverloadingTest(); 12 | System.out.println(obj.function(4, "Call")); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverrideStaticMethods.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Base { 4 | public static void display() { 5 | System.out.println("Static method from Base"); 6 | } 7 | public void print() { 8 | System.out.println("Non-static method from Base"); 9 | } 10 | } 11 | 12 | class Derived extends Base { 13 | public static void display() { 14 | System.out.print("Static method from Derived"); 15 | } 16 | public void print() { 17 | System.out.print("Non-Static method from Derived"); 18 | } 19 | } 20 | 21 | public class OverrideStaticMethods { 22 | 23 | public static void main(String[] args) { 24 | Base obj = new Derived(); 25 | obj.display(); 26 | obj.print(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/Overriding01.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Parent { 4 | void show() { 5 | System.out.print("Parent Class"); 6 | } 7 | } 8 | 9 | class Child extends Parent { 10 | @Override 11 | void show() { 12 | super.show(); 13 | System.out.println("\nChild Class"); 14 | } 15 | } 16 | public class Overriding01 { 17 | 18 | public static void main(String[] args) { 19 | Parent obj = new Child(); 20 | obj.show(); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverridingEquals.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Complex { 4 | private double re, im; 5 | public Complex(double re, double im) { 6 | this.re = re; 7 | this.im = im; 8 | } 9 | @Override 10 | public boolean equals(Object o) { 11 | if(o == this) { 12 | return true; 13 | } 14 | 15 | if(!(o instanceof Complex)) { 16 | return false; 17 | } 18 | 19 | Complex c = (Complex) o; 20 | return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0; 21 | } 22 | } 23 | 24 | public class OverridingEquals { 25 | 26 | public static void main(String[] args) { 27 | Complex c1 = new Complex(10, 15); 28 | Complex c2 = new Complex(10, 15); 29 | if(c1.equals(c2)) { 30 | System.out.println("Equal"); 31 | } else { 32 | System.out.println("Not Equal"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverridingExceptionHandling.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Parent1 { 4 | void show() throws RuntimeException { 5 | System.out.println("Parent Class"); 6 | } 7 | } 8 | 9 | class Child1 extends Parent1 { 10 | void show() throws ArithmeticException { 11 | System.out.println("Child Class"); 12 | } 13 | } 14 | 15 | public class OverridingExceptionHandling { 16 | 17 | public static void main(String[] args) { 18 | Parent1 obj = new Child1(); 19 | obj.show(); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/OverridingToString.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class Comp { 4 | private double re, im; 5 | 6 | public Comp(double re, double im) { 7 | this.re = re; 8 | this.im = im; 9 | } 10 | 11 | /** 12 | * Returns the String representation of this Complex number 13 | * The format of String is "Re + iIm" where Re is real part 14 | * and iIm is imaginary part. 15 | */ 16 | 17 | @Override 18 | public String toString() { 19 | return String.format(re + " + i" +im); 20 | } 21 | } 22 | 23 | public class OverridingToString { 24 | 25 | public static void main(String[] args) { 26 | Comp c1 = new Comp(10, 15); 27 | System.out.println(c1); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/ReflectionExample.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | import java.lang.reflect.Constructor; 4 | 5 | public class ReflectionExample { 6 | 7 | private String name; 8 | public void setName(String name) { 9 | this.name = name; 10 | } 11 | public static void main(String[] args) { 12 | try { 13 | Constructor constructor = ReflectionExample.class.getDeclaredConstructor(); 14 | ReflectionExample r = constructor.newInstance(); 15 | r.setName("Hello World!"); 16 | System.out.println(r.name); 17 | } catch (Exception e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/RuntimePolymorphism.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class A { 4 | int x = 10; 5 | } 6 | 7 | class B extends A { 8 | int x = 20; 9 | } 10 | 11 | public class RuntimePolymorphism { 12 | 13 | public static void main(String[] args) { 14 | A obj = new B(); 15 | System.out.println(obj.x); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/StaticBinding.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class StaticBinding { 4 | 5 | public static class SupperClass { 6 | static void print() { 7 | System.out.println("Print in Supper Class"); 8 | } 9 | } 10 | public static class SubClass extends SupperClass { 11 | static void print() { 12 | System.out.println("Print in Sub Class"); 13 | } 14 | } 15 | public static void main(String[] args) { 16 | SupperClass A = new SupperClass(); 17 | SupperClass B = new SubClass(); 18 | A.print(); 19 | B.print(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/StaticClass.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | class OuterClass { 4 | private static String msg = "Hello Java"; 5 | 6 | // Static nested class 7 | public static class NestedStaticClass { 8 | // Only static members of Outer class is directly accessible in nested static class 9 | public void printMessage() { 10 | System.out.println("Message from nested static class: " + msg); 11 | } 12 | } 13 | // non-static nested class - also called Inner class 14 | public class InnerClass { 15 | // Both static and non-static members of Outer class are accessible in this Inner class 16 | public void display() { 17 | System.out.println("Message from non-static nested class: " + msg); 18 | } 19 | } 20 | } 21 | 22 | public class StaticClass { 23 | 24 | public static void main(String[] args) { 25 | OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); 26 | 27 | printer.printMessage(); 28 | OuterClass outer = new OuterClass(); 29 | OuterClass.InnerClass inner = outer.new InnerClass(); 30 | 31 | inner.display(); 32 | OuterClass.InnerClass innerObject = new OuterClass().new InnerClass(); 33 | innerObject.display(); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/SwapObjectsUsingWrapperClass.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | /** 4 | * Java Program to demonstrate that we can use wrapper 5 | * classes to swap objects 6 | * 7 | */ 8 | 9 | class Car { 10 | int model, no; 11 | Car(int model, int no) { 12 | this.model = model; 13 | this.no = no; 14 | } 15 | void print() { 16 | System.out.println("Class = "+no+ ", model = "+ model); 17 | } 18 | } 19 | 20 | class CarWrapper { 21 | Car c; 22 | CarWrapper(Car c) { this.c = c; } 23 | } 24 | public class SwapObjectsUsingWrapperClass { 25 | 26 | public static void swap(CarWrapper cw1, CarWrapper cw2) { 27 | Car temp = cw1.c; 28 | cw1.c = cw2.c; 29 | cw2.c = temp; 30 | } 31 | public static void main(String[] args) { 32 | Car c1 = new Car(101, 1); 33 | Car c2 = new Car(202, 2); 34 | CarWrapper cw1 = new CarWrapper(c1); 35 | CarWrapper cw2 = new CarWrapper(c2); 36 | 37 | swap(cw1, cw2); 38 | cw1.c.print(); 39 | cw2.c.print(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/thisAsMethodParameter.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class thisAsMethodParameter { 4 | 5 | int a, b; 6 | thisAsMethodParameter() { 7 | a = 10; 8 | b = 20; 9 | } 10 | void display(thisAsMethodParameter obj) { 11 | System.out.println("a = " + a + " b = " +b); 12 | } 13 | void get() { 14 | display(this); 15 | } 16 | 17 | public static void main(String[] args) { 18 | thisAsMethodParameter obj = new thisAsMethodParameter(); 19 | obj.get(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/thisToInvokeCurrentClassConstructor.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class thisToInvokeCurrentClassConstructor { 4 | 5 | int a, b; 6 | // Default constructor 7 | thisToInvokeCurrentClassConstructor() { 8 | this(10, 20); 9 | System.out.println("Inside default constructor \n"); 10 | } 11 | 12 | thisToInvokeCurrentClassConstructor(int a, int b) { 13 | this.a = a; 14 | this.b = b; 15 | System.out.println("Inside parameterized constructor"); 16 | } 17 | 18 | public static void main(String[] args) { 19 | thisToInvokeCurrentClassConstructor obj = new thisToInvokeCurrentClassConstructor(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/thisToInvokeCurrentClassMethod.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class thisToInvokeCurrentClassMethod { 4 | 5 | void display() { 6 | this.show(); 7 | System.out.println("Inside display method"); 8 | } 9 | void show() { 10 | System.out.println("Inside show method"); 11 | } 12 | 13 | public static void main(String[] args) { 14 | thisToInvokeCurrentClassMethod obj = new thisToInvokeCurrentClassMethod(); 15 | obj.display(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/thisToReferCurrentClassInstanceVariables.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class thisToReferCurrentClassInstanceVariables { 4 | 5 | int a, b; 6 | thisToReferCurrentClassInstanceVariables(int a, int b) { 7 | this.a = a; 8 | this.b = b; 9 | } 10 | void display() { 11 | System.out.println("a = "+ a + " b = "+b); 12 | } 13 | public static void main(String[] args) { 14 | thisToReferCurrentClassInstanceVariables obj = new thisToReferCurrentClassInstanceVariables(10, 20); 15 | obj.display(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-java/oopsconcepts/thisToReturnCurrentClassInstance.java: -------------------------------------------------------------------------------- 1 | package oopsconcepts; 2 | 3 | public class thisToReturnCurrentClassInstance { 4 | 5 | int a, b; 6 | 7 | thisToReturnCurrentClassInstance() { 8 | a = 10; 9 | b = 20; 10 | } 11 | thisToReturnCurrentClassInstance get() { 12 | return this; 13 | } 14 | 15 | void display() { 16 | System.out.println("a = " + a + " b = "+b); 17 | } 18 | 19 | public static void main(String[] args) { 20 | thisToReturnCurrentClassInstance obj = new thisToReturnCurrentClassInstance(); 21 | obj.get().display(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/operators/AdditionAndConcatenation.java: -------------------------------------------------------------------------------- 1 | package operators; 2 | 3 | public class AdditionAndConcatenation { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println(2 + 0 + 1 + 8 + "Hello"); 8 | System.out.println("Hello" + 2 + 0 + 1 + 8); 9 | System.out.println(2 + 0 + 1 + 6 + "Hello" + 2 + 0 + 1 + 8); 10 | System.out.println(2 + 0 + 1 + 6 + "Hello" + ( 2 + 0 + 1 + 8)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /core-java/operators/AutoboxedIntegerObjects.java: -------------------------------------------------------------------------------- 1 | package operators; 2 | 3 | public class AutoboxedIntegerObjects { 4 | 5 | public static void main(String[] args) { 6 | Integer x = new Integer(10), y = new Integer(10); 7 | if(x == y) { 8 | System.out.println("Values are same"); 9 | } else { 10 | System.out.println("Values are not same"); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core-java/strings/CharactersSearch.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class CharactersSearch { 4 | 5 | public static void main(String[] args) { 6 | String str = "Hello World"; 7 | 8 | int fi = str.indexOf('o'); 9 | System.out.println("First occurence of char 's' is found at: " + fi ); 10 | 11 | int li = str.lastIndexOf('o'); 12 | System.out.println("Last occurence of char 's' is found at: " + li ); 13 | 14 | int fo = str.indexOf('o', 4); 15 | System.out.println("First occurence of char 's' is found at 4: " + fo); 16 | 17 | int char_at = str.charAt(0); // ASCII Value of H 18 | System.out.println("Character at location 20: " + char_at); 19 | 20 | CharSequence seq = "World"; 21 | boolean val = str.contains(seq); 22 | System.out.println("Found World ?: "+ val); 23 | 24 | // Substring search 25 | System.out.println("'Hello' found in String: " + str.startsWith("Hello")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /core-java/strings/CheckAlphabetsInString.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class CheckAlphabetsInString { 4 | 5 | public static boolean isStringContainsAlphabet(String str) { 6 | return ((str != null) && (!str.equals("") && (str.chars().allMatch(Character::isLetter)))); 7 | } 8 | 9 | public static void main(String[] args) { 10 | String str = "Hello"; 11 | System.out.println("Input: "+str); 12 | System.out.println("Output: "+isStringContainsAlphabet(str)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-java/strings/CompareStrings.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class CompareStrings { 4 | 5 | public static void main(String[] args) { 6 | String s1 = "Ram"; 7 | String s2 = "Ram"; 8 | String s3 = new String("Ram"); 9 | String s4 = new String("Ram"); 10 | String s5 = "Shyam"; 11 | String s6 = null; 12 | String s7 = null; 13 | 14 | try { 15 | 16 | System.out.println("\nComparing String with equals(): "); 17 | System.out.println(s1.equals(s2)); 18 | System.out.println(s1.equals(s3)); 19 | System.out.println(s3.equals(s4)); 20 | //System.out.println(s6.equals(s7)); // NullPointerException 21 | 22 | System.out.println("\nComparing String with ==:"); 23 | System.out.println(s1 == s2); 24 | System.out.println(s1 == s3); 25 | System.out.println(s1 == s4); 26 | System.out.println(s6 == s7); 27 | 28 | System.out.println("\nComparing String with compareTo():"); 29 | System.out.println(s1.compareTo(s3)); 30 | System.out.println(s1.compareTo(s5)); 31 | //System.out.println(s6.compareTo(s7)); // NullPointerException 32 | 33 | } catch (Exception e) { 34 | System.out.println("Exception: " + e); 35 | e.printStackTrace(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /core-java/strings/ListRemoveIf.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.function.Predicate; 7 | 8 | public class ListRemoveIf { 9 | 10 | public static List 11 | removeElements(List l, Predicate p) { 12 | 13 | // Removing nulls using Java Stream 14 | // using Predicate condition in removeIf() 15 | l.removeIf(x -> p.test(x)); 16 | 17 | return l; 18 | 19 | } 20 | 21 | public static void main(String[] args) { 22 | List l = new ArrayList<>( 23 | Arrays.asList("Geeks", 24 | null, 25 | "forGeeks", 26 | null, 27 | "A computer portal")); 28 | System.out.println("List with null values: "+l); 29 | 30 | Predicate isNull = i -> (i == null); 31 | 32 | l = removeElements(l, isNull); 33 | System.out.println("List with null values removed: " + l ); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /core-java/strings/ListUsingLambdas.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Predicate; 6 | import java.util.stream.Collectors; 7 | 8 | public class ListUsingLambdas { 9 | 10 | public static List 11 | removeElements(List l, Predicate p) { 12 | 13 | l = l.stream() 14 | .filter(p) 15 | .collect(Collectors.toList()); 16 | 17 | return l; 18 | 19 | } 20 | 21 | public static void main(String[] args) { 22 | List l = new ArrayList<>( 23 | Arrays.asList("Geeks", 24 | null, 25 | "forGeeks", 26 | null, 27 | "A counputer portal")); 28 | 29 | System.out.println("List with null values: "+l); 30 | 31 | // Creating a Predicate condition checking for null 32 | Predicate isNull = i -> (i == null); 33 | l = removeElements(l, isNull); 34 | 35 | System.out.println("List with null values removed: " + l); 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /core-java/strings/RemoveLeadingZeros.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class RemoveLeadingZeros { 4 | 5 | public static String removeZero(String str) { 6 | int i = 0; 7 | while(str.charAt(i) == '0') i++; 8 | 9 | // Convert str into StringBuffer as Strings are immutable 10 | StringBuffer sb = new StringBuffer(str); 11 | 12 | sb.replace(0, i, ""); 13 | return sb.toString(); 14 | } 15 | 16 | public static void main(String[] args) { 17 | String str = "0000087243"; 18 | str = removeZero(str); 19 | System.out.println(str); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /core-java/strings/SplitMethod.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class SplitMethod { 4 | 5 | public static void main(String[] args) { 6 | String str = "geekss@for@geekss"; 7 | String str2 = "word1, word2 word3@word4?word5.word6"; 8 | 9 | String[] arrOfStr = str.split("@", 2); 10 | String[] arrOfStr2 = str.split("[, ?.@]+"); 11 | 12 | for (String a: arrOfStr2) { 13 | System.out.println(a); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/strings/StringBufferAppendCodePoint.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringBufferAppendCodePoint { 4 | 5 | public static void main(String[] args) { 6 | StringBuffer obj = new StringBuffer("Hello World"); 7 | 8 | obj.appendCodePoint(115); // ASCII value of 's' 9 | System.out.println("After appending codePoint: " +obj); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /core-java/strings/StringBufferDeleteCharAt.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringBufferDeleteCharAt { 4 | 5 | public static void main(String[] args) { 6 | StringBuffer obj = new StringBuffer("Hello Worlds"); 7 | 8 | obj.deleteCharAt(11); 9 | System.out.println("After deletion of character: " + obj); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /core-java/strings/StringBufferMethods.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringBufferMethods { 4 | 5 | public static void main(String[] args) { 6 | 7 | StringBuffer str = new StringBuffer("Hello"); 8 | 9 | int len = str.length(); 10 | System.out.println("Length of String Hello: " + len); 11 | 12 | int cap = str.capacity(); 13 | System.out.println("Capacity of String Hello: " + cap); 14 | 15 | str.append(" World"); 16 | System.out.println("Appended String: " + str); 17 | 18 | str.insert(5, " for"); 19 | System.out.println("After Insert String: " + str); 20 | 21 | str.insert(0, 5); 22 | System.out.println("After inserting 5 at first position: "+str); 23 | 24 | str.insert(3, true); 25 | System.out.println("After inseting true at 3rd position: "+ str); 26 | 27 | char arr[] = {'p', 'r', 'a', 'd', 'e', 'e', 'p'}; 28 | 29 | // insert character array at offset 9 30 | str.insert(0, arr); 31 | System.out.println(str); 32 | 33 | str.reverse(); 34 | System.out.println("Reverse String: " + str); 35 | 36 | str.delete(0, 5); 37 | System.out.println("After Delete: " + str); 38 | 39 | str.deleteCharAt(7); 40 | System.out.println("After delete: " + str); 41 | 42 | str.replace(5, 8, "Happy"); 43 | System.out.println("After Replace: "+str); 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /core-java/strings/StringBuilderAndStringBufferClass.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | /** 3 | * @author U6044324 4 | * Oct 23, 2018 5 | * 6 | * Java program to demonstrate difference between String, 7 | * StringBuilder and StringBuffer 8 | */ 9 | 10 | public class StringBuilderAndStringBufferClass { 11 | 12 | // Concatenates to String 13 | public static void concat1(String s1) { 14 | s1 = s1 + "forgeeks"; 15 | } 16 | 17 | // Concatenates to StringBuilder 18 | public static void concat2(StringBuilder s2) { 19 | s2.append("forgeeks"); 20 | } 21 | 22 | // Concatenates to StringBuffer 23 | public static void concat3(StringBuffer s3) { 24 | s3.append("forgeeks"); 25 | } 26 | 27 | public static void main(String[] args) { 28 | String s1 = "Geeks"; 29 | concat1(s1); 30 | System.out.println("String: " + s1); 31 | 32 | StringBuilder s2 = new StringBuilder("Geeks"); 33 | concat2(s2); 34 | System.out.println("StringBuilder: " + s2); 35 | 36 | StringBuffer s3 = new StringBuffer("Geeks"); 37 | concat3(s3); 38 | System.out.println("StringBuffer: " + s3); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /core-java/strings/StringBuilderAndStringBufferClass02.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | /** 3 | * @author U6044324 4 | * Oct 23, 2018 5 | * 6 | * Java program to demonstrate conversion from 7 | // String to StringBuffer and StringBuilder. 8 | */ 9 | public class StringBuilderAndStringBufferClass02 { 10 | 11 | public static void main(String[] args) { 12 | String str = "Geeks"; 13 | 14 | // Conversion from String object to StringBuffer 15 | StringBuffer sbr = new StringBuffer(str); 16 | sbr.reverse(); 17 | System.out.println(sbr); 18 | 19 | // Conversion from String Object to StringBuilder 20 | StringBuilder sbl = new StringBuilder(str); 21 | sbl.append("ForGeeks"); 22 | System.out.println(sbl); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core-java/strings/StringBuilderAndStringBufferClass03.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | /** 3 | * @author U6044324 4 | * Oct 23, 2018 5 | * 6 | * Java program to demonstrate conversion from 7 | * String to StringBuffer and StringBuilder. 8 | */ 9 | public class StringBuilderAndStringBufferClass03 { 10 | 11 | public static void main(String[] args) { 12 | StringBuffer sbr = new StringBuffer("Hello"); 13 | StringBuilder sbdr = new StringBuilder("World"); 14 | 15 | // Conversion from StringBuffer object to String 16 | String str = sbr.toString(); 17 | System.out.println("\nStringBuffer object to String: "); 18 | System.out.println(str); 19 | 20 | // Conversion from StringBuilder object to String 21 | String str1 = sbdr.toString(); 22 | System.out.println("\nStringBuilder object to String: "); 23 | System.out.println(str1); 24 | 25 | sbr.append("ForGeeks"); 26 | System.out.println(sbr); 27 | System.out.println(str); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /core-java/strings/StringCompare.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.Objects; 4 | 5 | public class StringCompare { 6 | 7 | public static void main(String[] args) { 8 | String str1 = "Hello"; 9 | String str2 = "World"; 10 | String str3 = "hello"; 11 | String str4 = new String("Hello"); 12 | 13 | System.out.println("Comparing " + str1 + " and " + str2 + " : " + str1.equals(str2)); // false 14 | System.out.println("Comparing " + str1 + " and " + str3 + " : " + str1.equalsIgnoreCase(str3)); // true 15 | System.out.println("Comparing " + str1 + " and " + str4 + " : " + Objects.equals(str1, str4)); // true 16 | System.out.println("Comparing " + str1 + " and " + str4 + " : " + str1.compareTo(str4)); // 0 17 | System.out.println("Comparing " + str1 + " and " + str4 + " : " + (str1 == str4)); // false 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core-java/strings/StringContainsAlphabets.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringContainsAlphabets { 4 | 5 | public static boolean isStringContainsAlphabets(String str) { 6 | if(str == null || str.equals("")) { 7 | return false; 8 | } 9 | for(int i = 0; i < str.length(); i++) { 10 | char ch = str.charAt(i); 11 | if ((!(ch >= 'A' && ch <= 'Z')) && (!(ch >= 'a' && ch <= 'z'))) { 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | public static void main(String[] args) { 19 | 20 | String str = "HelloWorld"; 21 | System.out.println("Input: "+ str); 22 | System.out.println("Output: " + isStringContainsAlphabets(str)); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-java/strings/StringContainsAlphabetsRegx.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringContainsAlphabetsRegx { 4 | 5 | public static boolean isStringContainsAlpabets(String str) { 6 | return ((str !=null) 7 | && (!str.equals("") 8 | && (str.matches("^[a-zA-Z]*$")))); 9 | } 10 | 11 | public static void main(String[] args) { 12 | String str = "HelloWorld"; 13 | System.out.println("Input: " + str); 14 | System.out.println("Output: "+ isStringContainsAlpabets(str)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-java/strings/StringJoinerClass.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.ArrayList; 4 | import java.util.StringJoiner; 5 | 6 | public class StringJoinerClass { 7 | 8 | public static void main(String[] args) { 9 | ArrayList a1 = new ArrayList<>(); 10 | 11 | a1.add("Ram"); 12 | a1.add("Shyam"); 13 | a1.add("Alice"); 14 | a1.add("Bob"); 15 | 16 | StringJoiner sj1 = new StringJoiner(", "); 17 | 18 | // SetEmptyValue() method 19 | sj1.setEmptyValue("sj1 is empty"); 20 | System.out.println(sj1); 21 | 22 | // add() method 23 | sj1.add(a1.get(0)).add(a1.get(1)); 24 | System.out.println(sj1); 25 | 26 | // length method 27 | System.out.println("Length of string: " + sj1.length()); 28 | 29 | StringJoiner sj2 = new StringJoiner(" : "); 30 | sj2.add(a1.get(2)).add(a1.get(3)); 31 | 32 | // merge() method 33 | sj1.merge(sj2); 34 | 35 | // toString() method 36 | System.out.println(sj1.toString()); 37 | System.out.println("Length of new string: " + sj1.length()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /core-java/strings/StringToLowerCase.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.Locale; 4 | 5 | public class StringToLowerCase { 6 | 7 | public static void main(String[] args) { 8 | String s = "I Know YOU BuT You Don't Know ME."; 9 | 10 | Locale TURKISH = Locale.forLanguageTag("tr"); 11 | Locale ENGLISH = Locale.forLanguageTag("en"); 12 | 13 | String str1 = s.toLowerCase(TURKISH); 14 | String str2 = s.toLowerCase(ENGLISH); 15 | System.out.println("String LowerCase: "+ str1); 16 | System.out.println("String LowerCase: "+ str2); 17 | 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /core-java/strings/StringTokenizerClass.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.StringTokenizer; 4 | /** 5 | * StringTokenizer class in Java is used to break a string into tokens. 6 | * @author U6044324 7 | * Oct 23, 2018 8 | */ 9 | 10 | public class StringTokenizerClass { 11 | 12 | public static void main(String[] args) { 13 | System.out.println("\nUsing Constructor 1: "); 14 | StringTokenizer st1 = new StringTokenizer("Hello Geeks How are you", " "); 15 | 16 | while(st1.hasMoreTokens()) { 17 | System.out.println(st1.nextToken()); 18 | } 19 | 20 | System.out.println("\nUsing Constructor 2: "); 21 | StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :"); 22 | 23 | while(st2.hasMoreTokens()) { 24 | System.out.println(st2.nextToken()); 25 | } 26 | 27 | System.out.println("\nUsing Constructor 3: "); 28 | StringTokenizer st3 = new StringTokenizer("JAVA : Code : String" , " :", true); 29 | 30 | while(st3.hasMoreTokens()) { 31 | System.out.println(st3.nextToken()); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /core-java/strings/StringsToIntegerConversions.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringsToIntegerConversions { 4 | 5 | public static void main(String[] args) { 6 | int d = Integer.parseInt("20"); 7 | int sp = Integer.parseInt("+20"); 8 | int sn = Integer.parseInt("-20"); 9 | int r = Integer.parseInt("20", 16); // (2)*16^1 + (0)*16^0 = 32 10 | int str = Integer.parseInt("A", 12); // Output 10 11 | 12 | System.out.println("Decimal Number: " +d ); 13 | System.out.println("Signed Positive Number: " +sp); 14 | System.out.println("Signed Negative Number: "+sn); 15 | System.out.println("Radix Number: "+r); 16 | System.out.println("String Number: "+str); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-java/strings/SwapTwoStrings.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class SwapTwoStrings { 4 | 5 | public static void main(String[] args) { 6 | String a = "Hello"; 7 | String b = "World"; 8 | 9 | System.out.println("String before swap: a = "+ a + " and b = " + b); 10 | 11 | a = a + b; 12 | b = a.substring(0, a.length() - b.length()); 13 | 14 | // Store initial string b in String a 15 | a = a.substring(b.length()); 16 | 17 | // print String after swapping 18 | System.out.println("String after swap: a = "+ a + " and b = " + b); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /core-java/strings/ToStringMethod.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class ToStringMethod { 4 | 5 | public static void main(String[] args) { 6 | String obj = new String("Hello World"); 7 | System.out.println("String Value: " + obj); 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /core-java/wrapperclasses/NumberClass.java: -------------------------------------------------------------------------------- 1 | package wrapperclasses; 2 | 3 | public class NumberClass { 4 | 5 | public static void main(String[] args) { 6 | Double d = new Double("6.9685"); 7 | 8 | byte b = d.byteValue(); 9 | Integer i = new Integer("10"); 10 | 11 | System.out.println("After conversion to byte: " + b); // 6 12 | System.out.println("Compare: " + i.compareTo(7)); // 1 >> greater 13 | System.out.println("Compare: " + i.compareTo(11)); // -1 >> less 14 | System.out.println("Compare: " + i.compareTo(10)); // 0 >> equal 15 | System.out.println("Equals: " + i.equals(10)); // true 16 | System.out.println("ParseInt: " + Integer.parseInt("101", 2)); // 5 17 | System.out.println("ParseInt: " + Integer.toBinaryString(10)); // 1010 18 | System.out.println("ParseInt: " + Integer.valueOf(33)); // 33 19 | System.out.println("Letter Character Class: "+ Character.isLetter('A')); // true 20 | System.out.println("Digit Character Class: "+ Character.isDigit('0')); // true 21 | System.out.println("Whitespace Character Class: "+ Character.isWhitespace('9')); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-java/wrapperclasses/PrimitiveWrapperClasse.java: -------------------------------------------------------------------------------- 1 | package wrapperclasses; 2 | 3 | public class PrimitiveWrapperClasse { 4 | 5 | private static void modify(Integer i) { 6 | i = i + 1; 7 | } 8 | public static void main(String[] args) { 9 | Integer i = new Integer(12); 10 | System.out.println("Before Modification: "+i); 11 | modify(i); 12 | System.out.println("After Modification: "+i); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java-programs/ArrayListToArray.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class ArrayListToArray { 8 | 9 | public static void main(String[] args) { 10 | List list = new ArrayList<>(); 11 | list.add("Apple"); 12 | list.add("Banana"); 13 | list.add("Mango"); 14 | System.out.println("Converting ArrayList to Array: "); 15 | String[] item = list.toArray(new String[list.size()]); 16 | for (String s : item) { 17 | System.out.println(s); 18 | } 19 | System.out.println("Converting Array to ArrayList: "); 20 | List list2 = new ArrayList<>(); 21 | list2 = Arrays.asList(item); 22 | System.out.println(list2); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/ArraySort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Arrays; 3 | /** 4 | * Note:- 5 | * java.util.Arrays uses quicksort for primitive types such as int and 6 | * mergesort for objects that implement Comparable or use a Comparator. 7 | */ 8 | public class ArraySort { 9 | 10 | public static void main(String[] args) { 11 | String[] countries = {"India","United States","Malaysia","Australia","Lundon"}; 12 | Arrays.sort(countries); 13 | for(int i = 0; i < countries.length; i++) { 14 | System.out.println(countries[i]); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java-programs/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Steps:- 4 | * Bubble Sort algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. 5 | * 6 | */ 7 | public class BubbleSort { 8 | 9 | public void bubbleSort(int[] arr) { 10 | boolean swap; 11 | int n = arr.length; 12 | int tmp = 0; 13 | for (int i = 0; i < n ; i++) { 14 | swap = false; 15 | for (int j = 1; j < n-i; j++) { 16 | if (arr[j-1] > arr[j]) { 17 | tmp = arr[j]; 18 | arr[j] = arr[j-1]; 19 | arr[j-1] = tmp; 20 | swap = true; 21 | } 22 | } 23 | if (!swap){ 24 | break; 25 | } 26 | } 27 | } 28 | 29 | void printArray(int arr[]) { 30 | for (int i = 0; i < arr.length; i++) { 31 | System.out.print(arr[i] + " "); 32 | } 33 | System.out.println(""); 34 | } 35 | 36 | public static void main(String[] args) { 37 | BubbleSort obj = new BubbleSort(); 38 | int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; 39 | 40 | obj.bubbleSort(arr); 41 | System.out.println("Sorted Array"); 42 | obj.printArray(arr); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java-programs/BucketSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Arrays; 3 | /** 4 | * Bucket Sort is also known as bin sort. 5 | * It works by distributing the element into the array also called buckets. 6 | * 7 | */ 8 | public class BucketSort { 9 | 10 | public static int[] bucketSort(int[] arr) { 11 | int i, j; 12 | int[] bucket = new int[arr.length + 1]; 13 | Arrays.fill(bucket, 0); 14 | 15 | for(i = 0; i < arr.length; i++) { 16 | bucket[arr[i]]++; 17 | } 18 | int k = 0; 19 | for(i = 0; i <= arr.length; i++) { 20 | for(j = 0; j < bucket[i]; j++) { 21 | arr[k++] = i; 22 | } 23 | } 24 | return arr; 25 | } 26 | public static void main(String[] args) { 27 | int[] num = {3, 6, 1, 7, 2, 8, 10, 4, 9, 5}; 28 | bucketSort(num); 29 | for(int i = 0; i < num.length; i++) { 30 | System.out.print(num[i] + " "); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java-programs/CheckNumberInString.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class CheckNumberInString { 4 | 5 | public static void main(String[] args) { 6 | String str = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s."; 7 | Boolean flag = false; 8 | for(int i = 0; i < str.length(); i++) { 9 | flag = Character.isDigit(str.charAt(i)); 10 | if(flag) { 11 | System.out.println(str + "\n ==> contains number"); break; 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java-programs/CollectionSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | /** 7 | * Java Program to Sort a List using Collections.Sort methods 8 | * This implementation uses merge sort. 9 | * 10 | */ 11 | public class CollectionSort { 12 | 13 | public static void main(String[] args) { 14 | 15 | List list = new ArrayList<>(); 16 | list.add("India"); 17 | list.add("India"); 18 | list.add("United States"); 19 | list.add("Malaysia"); 20 | list.add("Australia"); 21 | list.add("Lundon"); 22 | 23 | Collections.sort(list); 24 | Iterator itr = list.iterator(); 25 | while(itr.hasNext()) { 26 | System.out.println(itr.next()); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java-programs/ConvertArrayListToStringArray.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class ConvertArrayListToStringArray { 6 | public static void main(String args[]) { 7 | List list = new ArrayList(); 8 | 9 | list.add("One"); 10 | list.add("Two"); 11 | list.add("Three"); 12 | list.add("Four"); 13 | list.add("Five"); 14 | 15 | String[] stringArrayObject = new String[list.size()]; 16 | list.toArray(stringArrayObject); 17 | 18 | for(String str: stringArrayObject) { 19 | System.out.print(str + ", "); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java-programs/ConvertCollectionToSynchronizedCollection.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | 8 | public class ConvertCollectionToSynchronizedCollection { 9 | 10 | public static void main(String[] args) { 11 | List syncList = Collections.synchronizedList(new ArrayList()); 12 | 13 | syncList.add("one"); 14 | syncList.add("two"); 15 | syncList.add("three"); 16 | 17 | synchronized (syncList) { 18 | Iterator iterator = syncList.iterator(); 19 | while (iterator.hasNext()) { 20 | System.out.println("Item: " + iterator.next()); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/ConvertLowerToUpperCase.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class ConvertLowerToUpperCase { 4 | 5 | public static void toLowerCase(String str) { 6 | for (int i = 0; i < str.length(); i++) { 7 | char character = str.charAt(i); 8 | if (character >= 65 && character <= 90) { 9 | character = (char) ((character + 32)); 10 | } 11 | System.out.print(character); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | String str = "HELLO WORLD"; 17 | toLowerCase(str); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java-programs/CountCharactersInFile.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | 9 | public class CountCharactersInFile { 10 | 11 | public static void main(String[] args) throws IOException { 12 | File file = new File("file.txt"); 13 | FileInputStream fis = new FileInputStream(file); 14 | InputStreamReader input = new InputStreamReader(fis); 15 | BufferedReader reader = new BufferedReader(input); 16 | 17 | String line; 18 | int countWord = 0; 19 | int sentenceCount = 0; 20 | int characterCount = 0; 21 | int paragraphCount = 1; 22 | int whitespaceCount = 0; 23 | 24 | while((line = reader.readLine()) != null) { 25 | if(line.equals("")) { 26 | paragraphCount++; 27 | } 28 | if(!(line.equals(""))) { 29 | characterCount += line.length(); 30 | String[] wordList = line.split("\\s+"); 31 | countWord += wordList.length; 32 | whitespaceCount += countWord - 1; 33 | String[] sentenceList = line.split("[!?.:]+"); 34 | sentenceCount += sentenceList.length; 35 | } 36 | } 37 | System.out.println("Total word count = " + countWord); 38 | System.out.println("Total number of sentences = " + sentenceCount); 39 | System.out.println("Total number of characters = " + characterCount); 40 | System.out.println("Number of paragraphs = " + paragraphCount); 41 | System.out.println("Total number of whitespaces = " + whitespaceCount); 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /java-programs/CountingSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Arrays; 3 | /** 4 | * Counting sort is used to sort elements between specific range. 5 | * Counting sort calculates the number of occurrence of objects and stores its key values. 6 | * New array is formed by adding previous key elements and assigning to objects. 7 | * It can only sort an integer array or number array e.g. short, byte or char array. 8 | * 9 | */ 10 | public class CountingSort { 11 | 12 | public static void countingSort(int[] input, int k) { 13 | int counter[] = new int[k + 1]; 14 | // fill bucket 15 | for(int i : input) { 16 | counter[i]++; 17 | } 18 | // sort array 19 | int ndx = 0; 20 | for(int i = 0; i < counter.length; i++) { 21 | while( 0 < counter[i]) { 22 | input[ndx++] = i; 23 | counter[i]--; 24 | } 25 | } 26 | } 27 | public static void main(String[] args) { 28 | int[] input = { 60, 40, 30, 20, 10, 40, 30, 60, 60, 20, 40, 30, 40 }; 29 | int k = 60; 30 | System.out.println("Integer array before sorting: " + Arrays.toString(input)); 31 | countingSort(input, k); 32 | System.out.println("Integer array after sorting: " + Arrays.toString(input)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java-programs/CreateDeadlockBetweenTwoThreads.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | /** 4 | * Description:- 5 | * Deadlock describes a situation where two or more threads are 6 | * blocked forever, waiting for each other. Deadlocks can occur in Java when the 7 | * synchronized keyword causes the executing thread to block while waiting to 8 | * get the lock, associated with the specified object. 9 | * 10 | */ 11 | public class CreateDeadlockBetweenTwoThreads { 12 | 13 | String str1 = "Hello"; 14 | String str2 = "World"; 15 | 16 | Thread t1 = new Thread("First Thread") { 17 | public void run() { 18 | while (true) { 19 | synchronized (str1) { 20 | synchronized (str2) { 21 | System.out.println(str1 + " " + str2); 22 | } 23 | } 24 | } 25 | } 26 | }; 27 | Thread t2 = new Thread("Second Thread") { 28 | public void run() { 29 | while (true) { 30 | synchronized (str2) { 31 | synchronized (str1) { 32 | System.out.println(str2 + " " + str1); 33 | } 34 | } 35 | } 36 | } 37 | }; 38 | 39 | public static void main(String[] args) { 40 | CreateDeadlockBetweenTwoThreads obj = new CreateDeadlockBetweenTwoThreads(); 41 | obj.t1.start(); 42 | obj.t2.start(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/PrintingLCS.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class PrintingLCS { 6 | 7 | public static String commonLCS(String txt1, String txt2) { 8 | String result = ""; 9 | int n = txt1.length(); 10 | int m = txt2.length(); 11 | 12 | int[][] dp = new int[n + 1][m + 1]; 13 | for (int i = 0; i < n + 1; i++) { 14 | for (int j = 0; j < m + 1; j++) { 15 | if (i == 0 || j == 0) { 16 | dp[i][j] = 0; 17 | } else { 18 | if (txt1.charAt(i - 1) == txt2.charAt(j - 1)) { 19 | dp[i][j] = dp[i - 1][j - 1] + 1; 20 | } else { 21 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 22 | } 23 | } 24 | } 25 | } 26 | 27 | print(dp); 28 | 29 | if(dp[n][m] == 0) { 30 | return result; 31 | } 32 | 33 | int i = n; 34 | int j = m; 35 | 36 | while(i > 0 && j > 0) { 37 | if(dp[i][j] > dp[i - 1][j] && dp[i][j] > dp[i][j - 1]) { 38 | result = txt1.charAt(i - 1) + result; 39 | i--; 40 | j--; 41 | }else { 42 | if(dp[i][j] == dp[i][j - 1]) { 43 | j--; 44 | }else { 45 | i--; 46 | } 47 | } 48 | } 49 | 50 | return result; 51 | } 52 | 53 | public static void print(int[][] dp) { 54 | for (int i = 0; i < dp.length; i++) { 55 | System.out.println(Arrays.toString(dp[i])); 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | // TODO Auto-generated method stub 61 | System.out.println(commonLCS("MZJAWXU","XMJYAUZ")); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/editDistance.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class editDistance { 4 | 5 | public static int eD(String s1, String s2, int n, int m) { 6 | 7 | if (m == 0) { 8 | return n; 9 | } 10 | 11 | if (n == 0) { 12 | return m; 13 | } 14 | 15 | if (s1.charAt(n - 1) == s2.charAt(m - 1)) { 16 | return eD(s1, s2, n - 1, m - 1); 17 | } else { 18 | return 1 + Math.min(eD(s1, s2, m, n - 1), Math.min(eD(s1, s2, m - 1, n), eD(s1, s2, n - 1, m - 1))); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | // TODO Auto-generated method stub 24 | // SATUR 25 | // SU 26 | 27 | System.out.println(eD("SATURDAY", "SUNDAY", 8, 6)); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/editDistanceOptimized.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class editDistanceOptimized { 4 | 5 | public static int eD(String s1, String s2, int n, int m) { 6 | 7 | int[][] dp = new int[n + 1][m + 1]; 8 | 9 | for (int i = 0; i < n + 1; i++) { 10 | for (int j = 0; j < m + 1; j++) { 11 | if (i == 0) { 12 | dp[i][j] = j; 13 | } else if (j == 0) { 14 | dp[i][j] = i; 15 | } else { 16 | if (s1.charAt(i - 1) == s2.charAt(j - 1)) { 17 | dp[i][j] = dp[i - 1][j - 1]; 18 | } else { 19 | dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); 20 | } 21 | } 22 | } 23 | } 24 | 25 | return dp[n][m]; 26 | } 27 | 28 | public static void main(String[] args) { 29 | // TODO Auto-generated method stub 30 | System.out.println(eD("SATURDAY", "SUNDAY", 8, 6)); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/eggDroppingPuzzle.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class eggDroppingPuzzle { 6 | 7 | public static int eggDrop(int e, int f) { 8 | if (f == 0 || f == 1) { 9 | return f; 10 | } 11 | 12 | if (e == 1) { 13 | return f; 14 | } 15 | 16 | int res = Integer.MAX_VALUE; 17 | for (int i = 1; i <= f; i++) { 18 | res = Math.min(res, Math.max(eggDrop(e - 1, i - 1), eggDrop(e, f - i))); 19 | } 20 | 21 | return res + 1; 22 | } 23 | 24 | public static int optimize(int egg, int floor) { 25 | int[][] dp = new int[egg + 1][floor + 1]; 26 | 27 | for(int i = 0; i <= egg; i++) { 28 | for(int j = 0; j <= floor; j++) { 29 | if(i == 0 || j == 0) { 30 | dp[i][j] = 0; 31 | }else if(i == 1) { 32 | dp[i][j] = j; 33 | }else if(j == 1) { 34 | dp[i][j] = 1; 35 | }else { 36 | int res; 37 | int min = Integer.MAX_VALUE; 38 | for(int x = 1; x <= j; x++) { 39 | res = Math.max(dp[i - 1][x - 1], dp[i][j - x]); 40 | min = Math.min(min, res); 41 | } 42 | 43 | dp[i][j] = min + 1; 44 | } 45 | } 46 | } 47 | 48 | print(dp); 49 | return dp[egg][floor]; 50 | } 51 | 52 | public static void print(int[][] arr) { 53 | for(int i = 0; i < arr.length; i++) { 54 | System.out.println(Arrays.toString(arr[i])); 55 | } 56 | } 57 | 58 | public static void main(String[] args) { 59 | // TODO Auto-generated method stub 60 | System.out.println(optimize(3, 10)); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/equalSumSubset.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.*; 4 | 5 | public class equalSumSubset { 6 | 7 | public static void generateAllSubsets(int[] arr, int index, ArrayList list, int n) { 8 | 9 | if (index == n) { 10 | System.out.println(list); 11 | return; 12 | } 13 | 14 | list.add(arr[index]); 15 | generateAllSubsets(arr, index + 1, list, n); 16 | list.remove(list.size() - 1); 17 | generateAllSubsets(arr, index + 1, list, n); 18 | } 19 | 20 | public static void checkSum(int[] arr, int index, int n, int sum) { 21 | if (index == n) { 22 | System.out.println(sum); 23 | return; 24 | } 25 | 26 | checkSum(arr, index + 1, n, sum + arr[index]); 27 | checkSum(arr, index + 1, n, sum); 28 | } 29 | 30 | public static int dpApproach(int[] arr, int target, int n) { 31 | int[][] dp = new int[n + 1][target + 1]; 32 | dp[0][0] = 1; 33 | 34 | for(int i = 1; i <= n; i++) { 35 | for(int j = 0; j <= target; j++) { 36 | if(j == 0) { 37 | dp[i][j] = 1; 38 | }else { 39 | if(j >= arr[i - 1]) { 40 | dp[i][j] = (dp[i][j - arr[i - 1]] | dp[i - 1][j]); 41 | }else { 42 | dp[i][j] = dp[i - 1][j]; 43 | } 44 | } 45 | } 46 | } 47 | 48 | return dp[n][target]; 49 | } 50 | 51 | public static void main(String[] args) { 52 | // TODO Auto-generated method stub 53 | int[] arr = { 1, 2, 3, 4 }; 54 | generateAllSubsets(arr, 0, new ArrayList(), arr.length); 55 | checkSum(arr, 0, arr.length, 0); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/getMinimumSquares.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class getMinimumSquares { 4 | 5 | // public static int getMinSqr(int n) { 6 | // if (n == 0) 7 | // return 0; 8 | // 9 | // int res = Integer.MAX_VALUE; 10 | // 11 | // for (int i = 1; i * i <= n; i++) { 12 | // res = Math.min(res, getMinSqr(n - i * i)); 13 | // } 14 | // 15 | // return res + 1; 16 | // } 17 | 18 | public static int dpGetMinSqr(int n) { 19 | int[] dp = new int[n + 1]; 20 | dp[0] = 0; 21 | dp[1] = 1; // 1 * 1 22 | dp[2] = 2; // 1 * 1 + 1 * 1 23 | dp[3] = 3; // 1 * 1 + 1 * 1 + 1 * 1 24 | 25 | for (int i = 4; i <= n; i++) { 26 | dp[i] = i; 27 | for (int j = 1; j * j <= i; j++) { 28 | dp[i] = Math.min(dp[i], 1 + dp[i - j * j]); 29 | } 30 | } 31 | 32 | return dp[n]; 33 | 34 | } 35 | 36 | public static void main(String[] args) { 37 | // TODO Auto-generated method stub 38 | System.out.println(dpGetMinSqr(1365)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/knapsack01.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class knapsack01 { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | int[] values = { 10, 40, 30, 50 }; 8 | int[] weight = { 5, 4, 6, 3 }; 9 | int W = 10; 10 | 11 | int[] values2 = { 60, 100, 120 }; 12 | int[] weight2 = { 10, 20, 30 }; 13 | int w2 = 50; 14 | 15 | System.out.println(getMaxValue(values, weight, 0, W, 0)); 16 | System.out.println(getMaxValue(values2, weight2, 0, w2, 0)); 17 | } 18 | 19 | public static int getMaxValue(int[] values, int[] weight, int index, int w, int val) { 20 | // TODO Auto-generated method stub 21 | if (index == values.length) 22 | return val; 23 | 24 | if (w - weight[index] >= 0) { 25 | return Math.max(getMaxValue(values, weight, index + 1, w - weight[index], val + values[index]), 26 | getMaxValue(values, weight, index + 1, w, val)); 27 | } else { 28 | return getMaxValue(values, weight, index + 1, w, val); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/largestNumberWithKSwaps.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class largestNumberWithKSwaps { 6 | 7 | public static void Kswaps(char[] arr, int swaps) { 8 | if (swaps == 0) { 9 | System.out.println(Arrays.toString(arr)); 10 | return; 11 | } 12 | 13 | for(int i = 0; i < arr.length; i++) { 14 | for(int j = i + 1; j < arr.length; j++) { 15 | if(arr[j] > arr[i]) { 16 | swap(arr, i, j); 17 | Kswaps(arr, swaps - 1); 18 | swap(arr, i, j); 19 | } 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | // TODO Auto-generated method stub 26 | char[] arr = { '1', '2', '3', '4', '5', '6', '7' }; 27 | Kswaps(arr, 4); 28 | } 29 | 30 | public static void swap(char[] arr, int i, int j) { 31 | char temp = arr[i]; 32 | arr[i] = arr[j]; 33 | arr[j] = temp; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/lcsReeatedKtimes.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class lcsReeatedKtimes { 6 | 7 | public static String commonLCS(String txt1, String txt2) { 8 | String result = ""; 9 | int n = txt1.length(); 10 | int m = txt2.length(); 11 | 12 | int[][] dp = new int[n + 1][m + 1]; 13 | for (int i = 0; i < n + 1; i++) { 14 | for (int j = 0; j < m + 1; j++) { 15 | if (i == 0 || j == 0) { 16 | dp[i][j] = 0; 17 | } else { 18 | if (txt1.charAt(i - 1) == txt2.charAt(j - 1) && i != j) { 19 | dp[i][j] = dp[i - 1][j - 1] + 1; 20 | } else { 21 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 22 | } 23 | } 24 | } 25 | } 26 | 27 | if(dp[n][m] == 0) { 28 | return result; 29 | } 30 | 31 | int i = n; 32 | int j = m; 33 | 34 | while(i > 0 && j > 0) { 35 | if(dp[i][j] > dp[i - 1][j] && dp[i][j] > dp[i][j - 1]) { 36 | result = txt1.charAt(i - 1) + result; 37 | i--; 38 | j--; 39 | }else { 40 | if(dp[i][j] == dp[i][j - 1]) { 41 | j--; 42 | }else { 43 | i--; 44 | } 45 | } 46 | } 47 | 48 | return result; 49 | } 50 | 51 | public static void main(String[] args) { 52 | // TODO Auto-generated method stub 53 | System.out.println(commonLCS("letsleetcode", "letsleetcode")); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/longestPallindromicSubsequence.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class longestPallindromicSubsequence { 6 | 7 | public static int longestPalinSubseq(String S) { 8 | // code here 9 | int n = S.length(); 10 | int[][] dp = new int[n][n]; 11 | 12 | 13 | for (int gap = 0; gap < n; gap++) { 14 | for (int i = 0, j = gap; j < n; i++, j++) { 15 | if (i == j) { 16 | dp[i][j] = 1; 17 | } else if (j - i == 1) { 18 | if (S.charAt(i) == S.charAt(j)) { 19 | dp[i][j] = 2; 20 | } else { 21 | dp[i][j] = 1; 22 | } 23 | } else { 24 | if (S.charAt(i) == S.charAt(j)) { 25 | dp[i][j] = 2 + dp[i + 1][j - 1]; 26 | } else { 27 | dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]); 28 | } 29 | } 30 | } 31 | } 32 | 33 | print(dp); 34 | 35 | return dp[0][n - 1]; 36 | } 37 | 38 | public static void print(int[][] arr) { 39 | for (int i = 0; i < arr.length; i++) { 40 | System.out.println(Arrays.toString(arr[i])); 41 | } 42 | } 43 | 44 | public static void main(String[] args) { 45 | // TODO Auto-generated method stub 46 | System.out.println(longestPalinSubseq("geekssgeek")); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/longestValidParanthesis.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Stack; 4 | 5 | public class longestValidParanthesis { 6 | 7 | public static int validParanthesis(String S) { 8 | 9 | Stack stc = new Stack<>(); 10 | Stack st = new Stack<>(); 11 | st.push(-1); 12 | int max = 0; 13 | 14 | for(int i = 0; i < S.length(); i++) { 15 | if(S.charAt(i) == '(') { 16 | stc.push('('); 17 | st.push(i); 18 | }else { 19 | if(!stc.isEmpty()) { 20 | stc.pop(); 21 | st.pop(); 22 | max = Math.max(max, i - st.peek()); 23 | }else { 24 | st.push(i); 25 | } 26 | } 27 | 28 | System.out.println(stc); 29 | System.out.println(st); 30 | } 31 | 32 | return max; 33 | } 34 | 35 | public static void main(String[] args) { 36 | // TODO Auto-generated method stub 37 | System.out.println(validParanthesis("))()(()")); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/maxPath.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class maxPath { 6 | 7 | public static int maxPathSum(int[][] matrix, int i, int j, int n, int[][] dp) { 8 | if (dp[i][j] == 0) { 9 | 10 | if (i == n - 1) { 11 | return matrix[i][j]; 12 | } 13 | 14 | int num1 = 0; 15 | int num2 = 0; 16 | int num3 = 0; 17 | if (i + 1 < n) { 18 | num1 = maxPathSum(matrix, i + 1, j, n, dp); 19 | } 20 | 21 | if (i + 1 < n && j - 1 > -1) { 22 | num2 = maxPathSum(matrix, i + 1, j - 1, n, dp); 23 | } 24 | 25 | if (i + 1 < n && j + 1 < n) { 26 | num3 = maxPathSum(matrix, i + 1, j + 1, n, dp); 27 | } 28 | 29 | dp[i][j] = matrix[i][j] + Math.max(num1, Math.max(num2, num3)); 30 | } 31 | 32 | return dp[i][j]; 33 | } 34 | 35 | public static void print(int[][] dp) { 36 | for(int i = 0; i < dp.length; i++) { 37 | System.out.println(Arrays.toString(dp[i])); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | // TODO Auto-generated method stub 43 | int[][] matrix = { {2} }; 44 | int[][] dp = new int[matrix.length][matrix.length]; 45 | int ans = Integer.MIN_VALUE; 46 | for (int i = 0; i < matrix.length; i++) { 47 | ans = Math.max(ans, maxPathSum(matrix, 0, i, matrix.length, dp)); 48 | } 49 | 50 | print(dp); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/maxSumByRemovingOneEle.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class maxSumByRemovingOneEle { 6 | 7 | public static int maxSum(int[] arr) { 8 | int n = arr.length; 9 | int[] arrl = new int[n]; 10 | int[] arrr = new int[n]; 11 | arrl[0] = arr[0]; 12 | arrr[n - 1] = arr[n - 1]; 13 | int suml = arr[0]; 14 | int maxS = arr[0]; 15 | int sumr = arr[n - 1]; 16 | 17 | for (int i = 1; i < n; i++) { 18 | suml = Math.max(suml + arr[i], arr[i]); 19 | sumr = Math.max(sumr + arr[n - 1 - i], arr[n - 1 - i]); 20 | maxS = Math.max(maxS, suml); 21 | arrl[i] = suml; 22 | arrr[n - 1 - i] = sumr; 23 | } 24 | 25 | System.out.println(Arrays.toString(arr)); 26 | System.out.println(Arrays.toString(arrl)); 27 | System.out.println(Arrays.toString(arrr)); 28 | 29 | int ans = maxS; 30 | 31 | for (int i = 0; i < n; i++) { 32 | if (i == 0) { 33 | ans = Math.max(ans, arrr[1]); 34 | } else if (i == n - 1) { 35 | ans = Math.max(ans, arrl[n - 2]); 36 | } else { 37 | ans = Math.max(ans, arrl[i - 1] + arrr[i + 1]); 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | 44 | public static void main(String[] args) { 45 | // TODO Auto-generated method stub 46 | int[] arr = { -2, -1, -1, 4, 5 }; 47 | System.out.println(maxSum(arr)); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/minimumCostPath.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class minimumCostPath { 4 | 5 | // public static int minimumPath(int[][] matrix, int i, int j, int up, int down, int left, int right) { 6 | // 7 | // if (i == down - 1 && j == right - 1) { 8 | // return matrix[i][j]; 9 | // } 10 | // 11 | // int num1 = Integer.MAX_VALUE; 12 | // int num2 = Integer.MAX_VALUE; 13 | // int num3 = Integer.MAX_VALUE; 14 | // int num4 = Integer.MAX_VALUE; 15 | // 16 | // if (j - 1 > left) { 17 | // num1 = minimumPath(matrix, i, j - 1, up, down, left, j - 1); 18 | // } 19 | // 20 | // if (j + 1 < right) { 21 | // num2 = minimumPath(matrix, i, j + 1, up, down, j + 1, right); 22 | // } 23 | // 24 | // if (i - 1 > up) { 25 | // num3 = minimumPath(matrix, i - 1, j, up, i - 1, left, right); 26 | // } 27 | // 28 | // if (i + 1 < down) { 29 | // num4 = minimumPath(matrix, i + 1, j, i + 1, down, left, right); 30 | // } 31 | // 32 | // return matrix[i][j] + Math.min(Math.min(num1, num2), Math.max(num3, num4)); 33 | // } 34 | 35 | public static void main(String[] args) { 36 | // TODO Auto-generated method stub 37 | int[][] grid = { { 9, 4, 9, 9 }, { 6, 7, 6, 4 }, { 8, 3, 3, 7 }, { 7, 4, 9, 10 } }; 38 | int n = grid.length; 39 | // System.out.println(minimumPath(grid, 0, 0, 0, n, 0, n)); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/n_stairs.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.*; 4 | 5 | public class n_stairs { 6 | 7 | public static int totalWays(int n) { 8 | int[][] dp = new int[3][n + 1]; 9 | for (int i = 0; i < 3; i++) { 10 | for (int j = 0; j <= n; j++) { 11 | if (j == 0 || i == 1) { 12 | dp[i][j] = 1; 13 | } else if (i == 0) { 14 | dp[i][j] = 0; 15 | } else if (j < i) { 16 | dp[i][j] = dp[i][j - 1]; 17 | } else { 18 | dp[i][j] = dp[i][j - 1] + dp[i][j - i]; 19 | } 20 | } 21 | } 22 | 23 | print(dp); 24 | return dp[2][n]; 25 | } 26 | 27 | public static void print(int[][] arr) { 28 | for (int i = 0; i < arr.length; i++) { 29 | System.out.println(Arrays.toString(arr[i])); 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | // TODO Auto-generated method stub 35 | totalWays(4); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/ncr.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ncr { 6 | 7 | public static int NcR(int n, int r) { 8 | if (n == 1 || r == 0 || n == r) { 9 | return 1; 10 | } 11 | 12 | if (r == 1) { 13 | return n; 14 | } 15 | 16 | return NcR(n - 1, r) + NcR(n - 1, r - 1); 17 | } 18 | 19 | public static int dpApproach(int n, int r) { 20 | 21 | if(r > n) return -1; 22 | 23 | if(n == r) return 1; 24 | 25 | if(r == 0) return n; 26 | 27 | int[][] dp = new int[n + 1][r + 1]; 28 | 29 | for (int i = 1; i <= n; i++) { 30 | for (int j = 0; j <= r; j++) { 31 | if (i >= j) { 32 | if (j == 0) { 33 | dp[i][j] = i; 34 | } else if (i == j) { 35 | dp[i][j] = 1; 36 | } else if (j == 1) { 37 | dp[i][j] = i; 38 | } else { 39 | dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - 1]) % 1000000007; 40 | } 41 | } 42 | } 43 | } 44 | 45 | // print(dp); 46 | return dp[n][r]; 47 | } 48 | 49 | public static void print(int[][] arr) { 50 | for(int i = 0; i < arr.length; i++) { 51 | System.out.println(Arrays.toString(arr[i])); 52 | } 53 | } 54 | 55 | public static void main(String[] args) { 56 | // TODO Auto-generated method stub 57 | // System.out.println(NcR(84, 56)); 58 | System.out.println(dpApproach(84, 56)); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/numberOfCoins.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class numberOfCoins { 6 | 7 | public static int mincoins(int[] coins, int m, int v) { 8 | int[] dp = new int[v + 1]; 9 | dp[0] = 0; 10 | 11 | for (int i = 1; i <= v; i++) { 12 | int min = Integer.MAX_VALUE; 13 | for (int j = 0; j < m; j++) { 14 | int value = i; 15 | int count = 1; 16 | if (coins[j] <= i) { 17 | while (value > 0) { 18 | if (value - coins[j] >= 0 && dp[value - coins[j]] != Integer.MAX_VALUE) { 19 | min = Math.min(min, count + dp[value - coins[j]]); 20 | } 21 | 22 | value = value - coins[j]; 23 | count++; 24 | } 25 | } 26 | } 27 | 28 | dp[i] = min; 29 | } 30 | 31 | return (dp[v] == Integer.MAX_VALUE) ? -1 : dp[v]; 32 | } 33 | 34 | public static void main(String[] args) { 35 | // TODO Auto-generated method stub 36 | int v = 26; 37 | int m = 5; 38 | int coins[] = { 3, 7, 6, 11, 8 }; 39 | 40 | System.out.println(mincoins(coins, m, v)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/numberOfUniqueWays.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class numberOfUniqueWays { 4 | 5 | public static int ways(int x, int y) { 6 | 7 | if(x > 0 && y > 0) 8 | return ways(x - 1, y) + ways(x, y - 1); 9 | else if(y > 0) 10 | return ways(x, y - 1); 11 | else if(x > 0) 12 | return ways(x - 1, y); 13 | else if(x == 0 || y == 0) 14 | return 1; 15 | else return 1; 16 | } 17 | 18 | public static void main(String[] args) { 19 | // TODO Auto-generated method stub 20 | int A = 3; 21 | int B = 4; 22 | System.out.println(ways(A - 1, B - 1)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/optimalGameStartegy.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class optimalGameStartegy { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | int[] arr = { 2,6,3 }; 8 | System.out.println(getMax(arr, 0, arr.length - 1)); 9 | 10 | // int[] arr2 = { 2, 3, 15, 7 }; 11 | // System.out.println(getMax(arr2, 0, arr2.length)); 12 | } 13 | 14 | public static int getMax(int[] arr, int i, int j) { 15 | // TODO Auto-generated method stub 16 | if (j - i == 1) { 17 | return Math.max(arr[i], arr[j]); 18 | } 19 | 20 | if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) { 21 | return Math.min(getMax(arr, i + 1, j), getMax(arr, i, j - 1)); 22 | } else { 23 | return Math.max(arr[i] + getMax(arr, i + 1, j), arr[j] + getMax(arr, i, j - 1)); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/pallindromicPartition.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.*; 4 | 5 | public class pallindromicPartition { 6 | 7 | public static int pp(String str) { 8 | // code here 9 | int n = str.length(); 10 | int[][] dp = new int[n][n]; 11 | 12 | for (int diagonal = 0; diagonal < n; diagonal++) { 13 | for (int i = 0, j = diagonal; j < n; i++, j++) { 14 | if (i == j) { 15 | dp[i][j] = 0; 16 | } else if (j - i == 1) { 17 | if (str.charAt(i) == str.charAt(j)) { 18 | dp[i][j] = 0; 19 | } else { 20 | dp[i][j] = 1; 21 | } 22 | } else { 23 | if (isPallindrome(str.substring(i, j + 1))) { 24 | dp[i][j] = 0; 25 | } else { 26 | dp[i][j] = Integer.MAX_VALUE; 27 | for (int k = i; k < j; k++) { 28 | dp[i][j] = Math.min(dp[i][j], 1 + dp[i][k] + dp[k + 1][j]); 29 | // System.out.println(dp[i][j]); 30 | } 31 | } 32 | } 33 | } 34 | } 35 | 36 | return dp[0][n - 1]; 37 | } 38 | 39 | static boolean isPallindrome(String s) { 40 | int start = 0; 41 | int end = s.length() - 1; 42 | 43 | while (start < end) { 44 | if (s.charAt(start) != s.charAt(end)) { 45 | return false; 46 | } 47 | 48 | start++; 49 | end--; 50 | } 51 | 52 | return true; 53 | } 54 | 55 | public static void main(String[] args) { 56 | // TODO Auto-generated method stub 57 | System.out.println(pp("geek")); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /java-programs/DynamicProgramming/playerWithMaxScore.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class playerWithMaxScore { 6 | 7 | public static int recursionMethod(int[] arr, int start, int end, boolean turn) { 8 | 9 | if (start == end) { 10 | return arr[start]; 11 | } else if (end - start == 1) { 12 | if (turn) { 13 | return Math.max(arr[start], arr[end]); 14 | } else { 15 | return Math.min(arr[start], arr[end]); 16 | } 17 | } 18 | 19 | if (turn) { 20 | return Math.max(arr[start] + recursionMethod(arr, start + 1, end, false), 21 | arr[end] + recursionMethod(arr, start, end - 1, false)); 22 | } else { 23 | return Math.min(recursionMethod(arr, start + 1, end, true), recursionMethod(arr, start, end - 1, true)); 24 | } 25 | } 26 | 27 | public static int dp(int[] arr, int len) { 28 | int[][] dp = new int[len][len]; 29 | for (int diagonal = 0; diagonal < len; diagonal = diagonal + 2) { 30 | for (int i = 0, j = diagonal; j < len; i++, j++) { 31 | if (i == j) { 32 | dp[i][j] = arr[i]; 33 | } else { 34 | dp[i][j] = Math.max(arr[i] + Math.min(dp[i + 1][j - 1], dp[i + 2][j]), 35 | arr[j] + Math.min(dp[i + 1][j - 1], dp[i][j - 2])); 36 | } 37 | } 38 | } 39 | 40 | if(len % 2 == 0) { 41 | return dp[0][len - 2]; 42 | }else { 43 | return dp[0][len - 1]; 44 | } 45 | } 46 | 47 | public static void main(String[] args) { 48 | // TODO Auto-generated method stub 49 | int[] arr = { 20, 5, 4, 6, 8, 3 }; 50 | System.out.println(recursionMethod(arr, 0, arr.length - 1, true)); 51 | dp(arr, arr.length); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /java-programs/FindDuplicateCharacter.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.HashSet; 3 | 4 | public class FindDuplicateCharacter { 5 | 6 | static char getDuplicate(char[] str) { 7 | HashSet h = new HashSet<>(); 8 | for (int i = 0; i < str.length - 1; i++) { 9 | char c = str[i]; 10 | if (h.contains(c)) { 11 | return c; 12 | } else { 13 | h.add(c); 14 | } 15 | } 16 | return '\0'; 17 | } 18 | 19 | public static void main(String[] args) { 20 | String str = "PRADEEP"; 21 | char[] arr = str.toCharArray(); 22 | System.out.println(getDuplicate(arr)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/FindMiddleIndex.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class FindMiddleIndex { 4 | 5 | public static void findMiddleIndex(int[] numbers) { 6 | int endIndex = numbers.length - 1; 7 | int startIndex = 0, sumLeft = 0, sumRight = 0; 8 | while (true) { 9 | if (sumLeft > sumRight) { 10 | sumRight += numbers[endIndex--]; 11 | } else { 12 | sumLeft += numbers[startIndex++]; 13 | } 14 | if (startIndex > endIndex) { 15 | if (sumLeft == sumRight) { 16 | System.out.println("Left Sum: " + sumLeft + "\nRight Sum: " + sumRight); 17 | break; 18 | } else { 19 | System.out.println("Left sum are not equal to right sum"); 20 | } 21 | } 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | int[] num = { 2, 4, 4, 5, 4, 1 }; 27 | findMiddleIndex(num); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java-programs/Hashcode_Equals.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Note:- 4 | * 1. equals(Object obj): a method provided by java.lang.Object that 5 | * indicates whether some other object passed as an argument is "equal to" the 6 | * current instance. 7 | * 2. hashcode(): a method provided by java.lang.Object that 8 | * returns an integer representation of the object memory address. 9 | * 10 | */ 11 | public class Hashcode_Equals { 12 | 13 | private int id; 14 | private String name; 15 | 16 | public Hashcode_Equals(int id, String name) { 17 | this.name = name; 18 | this.id = id; 19 | } 20 | 21 | public int getId() { 22 | return id; 23 | } 24 | 25 | public void setId(int id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public static void main(String[] args) { 38 | Hashcode_Equals obj1 = new Hashcode_Equals(1, "Alex"); 39 | Hashcode_Equals obj2 = new Hashcode_Equals(1, "Alex"); 40 | System.out.println("Alex1 hasCode(): " + obj1.hashCode()); 41 | System.out.println("Alex2 hasCode(): " + obj2.hashCode()); 42 | System.out.println("Checking equality: " + obj1.equals(obj2)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java-programs/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Steps:- Insertion sort algorithm builds the final sorted array one item at a 4 | * time. 5 | * Best Case:- n 6 | * Average Case:- n^{2} 7 | * Worst Case:- n^{2} 8 | * 9 | */ 10 | public class InsertionSort { 11 | 12 | public static int[] doInerstionSort(int[] input) { 13 | int tmp = 0; 14 | for (int i = 1; i < input.length; i++) { 15 | for (int j = i; j > 0; j--) { 16 | if (input[j] < input[j - 1]) { 17 | tmp = input[j]; 18 | input[j] = input[j - 1]; 19 | input[j - 1] = tmp; 20 | } 21 | } 22 | } 23 | return input; 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] arr = { 10, 34, 2, 56, 42 }; 28 | int[] result = doInerstionSort(arr); 29 | for (int i : result) { 30 | System.out.print(i + ", "); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java-programs/LCM_GCD.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Scanner; 3 | 4 | public class LCM_GCD { 5 | public static void lcm(int n1, int n2) { 6 | int max, step, lcm = 0; 7 | lcm = (n1 > n2) ? (max = step = n1) : (max = step = n2); 8 | 9 | while (n1 != 0) { 10 | if (max % n1 == 0 && max % n2 == 0) { 11 | lcm = max; 12 | break; 13 | } 14 | max += step; 15 | } 16 | System.out.println("LCM of given number: " + lcm); 17 | } 18 | 19 | public static void gcd(int n1, int n2) { 20 | int i, hcf = 0; 21 | for (i = 1; i <= n1 || i <= n2; i++) { 22 | if (n1 % i == 0 && n2 % i == 0) { 23 | hcf = i; 24 | } 25 | } 26 | System.out.println("GCD of given number: " + hcf); 27 | } 28 | 29 | public static void main(String[] args) { 30 | Scanner sc = new Scanner(System.in); 31 | System.out.println("Enter first number: "); 32 | int n1 = sc.nextInt(); 33 | System.out.println("Enter second number: "); 34 | int n2 = sc.nextInt(); 35 | lcm(n1, n2); 36 | gcd(n1, n2); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java-programs/LaunchingExternalApps.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.io.IOException; 3 | 4 | public class LaunchingExternalApps { 5 | 6 | public static void main(String[] args) { 7 | Runtime runtime = Runtime.getRuntime(); 8 | try { 9 | runtime.exec("notepad.exe"); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java-programs/LeadersInArray.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | /** 4 | * An element is leader if it is greater than all the elements to its right 5 | * side. And the rightmost element is always a leader. 6 | * 7 | */ 8 | public class LeadersInArray { 9 | 10 | void printLeaders(int arr[], int size) { 11 | for (int i = 0; i < size; i++) { 12 | int j; 13 | for (j = i + 1; j < size; j++) { 14 | if (arr[i] <= arr[j]) { 15 | break; 16 | } 17 | } 18 | if (j == size) { 19 | System.out.print(arr[i] + " "); 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | LeadersInArray obj = new LeadersInArray(); 26 | int arr[] = new int[] { 16, 17, 4, 3, 5, 2 }; 27 | int size = arr.length; 28 | obj.printLeaders(arr, size); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java-programs/LinkListSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Arrays; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Comparator; 6 | /** 7 | * Java Program to sort a LinkedList Using Comparator. 8 | * Note: 9 | * java.util.Arrays uses Quicksort for primitive types such as int and 10 | * Mergesort for objects that implement Comparable or use a Comparator. 11 | * 12 | **/ 13 | public class LinkListSort { 14 | 15 | public static void main(String[] args) { 16 | 17 | List list = new LinkedList<>(Arrays.asList("beans", "oats", "avocados", "broccoli")); 18 | System.out.println("Before Sorting: "+list); 19 | list.sort(Comparator.naturalOrder()); 20 | System.out.println("After Sorting: " + list); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /java-programs/LinkedListFindNodeFromEnd.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | class Node { 4 | int data; 5 | Node next; 6 | Node(int d) { 7 | data = d; 8 | next = null; 9 | } 10 | } 11 | public class LinkedListFindNodeFromEnd { 12 | 13 | Node head; 14 | // Function to get the nth node from the last of a linedList 15 | public int getNodeFromLinkedList(int index) { 16 | Node current = head; 17 | int count = 1; 18 | while(current != null) { 19 | if(count == index) { 20 | return current.data; 21 | } 22 | count++; 23 | current = current.next; 24 | } 25 | assert(false); 26 | return 0; 27 | } 28 | /* Inserts a new Node at front of the list. */ 29 | public void push(int data) { 30 | Node node = new Node(data); 31 | node.next = head; 32 | head = node; 33 | } 34 | public static void main(String[] args) { 35 | LinkedListFindNodeFromEnd linkedList = new LinkedListFindNodeFromEnd(); 36 | linkedList.push(10); 37 | linkedList.push(20); 38 | linkedList.push(30); 39 | linkedList.push(40); 40 | linkedList.push(50); 41 | System.out.println("Element at index 2: "+linkedList.getNodeFromLinkedList(2)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /java-programs/LongestPalindromeSubstring.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class LongestPalindromeSubstring { 4 | 5 | static void printSubString(String str, int low, int high) { 6 | System.out.println(str.substring(low, high + 1)); 7 | } 8 | static int longestPalSubStr(String str) { 9 | int maxLength = 1; 10 | int start = 0; 11 | int len = str.length(); 12 | int low, high; 13 | 14 | for(int i = 1; i < len; i++) { 15 | low = i - 1; 16 | high = i; 17 | while(low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { 18 | if(high - low + 1 > maxLength) { 19 | start = low; 20 | maxLength = high - low + 1; 21 | } 22 | --low; 23 | ++high; 24 | } 25 | // Find the longest odd length Palindrome with center point as i 26 | low = i - 1; 27 | high = i + 1; 28 | while(low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { 29 | if(high - low + 1 > maxLength) { 30 | start = low; 31 | maxLength = high - low + 1; 32 | } 33 | --low; 34 | ++high; 35 | } 36 | } 37 | System.out.print("Longest Palindrome Substring is: "); 38 | printSubString(str, start, start + maxLength - 1); 39 | 40 | return maxLength; 41 | } 42 | 43 | public static void main(String args[]) { 44 | String str = "Hello World"; 45 | System.out.println("String: " + str); 46 | System.out.println("Length is: "+longestPalSubStr(str)); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /java-programs/LongestSubstring.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | public class LongestSubstring { 6 | 7 | String getUniqueCharacterSubstringBruteForce(String input) { 8 | String output = ""; 9 | for (int start = 0; start < input.length(); start++) { 10 | Set visited = new HashSet<>(); 11 | int end = start; 12 | for (; end < input.length(); end++) { 13 | char currChar = input.charAt(end); 14 | if (visited.contains(currChar)) { 15 | break; 16 | } else { 17 | visited.add(currChar); 18 | } 19 | } 20 | if (output.length() < end - start + 1) { 21 | output = input.substring(start, end); 22 | } 23 | } 24 | return output; 25 | } 26 | 27 | public static void main(String[] args) { 28 | String input = "ABDEFGABEF"; 29 | LongestSubstring obj = new LongestSubstring(); 30 | System.out.println("Longest Substring: " + obj.getUniqueCharacterSubstringBruteForce(input)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java-programs/MaxTwoNumbersInArrays.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class MaxTwoNumbersInArrays { 4 | 5 | public void getMaxNumber(int[] arr) { 6 | int maxOne = 0; 7 | int maxTwo = 0; 8 | for (int n : arr) { 9 | if (maxOne < n) { 10 | maxTwo = maxOne; 11 | maxOne = n; 12 | } else if (maxTwo < n) { 13 | maxTwo = n; 14 | } 15 | } 16 | System.out.println("First Max Number: " + maxOne); 17 | System.out.println("Second Max Number: " + maxTwo); 18 | } 19 | 20 | public static void main(String[] args) { 21 | int arr[] = { 5, 34, 78, 2, 45, 1, 99, 23 }; 22 | MaxTwoNumbersInArrays obj = new MaxTwoNumbersInArrays(); 23 | obj.getMaxNumber(arr); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java-programs/MaximalSubarray.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class MaximalSubarray { 4 | 5 | private static int[] arr = {1, -2, 3, 4, -9, 6}; 6 | private int getMaxSubSum(int[] arr) { 7 | int maxSum = 0; 8 | int partialSum = 0; 9 | for(int i = 0; i < arr.length; i++) { 10 | partialSum += arr[i]; 11 | maxSum = Math.max(maxSum, partialSum); 12 | if(partialSum < 0) { 13 | partialSum = 0; // Zero if negative 14 | } 15 | } 16 | return maxSum; 17 | } 18 | 19 | public static void main(String[] args) { 20 | MaximalSubarray obj = new MaximalSubarray(); 21 | int sum = obj.getMaxSubSum(arr); 22 | System.out.println("Sum: "+sum); // 3 + 4 = 7 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/MissingNumber_01.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-basics/3efcad42a45f6993efc57041379081f5398b5ab6/java-programs/MissingNumber_01.java -------------------------------------------------------------------------------- /java-programs/MissingNumber_02.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Logic:- 4 | * loop through the given array and tick marking all the numbers 5 | * which are present by storing one of their respective indices. 6 | * 7 | */ 8 | public class MissingNumber_02 { 9 | 10 | public static void main(String[] args) { 11 | int[] input = { 1, 1, 2, 3, 5, 5, 7, 9, 9, 9 }; 12 | int[] register = new int[input.length]; 13 | 14 | for (int i : input) { 15 | register[i] = 1; 16 | } 17 | System.out.println("Missing number: "); 18 | for (int i = 1; i < register.length; i++) { 19 | if (register[i] == 0) { 20 | System.out.println(i); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/MostRepeatedWord.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.ArrayList; 8 | 9 | public class MostRepeatedWord { 10 | 11 | public static void main(String[] args) { 12 | String line, word = ""; 13 | int count = 0, maxCount = 0; 14 | ArrayList words = new ArrayList(); 15 | 16 | // Opens file in read mode 17 | FileReader file; 18 | try { 19 | file = new FileReader("file.txt"); 20 | BufferedReader br = new BufferedReader(file); 21 | 22 | // Reads each line 23 | try { 24 | while ((line = br.readLine()) != null) { 25 | String string[] = line.toLowerCase().split("([,.\\s]+)"); 26 | for (String s : string) { 27 | words.add(s); 28 | } 29 | } 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | } catch (FileNotFoundException e) { 34 | e.printStackTrace(); 35 | } 36 | 37 | // Determine the most repeated word in a file 38 | for (int i = 0; i < words.size(); i++) { 39 | count = 1; 40 | for (int j = i + 1; j < words.size(); j++) { 41 | if (words.get(i).equals(words.get(j))) { 42 | count++; 43 | } 44 | } 45 | if (count > maxCount) { 46 | maxCount = count; 47 | word = words.get(i); 48 | } 49 | } 50 | System.out.println("Most Repeated words: " + word); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /java-programs/MoveZerosInArrays.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class MoveZerosInArrays { 4 | 5 | static void pushZero(int arr[]) { 6 | int max = arr.length; 7 | int temp = 0; 8 | for (int i = 0, j = 0; j < max; j++) { 9 | if (arr[j] != 0) { 10 | if (i < j) { 11 | temp = arr[i]; 12 | arr[i] = arr[j]; 13 | arr[j] = temp; 14 | } 15 | i++; 16 | } 17 | } 18 | System.out.println("Array after pushing zeros to the back: "); 19 | for (int i = 0; i < max; i++) { 20 | System.out.print(arr[i] + " "); 21 | } 22 | } 23 | public static void main(String[] args) { 24 | int arr[] = { 0, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; 25 | 26 | pushZero(arr); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java-programs/PairSum.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class PairSum { 4 | 5 | public static void PairWithMinSum(int arr[]) { 6 | if (arr.length < 2) { 7 | return; 8 | } 9 | int minimumSum = arr[0] + arr[1]; 10 | int pair1stIndex = 0; 11 | int pair2ndIndex = 1; 12 | for (int i = 0; i < arr.length; i++) { 13 | for (int j = i + 1; j < arr.length; j++) { 14 | int tempSum = arr[i] + arr[j]; 15 | if (Math.abs(tempSum) < Math.abs(minimumSum)) { 16 | pair1stIndex = i; 17 | pair2ndIndex = j; 18 | minimumSum = tempSum; 19 | } 20 | } 21 | } 22 | System.out.println("The pair whose sum is closet to Zero: " + arr[pair1stIndex] + " & " + arr[pair2ndIndex]); 23 | } 24 | 25 | public static void main(String[] args) { 26 | 27 | int[] arr = { 1, 3, -5, 7, 8, 20, -40, 6 }; 28 | PairWithMinSum(arr); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java-programs/PairsWithGivenSum.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class PairsWithGivenSum { 4 | 5 | public static void getPairsSum(int[] arr, int sum) { 6 | 7 | for (int i = 0; i < arr.length; i++) { 8 | for (int j = i + 1; j < arr.length; j++) { 9 | if (arr[i] + arr[j] == sum) { 10 | System.out.println("Pairs: ( " + arr[i] + ", " + arr[j] + " ) = " + sum); 11 | } 12 | } 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | int[] arr = { 2, 4, 3, 5, 6, 1, -2, 4, 7, 8, 9 }; 18 | int sum = 10; 19 | getPairsSum(arr, sum); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java-programs/Permutation.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Algorithm:- 4 | * 1. Try each of the letters in turn as the first letter and 5 | * then find all the permutations of the remaining letters using a recursive call. 6 | * 2. The base case is when the input is an empty string the only permutation is the empty string. 7 | * 8 | */ 9 | public class Permutation { 10 | 11 | public static void permutation(String str) { 12 | permutation("", str); 13 | } 14 | 15 | private static void permutation(String prefix, String str) { 16 | int n = str.length(); 17 | if (n == 0) 18 | System.out.println(prefix); 19 | else { 20 | for (int i = 0; i < n; i++) 21 | permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | 27 | String str = "ABC"; 28 | Permutation obj = new Permutation(); 29 | obj.permutation(str); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java-programs/PrintAllSubstring.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class PrintAllSubstring { 4 | 5 | public static void PrintSubstring(String str, int length) { 6 | 7 | System.out.println("All Substring of ABC are: "); 8 | for (int i = 0; i < length; i++) { 9 | for (int j = i + 1; j <= length; j++) { 10 | System.out.println(str.substring(i, j)); 11 | } 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | 17 | PrintSubstring("ABC", "ABC".length()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java-programs/PrintEvenOddUsingThread.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class PrintEvenOddUsingThread { 4 | 5 | public static void main(String... args) { 6 | Printer print = new Printer(); 7 | Thread t1 = new Thread(new TaskEvenOdd(print, 10, false)); 8 | Thread t2 = new Thread(new TaskEvenOdd(print, 10, true)); 9 | t1.start(); 10 | t2.start(); 11 | } 12 | } 13 | 14 | class TaskEvenOdd implements Runnable { 15 | private int max; 16 | private Printer print; 17 | private boolean isEvenNumber; 18 | 19 | TaskEvenOdd(Printer print, int max, boolean isEvenNumber) { 20 | this.print = print; 21 | this.max = max; 22 | this.isEvenNumber = isEvenNumber; 23 | } 24 | 25 | @Override 26 | public void run() { 27 | int number = isEvenNumber == true ? 2 : 1; 28 | while (number <= max) { 29 | if (isEvenNumber) { 30 | print.printEven(number); 31 | } else { 32 | print.printOdd(number); 33 | } 34 | number += 2; 35 | } 36 | } 37 | } 38 | 39 | class Printer { 40 | boolean isOdd = false; 41 | 42 | synchronized void printEven(int number) { 43 | while (isOdd == false) { 44 | try { 45 | wait(); 46 | } catch (InterruptedException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | System.out.println("Even: " + number); 51 | isOdd = false; 52 | notifyAll(); 53 | } 54 | 55 | synchronized void printOdd(int number) { 56 | while (isOdd == true) { 57 | try { 58 | wait(); 59 | } catch (InterruptedException e) { 60 | e.printStackTrace(); 61 | } 62 | } 63 | System.out.println("Odd: " + number); 64 | isOdd = true; 65 | notifyAll(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /java-programs/RandomNumberGenerator.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | 5 | public class RandomNumberGenerator { 6 | 7 | public static void main(String args[]) { 8 | ArrayList numbers = new ArrayList(); 9 | for(int i = 1; i < 50; i++) { 10 | numbers.add(i+1); 11 | } 12 | Collections.shuffle(numbers); 13 | System.out.println("Random Number: "+numbers.get(0)); 14 | } 15 | } -------------------------------------------------------------------------------- /java-programs/RemoveCharacter.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class RemoveCharacter { 4 | 5 | public static void main(String[] args) { 6 | 7 | String str1 = "Hello World"; 8 | System.out.println("String after removing 'World' = " + str1.replace("World", "")); 9 | 10 | String str2 = "Hello World"; 11 | System.out.println("String after removing first 'o' = " + str2.replaceFirst("o", "")); 12 | 13 | String str3 = "Hello World"; 14 | System.out.println("String after replacing all small letters = " + str3.replaceAll("([a-z])", "")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java-programs/RemoveCharactersFromString.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class RemoveCharactersFromString { 4 | 5 | public static void main(String[] args) { 6 | String str = "(123)-456-78910"; 7 | str = str.replaceAll("[^0-9]", ""); 8 | System.out.println("Final String: "+ str); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java-programs/RemoveDuplicate.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.HashSet; 6 | import java.util.Iterator; 7 | import java.util.LinkedHashSet; 8 | 9 | public class RemoveDuplicate { 10 | 11 | public static void main(String[] args) { 12 | ArrayList list = new ArrayList(); 13 | list.add("two"); 14 | list.add("one"); 15 | list.add("three"); 16 | list.add("one"); 17 | list.add("four"); 18 | 19 | ArrayList list2 = new ArrayList(new HashSet(list)); // no elements order 20 | // ArrayList list2 = new ArrayList(new LinkedHashSet(list)); //To preserve the order of the elements 21 | Iterator itr = list2.iterator(); 22 | while(itr.hasNext()) { 23 | System.out.println(itr.next()); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java-programs/RemoveDuplicateInArraylist.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.LinkedHashSet; 5 | 6 | public class RemoveDuplicateInArraylist { 7 | 8 | public static void main(String[] args) { 9 | ArrayList arrList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8, 9, 9)); 10 | 11 | System.out.println("Array: " + arrList); 12 | 13 | ArrayList linkedHashSet = new ArrayList<>(new LinkedHashSet<>(arrList)); 14 | System.out.println("Array without duplicates: " + linkedHashSet); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java-programs/ReverseWordInString.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class ReverseWordInString { 4 | 5 | public void reverse(String str) { 6 | String[] words = str.split(" "); 7 | String result = ""; 8 | for (int i = 0; i < words.length; i++) { 9 | String word = words[i]; 10 | String reversedWord = ""; 11 | for (int j = word.length() - 1; j >= 0; j--) { 12 | reversedWord = reversedWord + word.charAt(j); 13 | } 14 | result = result + reversedWord + " "; 15 | } 16 | System.out.println(str); 17 | System.out.println(result); 18 | } 19 | 20 | public static void main(String[] args) { 21 | ReverseWordInString obj = new ReverseWordInString(); 22 | obj.reverse("Pradeep Kumar"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java-programs/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class SelectionSort { 4 | 5 | public static void doSelectionSort(int[] arr) { 6 | for (int i = 0; i < arr.length - 1; i++) { 7 | int index = i; 8 | for (int j = i + 1; j < arr.length; j++) { 9 | if (arr[j] < arr[index]) { 10 | index = j; 11 | } 12 | } 13 | int smallerNumber = arr[index]; 14 | arr[index] = arr[i]; 15 | arr[i] = smallerNumber; 16 | } 17 | System.out.println("\n\nArray after sort"); 18 | for (int element : arr) { 19 | System.out.print(element + ", "); 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | int[] arr1 = { 10, 34, 2, 56, 7, 67, 88, 42 }; 25 | 26 | System.out.println("Array before sort"); 27 | for (int i : arr1) { 28 | System.out.print(i + ", "); 29 | } 30 | doSelectionSort(arr1); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java-programs/SingletonClass.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class SingletonClass { 4 | 5 | private static SingletonClass instance; 6 | 7 | public synchronized static SingletonClass getInstance() { 8 | if(instance == null) { 9 | instance = new SingletonClass(); 10 | System.out.println("Object created...!"); 11 | } else { 12 | System.out.println("Object already exists."); 13 | } 14 | return instance; 15 | } 16 | public void message(String str) { 17 | System.out.println("Message function called, Hello "+str); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java-programs/SingletonClassMain.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class SingletonClassMain { 4 | 5 | public static void main(String[] args) { 6 | SingletonClass obj1 = SingletonClass.getInstance(); 7 | SingletonClass obj2 = SingletonClass.getInstance(); 8 | 9 | obj1.message("Pradeep"); 10 | obj2.message("Kumar"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java-programs/SortATextFile.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.FileWriter; 6 | import java.io.PrintWriter; 7 | import java.util.ArrayList; 8 | import java.util.Collections; 9 | import java.util.List; 10 | 11 | public class SortATextFile { 12 | 13 | public static void main(String[] args) throws Exception { 14 | String inputfile = "input.txt"; 15 | String outputfile = "output.txt"; 16 | 17 | FileReader fileReader = new FileReader(inputfile); 18 | BufferedReader bufferReader = new BufferedReader(fileReader); 19 | String inputLine; 20 | List lineList = new ArrayList(); 21 | while ((inputLine = bufferReader.readLine()) != null) { 22 | lineList.add(inputLine); 23 | } 24 | fileReader.close(); 25 | Collections.sort(lineList); 26 | 27 | FileWriter fileWriter = new FileWriter(outputfile); 28 | PrintWriter out = new PrintWriter(fileWriter); 29 | for (String outputLine : lineList) { 30 | out.println(outputLine); 31 | } 32 | 33 | out.flush(); 34 | out.close(); 35 | fileWriter.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java-programs/SquarerootOfNumber.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class SquarerootOfNumber { 4 | 5 | public static double sqrt(int number) { 6 | double t; 7 | double squareRoot = number / 2; 8 | do { 9 | t = squareRoot; 10 | squareRoot = (t + (number / t)) / 2; 11 | } while ((t - squareRoot) != 0); 12 | return squareRoot; 13 | } 14 | 15 | public static void main(String[] args) { 16 | System.out.println("Square root of 2: " + sqrt(2)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java-programs/StackSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import java.util.Stack; 3 | 4 | public class StackSort { 5 | 6 | public static Stack sortStack(Stack input) { 7 | Stack tmpStack = new Stack(); 8 | while (!input.isEmpty()) { 9 | int tmp = input.pop(); 10 | System.out.println("Element taken out: " + tmp); 11 | while (!tmpStack.isEmpty() && tmpStack.peek() > tmp) { 12 | input.push(tmpStack.pop()); 13 | } 14 | tmpStack.push(tmp); 15 | System.out.println("Input: " + input); 16 | System.out.println("Temporary Stack: " + tmpStack); 17 | } 18 | return tmpStack; 19 | } 20 | 21 | public static void main(String[] args) { 22 | 23 | Stack input = new Stack(); 24 | input.add(6); 25 | input.add(4); 26 | input.add(5); 27 | input.add(9); 28 | input.add(2); 29 | System.out.println("Input: " + input); 30 | System.out.println("\nFinal sorted Stack: " + sortStack(input)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java-programs/StringReverse.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class StringReverse { 4 | 5 | static void reverse(String str) { 6 | char[] inputArray = str.toCharArray(); 7 | char[] result = new char[inputArray.length]; 8 | 9 | // Mark spaces in result 10 | for (int i = 0; i < inputArray.length; i++) { 11 | if (inputArray[i] == ' ') { 12 | result[i] = ' '; 13 | } 14 | } 15 | 16 | // Traverse input string from beginning 17 | // and put characters in result from end 18 | int j = result.length - 1; 19 | for (int i = 0; i < inputArray.length; i++) { 20 | 21 | // Ignore spaces in input string 22 | if (inputArray[i] != ' ') { 23 | 24 | // ignore spaces in result. 25 | if (result[j] == ' ') { 26 | j--; 27 | } 28 | result[j] = inputArray[i]; 29 | j--; 30 | } 31 | } 32 | System.out.println(String.valueOf(result)); 33 | } 34 | 35 | public static void main(String[] args) { 36 | reverse("Pradeep Kumar"); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java-programs/StringRotation.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | /** 3 | * Algorithm:- 4 | * 1. Create a temp string and store concatenation of str1 to str1 in temp. 5 | * temp = str1.str1 6 | * 2. If str2 is a substring of temp then str1 and str2 are 7 | * rotations of each other. 8 | * 9 | * Example: 10 | * str1 = "ABACD" 11 | * str2 = "CDABA" 12 | * 13 | * temp = str1.str1 = "ABACDABACD" 14 | * Since str2 is a substring of temp, str1 and str2 are 15 | * rotations of each other. 16 | * 17 | */ 18 | 19 | public class StringRotation { 20 | 21 | static boolean isRotation(String str1, String str2) { 22 | return (str1.length() == str2.length()) && ((str1 + str2).indexOf(str2) != -1); 23 | } 24 | public static void main(String[] args) { 25 | String str1 = "AACD"; 26 | String str2 = "ACDA"; 27 | if(isRotation(str1, str2)) { 28 | System.out.println("Strings are rotations of each other"); 29 | } else { 30 | System.out.println("Strings are not rotations of each other"); 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /java-programs/StringSwap.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class StringSwap { 4 | 5 | public static void main(String[] args) { 6 | String a = "Hello"; 7 | String b = "World"; 8 | 9 | System.out.println("Strings before swap: a = " + a + " and b = " + b); 10 | a = a + b; 11 | // Store initial string a in string b 12 | b = a.substring(0, a.length() - b.length()); 13 | // Store initial string b in string a 14 | a = a.substring(b.length()); 15 | System.out.println("Strings after swap: a = " + a + " and b = " + b); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java-programs/SumOfPrimeNumbers.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class SumOfPrimeNumbers { 4 | 5 | private static boolean isPrimeNumber(int number) { 6 | for (int i = 2; i <= number / 2; i++) { 7 | if (number % i == 0) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | public static void main(String[] args) { 15 | int number = 2, count = 0, sum = 0; 16 | while (count < 10) { 17 | if (isPrimeNumber(number)) { 18 | System.out.println("Prime Number: " + number); 19 | sum += number; 20 | count++; 21 | } 22 | number++; 23 | } 24 | System.out.println("Sum of 5 Prime Numbers: " + sum); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java-programs/UserDefinedException.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class UserDefinedException extends Exception { 4 | 5 | private static final long serialVersionUID = 8331376309753029444L; 6 | private int price; 7 | 8 | public UserDefinedException(int price) { 9 | this.price = price; 10 | } 11 | public String toString() { 12 | return "Price should not be in Negative: " + price; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java-programs/UserDefinedExceptionMain.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class UserDefinedExceptionMain { 4 | 5 | public static void main(String[] args) throws Exception { 6 | int price = -120; 7 | if(price < 0 ) { 8 | throw new UserDefinedException(price); 9 | } else { 10 | System.out.println("You have entered: "+price + "rs"); 11 | } 12 | } 13 | } 14 | --------------------------------------------------------------------------------