├── .gitignore ├── JavaInterviewQuestions-UdemyCourse.pdf ├── docs ├── abstract-class.md ├── arrays.md ├── basics-class-object.md ├── collections.md ├── constructors.md ├── control-flow-if-switch-for-while ├── enum.md ├── exception-handling.md ├── file-io.md ├── generics.md ├── inheritance-and-polymorphism.md ├── initializers.md ├── inner-class.md ├── interfaces.md ├── modifiers-class-access.md ├── modifiers-members-access.md ├── modifiers-nonaccess-final.md ├── modifiers-nonaccess-static ├── object-methods.md ├── oops-advanced.md ├── operators.md ├── others-assert.md ├── others-date-calendar.md ├── others.md ├── serialization.md ├── string-and-string-buffer-builder.md ├── threads-and-synchronization.md ├── variable-arguments.md ├── variables-initialization-and-more.md └── wrapper-classes.md ├── images ├── JavaClassLoaders.png ├── JavaPlatFormIndependence.png └── jvm-jre-jdk.jpg ├── pom.xml ├── readme.md └── src ├── main └── java │ └── com │ └── in28minutes │ └── java │ ├── arrays │ └── ArrayExamples.java │ ├── basics │ ├── Actor.java │ ├── CricketScorer.java │ └── Cricketer.java │ ├── classmodifiers │ ├── defaultaccess │ │ ├── a │ │ │ ├── AnotherClassInSamePackage.java │ │ │ └── DefaultAccessClass.java │ │ └── b │ │ │ └── ClassInDifferentPackage.java │ └── nonaccess │ │ ├── abstractclass │ │ └── AbstractClassExample.java │ │ └── finalclass │ │ └── FinalClass.java │ ├── collections │ ├── CollectionHierarchy.java │ ├── FailFast.java │ ├── FailSafe.java │ └── examples │ │ ├── CollectionExamples.java │ │ └── ConcurrentCollectionsExamples.java │ ├── enums │ ├── Enum.java │ ├── EnumAdvanced.java │ └── EnumAdvanced2.java │ ├── exceptionhandling │ ├── ExceptionHandlingExample1.java │ └── ExceptionHandlingExample2.java │ ├── files │ ├── ConsoleExamples.java │ └── FileExamples.java │ ├── flow │ ├── BreakExamples.java │ ├── ContinueExamples.java │ ├── DoWhileLoopExamples.java │ ├── ForLoopExample.java │ ├── IfElseExamples.java │ ├── SwitchExamples.java │ └── WhileLoopExamples.java │ ├── generics │ ├── GenericsExamples.java │ ├── GenericsExamples2.java │ └── GenericsExamples3.java │ ├── initializers │ └── InitializerExamples.java │ ├── innerclass │ ├── AnonymousClass.java │ └── InnerClassExamples.java │ ├── membermodifiers │ ├── access │ │ ├── ExampleClass.java │ │ ├── SubClassInSamePackage.java │ │ ├── TestClassInSamePackage.java │ │ └── different │ │ │ ├── SubClassInDifferentPackage.java │ │ │ └── TestClassInDifferentPackage.java │ └── nonaccess │ │ ├── FinalMemberModifiersExample.java │ │ └── StaticModifierExamples.java │ ├── object │ ├── EqualsHashCodeExamples.java │ ├── ToStringExamples.java │ └── constructors │ │ └── ConstructorExamples.java │ ├── oops │ ├── cohesion │ │ ├── problem │ │ │ └── CohesionExampleProblem.java │ │ └── solution │ │ │ └── CohesionExampleSolution.java │ ├── coupling │ │ ├── problem │ │ │ └── CouplingExamplesProblem.java │ │ └── solution │ │ │ └── CouplingExamplesSolution.java │ ├── encapsulation │ │ └── EncapsulationExample.java │ ├── inheritance │ │ ├── EveryClassExtendsObject.java │ │ ├── InheritanceExamples.java │ │ ├── overloading │ │ │ └── OverloadingRules.java │ │ ├── overriding │ │ │ └── OverridingRules.java │ │ ├── polymorphism │ │ │ ├── Animal.java │ │ │ ├── Cat.java │ │ │ ├── Dog.java │ │ │ └── TestPolymorphism.java │ │ └── reuse │ │ │ ├── Actor.java │ │ │ ├── Comedian.java │ │ │ ├── Hero.java │ │ │ └── TestReuse.java │ └── interfaces │ │ ├── Aeroplane.java │ │ ├── Bird.java │ │ ├── Flyable.java │ │ ├── IntefaceRules.java │ │ ├── InterfaceExamples.java │ │ └── InterfaceWithMain.java │ ├── operators │ ├── IncrementAndDecrementOperators.java │ ├── InstanceOfExamples.java │ ├── LogicalOperators.java │ ├── RelationalOperators.java │ ├── StringConcatenationExamples.java │ └── TernaryOperator.java │ ├── others │ ├── PrintfExamples.java │ ├── SameType.java │ ├── assertexample │ │ └── AssertExamples.java │ ├── date │ │ ├── CalendarExamples.java │ │ └── DateExamples.java │ ├── garbagecollection │ │ └── GarbageCollectionExamples.java │ └── regularexpressions │ │ └── RegularExpressionExamples.java │ ├── serialization │ ├── SerializationExamples.java │ ├── SerializationExamples2.java │ └── SerializationExamples3.java │ ├── string │ ├── StringBufferBuilderExamples.java │ └── StringExamples.java │ ├── threads │ ├── ExecutorServiceExamples.java │ ├── ThreadDeadlock.java │ ├── ThreadExampleSynchronized.java │ ├── ThreadExamples.java │ ├── ThreadPriority.java │ └── ThreadWaitAndNotify.java │ ├── varargs │ └── VariableArgumentExamples.java │ ├── variables │ ├── PassingVariablesToMethods.java │ ├── StaticAndMemberVariables.java │ ├── VariableInitialization.java │ └── scope │ │ └── VariablesExample.java │ └── wrapper │ └── WrapperExamples.java └── test └── java ├── LambdaExpressionsTest.java └── StringVsStringBuffer.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | /target/ 14 | -------------------------------------------------------------------------------- /JavaInterviewQuestions-UdemyCourse.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sriharivaleti/in28minutes_JavaInterviewQuestionsAndAnswers/8aad83f4b6076fe86317517720a2b64723c4414d/JavaInterviewQuestions-UdemyCourse.pdf -------------------------------------------------------------------------------- /docs/abstract-class.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/classmodifiers/nonaccess/abstractclass/AbstractClassExample.java 2 | ``` 3 | package com.in28minutes.java.classmodifiers.nonaccess.abstractclass; 4 | 5 | public abstract class AbstractClassExample { 6 | 7 | // Abstract class can contain instance and static variables 8 | public int publicVariable; 9 | private int privateVariable; 10 | static int staticVariable; 11 | 12 | // Abstract Class can contain 0 or more abstract methods 13 | // Abstract method does not have a body 14 | abstract void abstractMethod1(); 15 | 16 | abstract void abstractMethod2(); 17 | 18 | // Abstract Class can contain 0 or more non-abstract methods 19 | public void nonAbstractMethod() { 20 | System.out.println("Non Abstract Method"); 21 | } 22 | 23 | public static void main(String[] args) { 24 | // An abstract class cannot be instantiated 25 | // Below line gives compilation error if uncommented 26 | // AbstractClassExample ex = new AbstractClassExample(); 27 | } 28 | } 29 | 30 | // A non-abstract sub class of an abstract class should 31 | // implement all the abstract methods 32 | // Below class gives compilation error if uncommented 33 | /* 34 | * class SubClass extends AbstractClassExample { 35 | * 36 | * } 37 | */ 38 | 39 | // This class implements both abstractMethod1 and abstractMethod2 40 | class SubClass2 extends AbstractClassExample { 41 | void abstractMethod1() { 42 | System.out.println("Abstract Method1"); 43 | } 44 | 45 | void abstractMethod2() { 46 | System.out.println("Abstract Method2"); 47 | } 48 | } 49 | 50 | // We can create a subclass of an abstract class which is abstract 51 | // It doesn't need to implement all the abstract methods 52 | abstract class AbstractSubClass extends AbstractClassExample { 53 | void abstractMethod1() { 54 | System.out.println("Abstract Method1"); 55 | } 56 | // abstractMethod2 is not defined at all. 57 | } 58 | ``` 59 | -------------------------------------------------------------------------------- /docs/arrays.md: -------------------------------------------------------------------------------- 1 | ## Examples 2 | ### /com/in28minutes/java/arrays/ArrayExamples.java 3 | ``` 4 | package com.in28minutes.java.arrays; 5 | 6 | import java.util.Arrays; 7 | 8 | public class ArrayExamples { 9 | public static void main(String[] args) { 10 | // Declare an Array. All below ways are legal. 11 | int marks[]; // Not Readable 12 | int[] runs; // Not Readable 13 | int[] temperatures;// Recommended 14 | 15 | // Declaration of an Array should not include size. 16 | // int values[5];//Compilation Error! 17 | 18 | // Declaring 2D ArrayExamples 19 | int[][] matrix1; // Recommended 20 | int[] matrix2[]; // Legal but not readable. Avoid. 21 | 22 | // Creating an array 23 | marks = new int[5]; // 5 is size of array 24 | 25 | // Size of an array is mandatory to create an array 26 | // marks = new int[];//COMPILER ERROR 27 | 28 | // Once An Array is created, its size cannot be changed. 29 | 30 | // Declaring and creating an array in same line 31 | int marks2[] = new int[5]; 32 | 33 | // new Arrays are alway initialized with default values 34 | System.out.println(marks2[0]);// 0 35 | 36 | // Default Values 37 | // byte,short,int,long-0 38 | // float,double-0.0 39 | // boolean false 40 | // object-null 41 | 42 | // Assigning values to array 43 | marks[0] = 25; 44 | marks[1] = 30; 45 | marks[2] = 50; 46 | marks[3] = 10; 47 | marks[4] = 5; 48 | 49 | // ArrayOnHeap.xls 50 | 51 | // Note : Index of an array runs from 0 to length - 1 52 | 53 | // Declare, Create and Initialize Array on same line 54 | int marks3[] = { 25, 30, 50, 10, 5 }; 55 | 56 | // Leaving additional comma is not a problem 57 | int marks4[] = { 25, 30, 50, 10, 5, }; 58 | 59 | // Default Values in Array 60 | // numbers - 0 floating point - 0.0 Objects - null 61 | 62 | // Length of an array : Property length 63 | int length = marks.length; 64 | 65 | // Printing a value from array 66 | System.out.println(marks[2]); 67 | 68 | // Looping around an array - Enhanced for loop 69 | for (int mark : marks) { 70 | System.out.println(mark); 71 | } 72 | 73 | // Fill array with same default value 74 | Arrays.fill(marks, 100); // All array values will be 100 75 | 76 | // Access 10th element when array has only length 5 77 | // Runtime Exception : ArrayIndexOutOfBoundsException 78 | // System.out.println(marks[10]); 79 | 80 | // String Array: similar to int array. 81 | String[] daysOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", 82 | "Thursday", "Friday", "Saturday" }; 83 | 84 | // Array can contain only values of same type. 85 | // COMPILE ERROR!! 86 | // int marks4[] = {10,15.0}; //10 is int 15.0 is float 87 | 88 | // Cross assigment of primitive arrays is ILLEGAL 89 | int[] ints = new int[5]; 90 | short[] shorts = new short[5]; 91 | // ints = shorts;//COMPILER ERROR 92 | // ints = (int[])shorts;//COMPILER ERROR 93 | 94 | // 2D Arrays 95 | int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; 96 | 97 | int[][] matrixA = new int[5][6]; 98 | 99 | // First dimension is necessary to create a 2D Array 100 | // Best way to visualize a 2D array is as an array of arrays 101 | // ArrayOnHeap.xls 102 | matrixA = new int[3][];// FINE 103 | // matrixA = new int[][5];//COMPILER ERROR 104 | // matrixA = new int[][];//COMPILER ERROR 105 | 106 | // We can create a ragged 2D Array 107 | matrixA[0] = new int[3]; 108 | matrixA[0] = new int[4]; 109 | matrixA[0] = new int[5]; 110 | 111 | // Above matrix has 2 rows 3 columns. 112 | 113 | // Accessing an element from 2D array: 114 | System.out.println(matrix[0][0]); // 1 115 | System.out.println(matrix[1][2]); // 6 116 | 117 | // Looping a 2D array: 118 | for (int[] array : matrix) { 119 | for (int number : array) { 120 | System.out.println(number); 121 | } 122 | } 123 | 124 | // Printing a 1D Array 125 | int marks5[] = { 25, 30, 50, 10, 5 }; 126 | System.out.println(marks5); // [I@6db3f829 127 | System.out.println(Arrays.toString(marks5));// [25, 30, 50, 10, 5] 128 | 129 | // Printing a 2D Array 130 | int[][] matrix3 = { { 1, 2, 3 }, { 4, 5, 6 } }; 131 | System.out.println(matrix3); // [[I@1d5a0305 132 | System.out.println(Arrays.toString(matrix3)); 133 | // [[I@6db3f829, [I@42698403] 134 | System.out.println(Arrays.deepToString(matrix3)); 135 | // [[1, 2, 3], [4, 5, 6]] 136 | 137 | // matrix3[0] is a 1D Array 138 | System.out.println(matrix3[0]);// [I@86c347 139 | System.out.println(Arrays.toString(matrix3[0]));// [1, 2, 3] 140 | 141 | // Comparing Arrays 142 | int[] numbers1 = { 1, 2, 3 }; 143 | int[] numbers2 = { 4, 5, 6 }; 144 | System.out.println(Arrays.equals(numbers1, numbers2)); // false 145 | int[] numbers3 = { 1, 2, 3 }; 146 | System.out.println(Arrays.equals(numbers1, numbers3)); // true 147 | 148 | // Sorting An Array 149 | int rollNos[] = { 12, 5, 7, 9 }; 150 | Arrays.sort(rollNos); 151 | System.out.println(Arrays.toString(rollNos));// [5, 7, 9, 12] 152 | 153 | // Array of Objects(ArrayOnHeap.xls) 154 | Person[] persons = new Person[3]; 155 | 156 | // Creating an array of Persons creates 157 | // 4 Reference Variables to Person 158 | // It does not create the Person Objects 159 | // ArrayOnHeap.xls 160 | System.out.println(persons[0]);// null 161 | 162 | // to assign objects we would need to create them 163 | persons[0] = new Person(); 164 | persons[1] = new Person(); 165 | persons[2] = new Person(); 166 | 167 | // Other way 168 | // How may objects are created? 169 | Person[] personsAgain = { new Person(), new Person(), new Person() }; 170 | 171 | // How may objects are created? 172 | Person[][] persons2D = { { new Person(), new Person(), new Person() }, 173 | { new Person(), new Person() } }; 174 | 175 | } 176 | } 177 | 178 | class Person { 179 | long ssn; 180 | String name; 181 | } 182 | ``` 183 | -------------------------------------------------------------------------------- /docs/basics-class-object.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/basics/Actor.java 2 | ``` 3 | package com.in28minutes.java.basics; 4 | 5 | public class Actor { 6 | 7 | // name is a Member Variable 8 | private String name; 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void setName(String name) { 15 | // This is called shadowing 16 | // Local variable or parameter with 17 | // same name as a member variable 18 | // this.name refers to member variable 19 | // name refers to local variable 20 | this.name = name; 21 | } 22 | 23 | public static void main(String[] args) { 24 | // bradPitt & tomCruise are objects or instances 25 | // of Class Actor 26 | // Each instance has separate value for the 27 | // member variable name 28 | Actor bradPitt = new Actor(); 29 | bradPitt.setName("Brad Pitt"); 30 | 31 | Actor tomCruise = new Actor(); 32 | tomCruise.setName("Tom Cruise"); 33 | } 34 | } 35 | ``` 36 | ### /com/in28minutes/java/basics/Cricketer.java 37 | ``` 38 | package com.in28minutes.java.basics; 39 | 40 | public class Cricketer { 41 | String name; 42 | int odiRuns; 43 | int testRuns; 44 | int t20Runs; 45 | 46 | public int totalRuns() { 47 | int totalRuns = odiRuns + testRuns + t20Runs; 48 | return totalRuns; 49 | } 50 | } 51 | ``` 52 | ### /com/in28minutes/java/basics/CricketScorer.java 53 | ``` 54 | package com.in28minutes.java.basics; 55 | 56 | public class CricketScorer { 57 | // Instance Variables - constitute the state of an object 58 | private int score; 59 | 60 | // Behavior - all the methods that are part of the class 61 | // An object of this type has behavior based on the 62 | // methods four, six and getScore 63 | public void four() { 64 | score = score + 4; 65 | } 66 | 67 | public void six() { 68 | score = score + 6; 69 | } 70 | 71 | public int getScore() { 72 | return score; 73 | } 74 | 75 | public static void main(String[] args) { 76 | CricketScorer scorer = new CricketScorer(); 77 | scorer.six(); 78 | // State of scorer is (score => 6) 79 | scorer.four(); 80 | // State of scorer is (score => 10) 81 | System.out.println(scorer.getScore()); 82 | } 83 | } 84 | ``` 85 | -------------------------------------------------------------------------------- /docs/constructors.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/object/constructors/ConstructorExamples.java 2 | ``` 3 | package com.in28minutes.java.object.constructors; 4 | 5 | class Animal { 6 | String name; 7 | 8 | public Animal(String name) { 9 | this.name = name; 10 | System.out.println("Animal Constructor with name"); 11 | } 12 | } 13 | 14 | class Dog extends Animal { 15 | public Dog(String name) { 16 | super(name); 17 | } 18 | 19 | public Dog() { 20 | super("Default Dog Name"); 21 | } 22 | } 23 | 24 | public class ConstructorExamples { 25 | public static void main(String[] args) { 26 | Dog dog = new Dog("Terry"); 27 | } 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /docs/enum.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/enums/Enum.java 2 | ``` 3 | package com.in28minutes.java.enums; 4 | 5 | //Enum can be declared outside a class 6 | enum SeasonOutsideClass { 7 | WINTER, SPRING, SUMMER, FALL 8 | }; 9 | 10 | public class Enum { 11 | // Enum can be declared inside a class 12 | enum Season { 13 | WINTER, SPRING, SUMMER, FALL 14 | }; 15 | 16 | public static void main(String[] args) { 17 | /* 18 | * //Uncommenting gives compilation error //enum cannot be created in a 19 | * method enum InsideMethodNotAllowed { WINTER, SPRING, SUMMER, FALL }; 20 | */ 21 | 22 | // Converting String to Enum 23 | Season season = Season.valueOf("FALL"); 24 | 25 | // Converting Enum to String 26 | System.out.println(season.name());// FALL 27 | 28 | // Default ordinals of enum 29 | // By default java assigns ordinals in order 30 | System.out.println(Season.WINTER.ordinal());// 0 31 | System.out.println(Season.SPRING.ordinal());// 1 32 | System.out.println(Season.SUMMER.ordinal());// 2 33 | System.out.println(Season.FALL.ordinal());// 3 34 | 35 | // Looping an enum => We use method values 36 | for (Season season1 : Season.values()) { 37 | System.out.println(season1.name()); 38 | // WINTER SPRING SUMMER FALL (separate lines) 39 | } 40 | 41 | // Comparing two Enums 42 | Season season1 = Season.FALL; 43 | Season season2 = Season.FALL; 44 | System.out.println(season1 == season2);// true 45 | System.out.println(season1.equals(season2));// true 46 | } 47 | } 48 | ``` 49 | ### /com/in28minutes/java/enums/EnumAdvanced.java 50 | ``` 51 | package com.in28minutes.java.enums; 52 | 53 | public class EnumAdvanced { 54 | 55 | // Enum with a variable,method and constructor 56 | enum SeasonCustomized { 57 | WINTER(1), SPRING(2), SUMMER(3), FALL(4); 58 | 59 | // variable 60 | private int code; 61 | 62 | // method 63 | public int getCode() { 64 | return code; 65 | } 66 | 67 | // Constructor-only private or (default) 68 | // modifiers are allowed 69 | SeasonCustomized(int code) { 70 | this.code = code; 71 | } 72 | 73 | // Getting value of enum from code 74 | public static SeasonCustomized valueOf(int code) { 75 | for (SeasonCustomized season : SeasonCustomized.values()) { 76 | if (season.getCode() == code) 77 | return season; 78 | } 79 | throw new RuntimeException("value not found");// Just for kicks 80 | } 81 | 82 | // Using switch statement on an enum 83 | public int getExpectedMaxTemperature() { 84 | switch (this) { 85 | case WINTER: 86 | return 5; 87 | case SPRING: 88 | case FALL: 89 | return 10; 90 | case SUMMER: 91 | return 20; 92 | } 93 | return -1;// Dummy since Java does not recognize this is possible :) 94 | } 95 | 96 | }; 97 | 98 | public static void main(String[] args) { 99 | SeasonCustomized season = SeasonCustomized.WINTER; 100 | 101 | /* 102 | * //Enum constructor cannot be invoked directly //Below line would 103 | * cause COMPILER ERROR SeasonCustomized season2 = new 104 | * SeasonCustomized(1); 105 | */ 106 | 107 | System.out.println(season.getCode());// 1 108 | 109 | System.out.println(season.getExpectedMaxTemperature());// 5 110 | 111 | System.out.println(SeasonCustomized.valueOf(4));// FALL 112 | 113 | } 114 | 115 | } 116 | ``` 117 | ### /com/in28minutes/java/enums/EnumAdvanced2.java 118 | ``` 119 | package com.in28minutes.java.enums; 120 | 121 | public class EnumAdvanced2 { 122 | 123 | // Enum with a variable,method and constructor 124 | enum SeasonCustomized { 125 | WINTER(1) { 126 | public int getExpectedMaxTemperature() { 127 | return 5; 128 | } 129 | }, 130 | SPRING(2), SUMMER(3) { 131 | public int getExpectedMaxTemperature() { 132 | return 20; 133 | } 134 | }, 135 | FALL(4); 136 | 137 | // variable 138 | private int code; 139 | 140 | // method 141 | public int getCode() { 142 | return code; 143 | } 144 | 145 | // Constructor-only private or (default) 146 | // modifiers are allowed 147 | SeasonCustomized(int code) { 148 | this.code = code; 149 | } 150 | 151 | public int getExpectedMaxTemperature() { 152 | return 10; 153 | } 154 | 155 | }; 156 | 157 | public static void main(String[] args) { 158 | SeasonCustomized season = SeasonCustomized.WINTER; 159 | 160 | System.out.println(season.getExpectedMaxTemperature());// 5 161 | 162 | System.out.println(SeasonCustomized.FALL.getExpectedMaxTemperature());// 10 163 | 164 | } 165 | 166 | } 167 | ``` 168 | -------------------------------------------------------------------------------- /docs/exception-handling.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/exceptionhandling/ExceptionHandlingExample1.java 2 | ``` 3 | package com.in28minutes.java.exceptionhandling; 4 | 5 | //Java Interview Questions Exception Handling 6 | //������������������������������������������� 7 | //What is difference between Error and Exception - done? 8 | //What is the Exception Handling Hierarchy - done? 9 | //Difference between runtime exception and checked exception? 10 | //When should we use Checked Exceptions? 11 | //What does Exception propagation mean? 12 | //Why should type 'Exception' not be catched? 13 | //What are the best practices of Exception Handling? 14 | //How do you create a custom exception - checked and unchecked? 15 | //Is try without catch and finally allowed? 16 | //When is finally block NOT executed? 17 | //Let's say there is a return in the try block. Will finally block be executed? 18 | //Exception Handling - Best Practices 19 | 20 | //Runtime Exceptions => Unchecked exceptions 21 | //Checked Exceptions 22 | 23 | class CheckedException extends Exception { 24 | 25 | } 26 | 27 | class RuntimeExceptionExample extends RuntimeException { 28 | 29 | } 30 | 31 | class Test { 32 | void readAFileAndParse() throws RuntimeExceptionExample { 33 | // Reading a file => FileNotFound 34 | // Parses the file => FileIsNotInCorrectFormat 35 | } 36 | } 37 | 38 | class Reuse { 39 | void doSomething() { 40 | Test test = new Test(); 41 | test.readAFileAndParse(); 42 | } 43 | 44 | public void firstMethod() throws RuntimeException { 45 | 46 | } 47 | 48 | public void secondMethod() { 49 | firstMethod(); 50 | } 51 | } 52 | 53 | // Below class definitions show creation of a programmer defined exception in 54 | // Java. 55 | // Programmer defined classes 56 | class CheckedException1 extends Exception { 57 | } 58 | 59 | class CheckedException2 extends CheckedException1 { 60 | } 61 | 62 | class UnCheckedException extends RuntimeException { 63 | } 64 | 65 | class UnCheckedException2 extends UnCheckedException { 66 | } 67 | 68 | class Connection { 69 | void open() { 70 | System.out.println("Connection Opened"); 71 | } 72 | 73 | void close() { 74 | System.out.println("Connection Closed"); 75 | } 76 | } 77 | 78 | public class ExceptionHandlingExample1 { 79 | 80 | public static void methodThrowCheckedException() throws RuntimeException { 81 | throw new RuntimeException(); 82 | } 83 | 84 | public static void methodSomething() { 85 | ExceptionHandlingExample1.methodThrowCheckedException(); 86 | } 87 | 88 | // Exception Handling Example 1 89 | // Let's add a try catch block in method2 90 | public static void main(String[] args) { 91 | method1(); 92 | System.out.println("Line after Exception - Main"); 93 | } 94 | 95 | private static void method1() { 96 | method2(); 97 | System.out.println("Line after Exception - Method 1"); 98 | } 99 | 100 | private static void method2() { 101 | Connection connection = new Connection(); 102 | connection.open(); 103 | try { 104 | return; 105 | } catch (Exception e) { 106 | 107 | } finally { 108 | // 1 109 | // 2 110 | // 3 111 | } 112 | } 113 | } 114 | 115 | // Connection Opened 116 | // Connection Closed 117 | // Exception in thread "main" java.lang.NullPointerException 118 | // at 119 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:33) 120 | // at 121 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:22) 122 | // at 123 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:17) 124 | ``` 125 | ### /com/in28minutes/java/exceptionhandling/ExceptionHandlingExample2.java 126 | ``` 127 | package com.in28minutes.java.exceptionhandling; 128 | 129 | //PLEASE GIVE ME A BREAK ON CODING STANDARDS 130 | class Amount { 131 | public Amount(String currency, int amount) { 132 | this.currency = currency; 133 | this.amount = amount; 134 | } 135 | 136 | String currency; 137 | int amount;// Should ideally use BigDecimal 138 | } 139 | 140 | class CurrenciesDoNotMatchException extends RuntimeException { 141 | } 142 | 143 | class AmountAdder { 144 | static Amount addAmounts(Amount amount1, Amount amount2) { 145 | if (!amount1.currency.equals(amount2.currency)) { 146 | throw new CurrenciesDoNotMatchException(); 147 | } 148 | return new Amount(amount1.currency, amount1.amount + amount2.amount); 149 | } 150 | } 151 | 152 | public class ExceptionHandlingExample2 { 153 | public static void main(String[] args) { 154 | try { 155 | AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 156 | 5)); 157 | String string = null; 158 | string.toString(); 159 | } catch (CurrenciesDoNotMatchException e) { 160 | System.out.println("Handled CurrenciesDoNotMatchException"); 161 | } 162 | } 163 | } 164 | ``` 165 | -------------------------------------------------------------------------------- /docs/inheritance-and-polymorphism.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/oops/inheritance/EveryClassExtendsObject.java 2 | ``` 3 | package com.in28minutes.java.oops.inheritance; 4 | 5 | //Every Java class extends Object class 6 | public class EveryClassExtendsObject { 7 | public void testMethod() throws CloneNotSupportedException { 8 | // toString,hashCode,clone methods are 9 | // inherited from Object class 10 | System.out.println(this.toString()); 11 | System.out.println(this.hashCode()); 12 | System.out.println(this.clone()); 13 | } 14 | 15 | public static void main(String[] args) throws CloneNotSupportedException { 16 | EveryClassExtendsObject example1 = new EveryClassExtendsObject(); 17 | 18 | EveryClassExtendsObject example2 = new EveryClassExtendsObject(); 19 | 20 | if (example1 instanceof Object) { 21 | System.out.println("I extend Object");// Will be printed 22 | } 23 | 24 | // equals method is inherited from Object class 25 | System.out.println(example1.equals(example2));// false 26 | 27 | } 28 | } 29 | ``` 30 | ### /com/in28minutes/java/oops/inheritance/InheritanceExamples.java 31 | ``` 32 | package com.in28minutes.java.oops.inheritance; 33 | 34 | abstract class Animal { 35 | String name; 36 | 37 | // cool functionality 38 | abstract String bark(); 39 | } 40 | 41 | class Dog extends Animal { 42 | String bark() { 43 | return "Bow Bow"; 44 | } 45 | } 46 | 47 | class Cat extends Animal { 48 | String bark() { 49 | return "Meow Meow"; 50 | } 51 | } 52 | 53 | public class InheritanceExamples { 54 | public static void main(String[] args) { 55 | Animal animal = new Cat(); 56 | System.out.println(animal.bark()); 57 | } 58 | } 59 | ``` 60 | ### /com/in28minutes/java/oops/inheritance/overloading/OverloadingRules.java 61 | ``` 62 | package com.in28minutes.java.oops.inheritance.overloading; 63 | 64 | public class OverloadingRules { 65 | } 66 | 67 | class Foo { 68 | public void doIt(int number) { 69 | System.out.println("test"); 70 | } 71 | } 72 | 73 | class Bar extends Foo { 74 | public void doIt(String str) { 75 | System.out.println("test"); 76 | } 77 | } 78 | ``` 79 | ### /com/in28minutes/java/oops/inheritance/overriding/OverridingRules.java 80 | ``` 81 | package com.in28minutes.java.oops.inheritance.overriding; 82 | 83 | import java.io.FileNotFoundException; 84 | 85 | public class OverridingRules { 86 | } 87 | 88 | class SuperClass { 89 | public void publicMethod() throws FileNotFoundException { 90 | 91 | } 92 | 93 | void protectedMethod() { 94 | 95 | } 96 | } 97 | 98 | class SubClass { 99 | // Cannot reduce visibility of SuperClass Method 100 | // So, only option is public 101 | // Cannot throw bigger exceptions than Super Class 102 | public void publicMethod() /* throws IOException */{ 103 | 104 | } 105 | 106 | // Can be overridden with public,(default) or protected 107 | // private would give COMPILE ERROR! 108 | public void protectedMethod() { 109 | 110 | } 111 | 112 | } 113 | ``` 114 | ### /com/in28minutes/java/oops/inheritance/polymorphism/Animal.java 115 | ``` 116 | package com.in28minutes.java.oops.inheritance.polymorphism; 117 | 118 | public class Animal { 119 | public String shout() { 120 | return "Don't Know!"; 121 | } 122 | } 123 | ``` 124 | ### /com/in28minutes/java/oops/inheritance/polymorphism/Cat.java 125 | ``` 126 | package com.in28minutes.java.oops.inheritance.polymorphism; 127 | 128 | class Cat extends Animal { 129 | // This is method overriding. 130 | // Method shout in Animal is being overridden. 131 | 132 | // Overriding Class cannot reduce visibility of the method. 133 | // So, shout method cannot be declared as protected. 134 | public String shout() { 135 | return "Meow Meow"; 136 | } 137 | } 138 | ``` 139 | ### /com/in28minutes/java/oops/inheritance/polymorphism/Dog.java 140 | ``` 141 | package com.in28minutes.java.oops.inheritance.polymorphism; 142 | 143 | class Dog extends Animal { 144 | public String shout() { 145 | return "BOW BOW"; 146 | } 147 | 148 | public void run() { 149 | 150 | } 151 | } 152 | ``` 153 | ### /com/in28minutes/java/oops/inheritance/polymorphism/TestPolymorphism.java 154 | ``` 155 | package com.in28minutes.java.oops.inheritance.polymorphism; 156 | 157 | public class TestPolymorphism { 158 | 159 | public static void main(String[] args) { 160 | Animal animal1 = new Animal(); 161 | System.out.println(animal1.shout()); // Don't Know! 162 | 163 | Animal animal2 = new Dog(); 164 | 165 | // Reference variable type => Animal 166 | // Object referred to => Dog 167 | // Dog's bark method is called. 168 | System.out.println(animal2.shout()); // BOW BOW 169 | 170 | // Even though dog has a method run,it cannot be 171 | // invoked using super class reference variable 172 | // animal2.run();//COMPILE ERROR 173 | } 174 | } 175 | ``` 176 | ### /com/in28minutes/java/oops/inheritance/reuse/Actor.java 177 | ``` 178 | package com.in28minutes.java.oops.inheritance.reuse; 179 | 180 | public class Actor { 181 | public void act() { 182 | System.out.println("Act"); 183 | }; 184 | } 185 | ``` 186 | ### /com/in28minutes/java/oops/inheritance/reuse/Comedian.java 187 | ``` 188 | package com.in28minutes.java.oops.inheritance.reuse; 189 | 190 | //IS-A relationship. Comedian is-a Actor 191 | public class Comedian extends Actor { 192 | public void performComedy() { 193 | System.out.println("Comedy"); 194 | }; 195 | } 196 | ``` 197 | ### /com/in28minutes/java/oops/inheritance/reuse/Hero.java 198 | ``` 199 | package com.in28minutes.java.oops.inheritance.reuse; 200 | 201 | //IS-A relationship. Hero is-a Actor 202 | public class Hero extends Actor { 203 | public void fight() { 204 | System.out.println("fight"); 205 | }; 206 | } 207 | ``` 208 | ### /com/in28minutes/java/oops/inheritance/reuse/TestReuse.java 209 | ``` 210 | package com.in28minutes.java.oops.inheritance.reuse; 211 | 212 | public class TestReuse { 213 | public static void main(String[] args) { 214 | Hero hero = new Hero(); 215 | // act method inherited from Actor 216 | hero.act();// Act 217 | hero.fight();// fight 218 | 219 | Comedian comedian = new Comedian(); 220 | // act method inherited from Actor 221 | comedian.act();// Act 222 | comedian.performComedy();// Comedy 223 | 224 | // Super class reference variable can hold 225 | // an object of sub class 226 | Actor actor1 = new Comedian(); 227 | Actor actor2 = new Hero(); 228 | 229 | // Object is super class of all java classes 230 | Object object = new Hero(); 231 | } 232 | } 233 | ``` 234 | -------------------------------------------------------------------------------- /docs/initializers.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/initializers/InitializerExamples.java 2 | ``` 3 | package com.in28minutes.java.initializers; 4 | 5 | public class InitializerExamples { 6 | static int count; 7 | int i; 8 | { 9 | // This is an instance initializers. Run every time an object is 10 | // created. 11 | // static and instance variables can be accessed 12 | System.out.println("Instance Initializer"); 13 | i = 6; 14 | count = count + 1; 15 | System.out 16 | .println("Count when Instance Initializer is run is " + count); 17 | } 18 | 19 | static { 20 | // This is a static initializers. Run only when Class is first loaded. 21 | // Only static variables can be accessed 22 | System.out.println("Static Initializer"); 23 | // i = 6;//COMPILER ERROR 24 | System.out.println("Count when Static Initializer is run is " + count); 25 | } 26 | 27 | public static void main(String[] args) { 28 | InitializerExamples example = new InitializerExamples();// Output below 29 | // Static Initializer 30 | // Count when Static Initializer is run is 0 31 | // Instance Initializer 32 | // Count when Instance Initializer is run is 1 33 | 34 | InitializerExamples example1 = new InitializerExamples();// Output below 35 | // Instance Initializer 36 | // Count when Instance Initializer is run is 2 37 | 38 | InitializerExamples example2 = new InitializerExamples();// Output below 39 | // Instance Initializer 40 | // Count when Instance Initializer is run is 3 41 | 42 | } 43 | 44 | } 45 | ``` 46 | -------------------------------------------------------------------------------- /docs/inner-class.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/innerclass/AnonymousClass.java 2 | ``` 3 | package com.in28minutes.java.innerclass; 4 | 5 | import java.util.Arrays; 6 | import java.util.Comparator; 7 | 8 | class Animal { 9 | void bark() { 10 | System.out.println("Animal Bark"); 11 | } 12 | }; 13 | 14 | public class AnonymousClass { 15 | 16 | private static String[] reverseSort(String[] array) { 17 | 18 | Comparator reverseComparator = new Comparator() { 19 | /* Anonymous Class */ 20 | @Override 21 | public int compare(String string1, String string2) { 22 | return string2.compareTo(string1); 23 | } 24 | 25 | }; 26 | 27 | Arrays.sort(array, reverseComparator); 28 | 29 | return array; 30 | } 31 | 32 | public static void main(String[] args) { 33 | 34 | String[] array = { "Apple", "Cat", "Boy" }; 35 | 36 | System.out.println(Arrays.toString(reverseSort(array)));// [Cat, Boy, 37 | // Apple] 38 | 39 | /* Second Anonymous Class - SubClass of Animal */ 40 | Animal animal = new Animal() { 41 | void bark() { 42 | System.out.println("Subclass bark"); 43 | } 44 | }; 45 | 46 | animal.bark();// Subclass bark 47 | 48 | } 49 | 50 | } 51 | ``` 52 | ### /com/in28minutes/java/innerclass/InnerClassExamples.java 53 | ``` 54 | package com.in28minutes.java.innerclass; 55 | 56 | class OuterClass { 57 | private int outerClassInstanceVariable; 58 | 59 | public void exampleMethod() { 60 | int localVariable; 61 | final int finalVariable = 5; 62 | 63 | class MethodLocalInnerClass { 64 | public void method() { 65 | // Can access class instance variables 66 | System.out.println(outerClassInstanceVariable); 67 | 68 | // Cannot access method's non-final local variables 69 | // localVariable = 5;//Compiler Error 70 | System.out.println(finalVariable);// Final variable is fine.. 71 | } 72 | } 73 | 74 | // MethodLocalInnerClass can be instantiated only in this method 75 | MethodLocalInnerClass m1 = new MethodLocalInnerClass(); 76 | m1.method(); 77 | } 78 | 79 | // MethodLocalInnerClass can be instantiated only in the method where it is 80 | // declared 81 | // MethodLocalInnerClass m1 = new MethodLocalInnerClass();//COMPILER ERROR 82 | 83 | public static class StaticNestedClass { 84 | private int staticNestedClassVariable; 85 | 86 | public int getStaticNestedClassVariable() { 87 | return staticNestedClassVariable; 88 | } 89 | 90 | public void setStaticNestedClassVariable(int staticNestedClassVariable) { 91 | this.staticNestedClassVariable = staticNestedClassVariable; 92 | } 93 | 94 | public void privateVariablesOfOuterClassAreNOTAvailable() { 95 | // outerClassInstanceVariable = 5; //COMPILE ERROR 96 | } 97 | } 98 | 99 | public class InnerClass { 100 | private int innerClassVariable; 101 | 102 | public int getInnerClassVariable() { 103 | return innerClassVariable; 104 | } 105 | 106 | public void setInnerClassVariable(int innerClassVariable) { 107 | this.innerClassVariable = innerClassVariable; 108 | } 109 | 110 | public void privateVariablesOfOuterClassAreAvailable() { 111 | outerClassInstanceVariable = 5; // we can access the value and 112 | // change it 113 | 114 | System.out.println("Inner class ref is " + this); 115 | 116 | // Accessing outer class reference variable 117 | System.out.println("Outer class ref is " + OuterClass.this); 118 | } 119 | } 120 | 121 | public void createInnerClass() { 122 | // Just use the inner class name to create it 123 | InnerClass inner = new InnerClass(); 124 | } 125 | 126 | } 127 | 128 | public class InnerClassExamples { 129 | public static void main(String[] args) { 130 | // Static Nested Class can be created without needing to create its 131 | // parent. Without creating NestedClassesExample, we created 132 | // StaticNestedClass 133 | OuterClass.StaticNestedClass staticNestedClass1 = new OuterClass.StaticNestedClass(); 134 | staticNestedClass1.setStaticNestedClassVariable(5); 135 | 136 | OuterClass.StaticNestedClass staticNestedClass2 = new OuterClass.StaticNestedClass(); 137 | staticNestedClass2.setStaticNestedClassVariable(10); 138 | 139 | // Static Nested Class member variables are not static. They can have 140 | // different values. 141 | System.out.println(staticNestedClass1.getStaticNestedClassVariable()); // 5 142 | System.out.println(staticNestedClass2.getStaticNestedClassVariable()); // 10 143 | 144 | // COMPILER ERROR! You cannot create an inner class on its own. 145 | // InnerClass innerClass = new InnerClass(); 146 | OuterClass example = new OuterClass(); 147 | 148 | // To create an Inner Class you need an instance of Outer Class 149 | OuterClass.InnerClass innerClass = example.new InnerClass(); 150 | 151 | } 152 | } 153 | ``` 154 | -------------------------------------------------------------------------------- /docs/interfaces.md: -------------------------------------------------------------------------------- 1 | ``` 2 | ### /com/in28minutes/java/oops/interfaces/Aeroplane.java 3 | ``` 4 | package com.in28minutes.java.oops.interfaces; 5 | 6 | public class Aeroplane implements Flyable { 7 | public void fly() { 8 | System.out.println("Aeroplane is flying"); 9 | } 10 | } 11 | ``` 12 | ### /com/in28minutes/java/oops/interfaces/Bird.java 13 | ``` 14 | package com.in28minutes.java.oops.interfaces; 15 | public class Bird implements Flyable { 16 | public void fly() { 17 | System.out.println("Bird is flying"); 18 | } 19 | } 20 | ``` 21 | ### /com/in28minutes/java/oops/interfaces/Flyable.java 22 | ``` 23 | package com.in28minutes.java.oops.interfaces; 24 | 25 | public interface Flyable { 26 | void fly(); 27 | } 28 | ``` 29 | ### /com/in28minutes/java/oops/interfaces/IntefaceRules.java 30 | ``` 31 | package com.in28minutes.java.oops.interfaces; 32 | 33 | public class IntefaceRules { 34 | } 35 | 36 | interface ExampleInterface1 { 37 | // By default - public static final. No other modifier allowed 38 | // value1,value2,value3,value4 all are - public static final 39 | int value1 = 10; 40 | public int value2 = 15; 41 | public static int value3 = 20; 42 | public static final int value4 = 25; 43 | 44 | // private int value5 = 10;//COMPILER ERROR 45 | 46 | // By default - public abstract. No other modifier allowed 47 | void method1();// method1 is public and abstract 48 | // private void method6();//COMPILER ERROR! 49 | 50 | //Interface can have a default definition of method. 51 | //NEW FEATURE 52 | default void method5() { 53 | System.out.println("Method5"); 54 | } 55 | 56 | } 57 | 58 | interface ExampleInterface2 { 59 | void method2(); 60 | } 61 | 62 | // An interface can extend another interface 63 | // Class implementing SubInterface1 should 64 | // implement method3 and method1(from ExampleInterface1) 65 | interface SubInterface1 extends ExampleInterface1 { 66 | void method3(); 67 | } 68 | 69 | /* 70 | * //COMPILE ERROR IF UnCommented //Interface cannot extend a Class interface 71 | * SubInterface2 extends InterfaceRules{ void method3(); } 72 | */ 73 | 74 | /* A Class can implement multiple interfaces */ 75 | class SampleImpl implements ExampleInterface1, ExampleInterface2 { 76 | /* 77 | * A class should implement all the methods in an interface. If either of 78 | * method1 or method2 is commented, it would result in compilation error. 79 | */ 80 | public void method2() { 81 | System.out.println("Sample Implementation for Method2"); 82 | } 83 | 84 | public void method1() { 85 | System.out.println("Sample Implementation for Method1"); 86 | } 87 | 88 | } 89 | ``` 90 | ### /com/in28minutes/java/oops/interfaces/InterfaceExamples.java 91 | ``` 92 | package com.in28minutes.java.oops.interfaces; 93 | 94 | public class InterfaceExamples { 95 | public static void main(String[] args) { 96 | Flyable flyable = new Bird(); 97 | flyable.fly(); 98 | } 99 | } 100 | ``` 101 | ### /com/in28minutes/java/oops/interfaces/InterfaceTest.java 102 | ``` 103 | package com.in28minutes.java.oops.interfaces; 104 | 105 | 106 | public class InterfaceTest { 107 | public static void main(String[] args) { 108 | Bird bird = new Bird(); 109 | bird.fly();// Bird is flying 110 | 111 | Aeroplane aeroplane = new Aeroplane(); 112 | aeroplane.fly();// Aeroplane is flying 113 | 114 | // An interface reference variable can hold 115 | // objects of any implementation of interface 116 | Flyable flyable1 = new Bird(); 117 | Flyable flyable2 = new Aeroplane(); 118 | 119 | } 120 | } 121 | ``` 122 | -------------------------------------------------------------------------------- /docs/modifiers-class-access.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/classmodifiers/defaultaccess/a/AnotherClassInSamePackage.java 2 | ``` 3 | package com.in28minutes.java.classmodifiers.defaultaccess.a; 4 | 5 | public class AnotherClassInSamePackage { 6 | // DefaultAccessClass and AnotherClassInSamePackage 7 | // are in same package. 8 | // So, DefaultAccessClass is visible. 9 | // An instance of the class can be created. 10 | 11 | DefaultAccessClass defaultAccess; 12 | } 13 | ``` 14 | ### /com/in28minutes/java/classmodifiers/defaultaccess/a/DefaultAccessClass.java 15 | ``` 16 | package com.in28minutes.java.classmodifiers.defaultaccess.a; 17 | 18 | /* No public before class. So this class has default access*/ 19 | class DefaultAccessClass { 20 | // Default access is also called package access 21 | } 22 | ``` 23 | ### /com/in28minutes/java/classmodifiers/defaultaccess/b/ClassInDifferentPackage.java 24 | ``` 25 | package com.in28minutes.java.classmodifiers.defaultaccess.b; 26 | 27 | public class ClassInDifferentPackage { 28 | // Class DefaultAccessClass and Class ClassInDifferentPackage 29 | // are in different packages (*.a and *.b) 30 | // So, DefaultAccessClass is not visible to ClassInDifferentPackage 31 | 32 | // Below line of code will cause compilation error if uncommented 33 | // DefaultAccessClass defaultAccess; //COMPILE ERROR!! 34 | } 35 | ``` 36 | -------------------------------------------------------------------------------- /docs/modifiers-members-access.md: -------------------------------------------------------------------------------- 1 | 2 | ### /com/in28minutes/java/membermodifiers/access/different/SubClassInDifferentPackage.java 3 | ``` 4 | package com.in28minutes.java.membermodifiers.access.different; 5 | 6 | import com.in28minutes.java.membermodifiers.access.ExampleClass; 7 | 8 | public class SubClassInDifferentPackage extends ExampleClass { 9 | 10 | void subClassMethod() { 11 | publicVariable = 5; 12 | publicMethod(); 13 | 14 | // privateVariable is not visible to SubClass 15 | // Below Line, uncommented, would give compiler error 16 | // privateVariable=5; //COMPILE ERROR 17 | // privateMethod(); 18 | 19 | protectedVariable = 5; 20 | protectedMethod(); 21 | 22 | // privateVariable is not visible to SubClass 23 | // Below Line, uncommented, would give compiler error 24 | // defaultVariable = 5; //COMPILE ERROR 25 | // defaultMethod(); 26 | } 27 | } 28 | ``` 29 | ### /com/in28minutes/java/membermodifiers/access/different/TestClassInDifferentPackage.java 30 | ``` 31 | package com.in28minutes.java.membermodifiers.access.different; 32 | 33 | import com.in28minutes.java.membermodifiers.access.ExampleClass; 34 | 35 | public class TestClassInDifferentPackage { 36 | public static void main(String[] args) { 37 | ExampleClass example = new ExampleClass(); 38 | 39 | example.publicVariable = 5; 40 | example.publicMethod(); 41 | 42 | // privateVariable,privateMethod are not visible 43 | // Below Lines, uncommented, would give compiler error 44 | // example.privateVariable=5; //COMPILE ERROR 45 | // example.privateMethod();//COMPILE ERROR 46 | 47 | // protectedVariable,protectedMethod are not visible 48 | // Below Lines, uncommented, would give compiler error 49 | // example.protectedVariable = 5; //COMPILE ERROR 50 | // example.protectedMethod();//COMPILE ERROR 51 | 52 | // defaultVariable,defaultMethod are not visible 53 | // Below Lines, uncommented, would give compiler error 54 | // example.defaultVariable = 5;//COMPILE ERROR 55 | // example.defaultMethod();//COMPILE ERROR 56 | } 57 | } 58 | ``` 59 | ### /com/in28minutes/java/membermodifiers/access/ExampleClass.java 60 | ``` 61 | package com.in28minutes.java.membermodifiers.access; 62 | 63 | public class ExampleClass { 64 | int defaultVariable; 65 | public int publicVariable; 66 | private int privateVariable; 67 | protected int protectedVariable; 68 | 69 | void defaultMethod() { 70 | privateVariable = 5; 71 | } 72 | 73 | public void publicMethod() { 74 | 75 | } 76 | 77 | private void privateMethod() { 78 | 79 | } 80 | 81 | protected void protectedMethod() { 82 | 83 | } 84 | } 85 | ``` 86 | ### /com/in28minutes/java/membermodifiers/access/SubClassInSamePackage.java 87 | ``` 88 | package com.in28minutes.java.membermodifiers.access; 89 | 90 | public class SubClassInSamePackage extends ExampleClass { 91 | 92 | void subClassMethod() { 93 | publicVariable = 5; 94 | publicMethod(); 95 | 96 | // privateVariable is not visible to SubClass 97 | // Below Line, uncommented, would give compiler error 98 | // privateVariable=5; //COMPILE ERROR 99 | // privateMethod(); 100 | 101 | protectedVariable = 5; 102 | protectedMethod(); 103 | 104 | defaultVariable = 5; 105 | defaultMethod(); 106 | } 107 | } 108 | ``` 109 | ### /com/in28minutes/java/membermodifiers/access/TestClassInSamePackage.java 110 | ``` 111 | package com.in28minutes.java.membermodifiers.access; 112 | 113 | public class TestClassInSamePackage { 114 | public static void main(String[] args) { 115 | ExampleClass example = new ExampleClass(); 116 | 117 | example.publicVariable = 5; 118 | example.publicMethod(); 119 | 120 | // privateVariable is not visible 121 | // Below Line, uncommented, would give compiler error 122 | // example.privateVariable=5; //COMPILE ERROR 123 | // example.privateMethod(); 124 | 125 | example.protectedVariable = 5; 126 | example.protectedMethod(); 127 | 128 | example.defaultVariable = 5; 129 | example.defaultMethod(); 130 | } 131 | } 132 | ``` 133 | -------------------------------------------------------------------------------- /docs/modifiers-nonaccess-final.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/classmodifiers/nonaccess/finalclass/FinalClass.java 2 | ``` 3 | package com.in28minutes.java.classmodifiers.nonaccess.finalclass; 4 | 5 | final public class FinalClass { 6 | } 7 | 8 | // Below class will not compile if uncommented 9 | // FinalClass cannot be extended 10 | /* 11 | * class ExtendingFinalClass extends FinalClass{ 12 | * 13 | * } 14 | */ 15 | ``` 16 | ### /com/in28minutes/java/membermodifiers/nonaccess/FinalMemberModifiersExample.java 17 | ``` 18 | package com.in28minutes.java.membermodifiers.nonaccess; 19 | 20 | public class FinalMemberModifiersExample { 21 | final int FINAL_VALUE = 5; 22 | 23 | final void finalMethod() { 24 | // final value cannot be modified 25 | // Below line, uncommented, causes compilation Error 26 | // FINAL_VALUE = 6;//COMPILER ERROR 27 | } 28 | 29 | void testMethod(final int finalArgument) { 30 | // final argument cannot be modified 31 | // Below line, uncommented, causes compilation Error 32 | // finalArgument = 5;//COMPILER ERROR 33 | } 34 | } 35 | 36 | class SubClass extends FinalMemberModifiersExample { 37 | // final method cannot be over-riddent 38 | // Below method, uncommented, causes compilation Error 39 | /* 40 | * final void finalMethod(){ 41 | * 42 | * } 43 | */ 44 | } 45 | ``` 46 | -------------------------------------------------------------------------------- /docs/modifiers-nonaccess-static: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/membermodifiers/nonaccess/StaticModifierExamples.java 2 | ``` 3 | package com.in28minutes.java.membermodifiers.nonaccess; 4 | 5 | class Cricketer { 6 | private static int count; 7 | 8 | public Cricketer() { 9 | count++; 10 | } 11 | 12 | static int getCount() { 13 | return count; 14 | } 15 | } 16 | 17 | class Animal { 18 | static void StaticMethod() { 19 | System.out.println("Animal Static Method"); 20 | } 21 | } 22 | 23 | class Dog extends Animal { 24 | static void StaticMethod() { 25 | System.out.println("Dog Static Method"); 26 | } 27 | } 28 | 29 | public class StaticModifierExamples { 30 | private static int staticVariable; 31 | private int instanceVariable; 32 | 33 | public static void staticMethod() { 34 | // instance variables are not accessible in static methods 35 | // instanceVariable = 10; //COMPILER ERROR 36 | 37 | // Also, this Keyword is not accessible.this refers to object. 38 | // static methods are class methods 39 | 40 | // static variables are accessible in static methods 41 | staticVariable = 10; 42 | } 43 | 44 | public void instanceMethod() { 45 | // static and instance variables are accessible in instance methods 46 | instanceVariable = 10; 47 | staticVariable = 10; 48 | } 49 | 50 | public static void main(String[] args) { 51 | // static int i =5; //COMPILER ERROR 52 | StaticModifierExamples example = new StaticModifierExamples(); 53 | 54 | // instance variables and methods are only accessible through object 55 | // references 56 | example.instanceVariable = 10; 57 | example.instanceMethod(); 58 | // StaticModifierExamples.instanceVariable = 10;//COMPILER ERROR 59 | // StaticModifierExamples.instanceMethod();//COMPILER ERROR 60 | 61 | // static variables and methods are accessible through object references 62 | // and Class Name. 63 | example.staticVariable = 10; 64 | example.staticMethod(); 65 | StaticModifierExamples.staticVariable = 10; 66 | StaticModifierExamples.staticMethod(); 67 | 68 | // It is always recommended to use Class Name to access a static 69 | // variable or method. 70 | // This is because static methods are class level methods. It is not 71 | // appropriate 72 | // to use instance references to call static methods (even though it 73 | // compiles and works). 74 | 75 | Cricketer cricketer1 = new Cricketer(); 76 | Cricketer cricketer2 = new Cricketer(); 77 | Cricketer cricketer3 = new Cricketer(); 78 | Cricketer cricketer4 = new Cricketer(); 79 | 80 | System.out.println(Cricketer.getCount());// 4 81 | 82 | Animal animal = new Dog(); 83 | animal.StaticMethod();// Animal Static Method 84 | 85 | } 86 | } 87 | ``` 88 | -------------------------------------------------------------------------------- /docs/object-methods.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/object/EqualsHashCodeExamples.java 2 | ``` 3 | package com.in28minutes.java.object; 4 | 5 | class Client { 6 | private int id; 7 | 8 | public Client(int id) { 9 | this.id = id; 10 | } 11 | 12 | @Override 13 | public int hashCode() { 14 | final int prime = 31; 15 | int result = 1; 16 | result = prime * result + id; 17 | return result; 18 | } 19 | 20 | @Override 21 | public boolean equals(Object obj) { 22 | if (this == obj) 23 | return true; 24 | if (obj == null) 25 | return false; 26 | if (getClass() != obj.getClass()) 27 | return false; 28 | Client other = (Client) obj; 29 | if (id != other.id) 30 | return false; 31 | return true; 32 | } 33 | 34 | } 35 | 36 | public class EqualsHashCodeExamples { 37 | 38 | public static void main(String[] args) { 39 | 40 | // == comparison operator checks if the object references are pointing 41 | // to the same object. It does NOT look at the content of the object. 42 | Client client1 = new Client(25); 43 | Client client2 = new Client(25); 44 | Client client3 = client1; 45 | 46 | System.out.println(client1.equals(client2));// true 47 | System.out.println(client1.equals(client3));// true 48 | 49 | } 50 | } 51 | ``` 52 | ### /com/in28minutes/java/object/ToStringExamples.java 53 | ``` 54 | package com.in28minutes.java.object; 55 | 56 | class Animal { 57 | 58 | public Animal(String name, String type) { 59 | this.name = name; 60 | this.type = type; 61 | } 62 | 63 | String name; 64 | String type; 65 | 66 | public String toString() { 67 | return "Animal [name=" + name + ", type=" + type + "]"; 68 | } 69 | 70 | } 71 | 72 | public class ToStringExamples { 73 | public static void main(String[] args) { 74 | Animal animal = new Animal("Tommy", "Dog"); 75 | System.out.println(animal);// Animal [name=Tommy, type=Dog] 76 | } 77 | } 78 | ``` 79 | -------------------------------------------------------------------------------- /docs/oops-advanced.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/oops/cohesion/problem/CohesionExampleProblem.java 2 | ``` 3 | package com.in28minutes.java.oops.cohesion.problem; 4 | 5 | //Cohesion is a measure of how related the responsibilities of a class are. 6 | //This class is downloading from internet, parsing data and storing data to database. 7 | //The responsibilities of this class are not really related. This is not cohesive class. 8 | class DownloadAndStore { 9 | void downloadFromInternet() { 10 | 11 | } 12 | 13 | void parseData() { 14 | 15 | } 16 | 17 | void storeIntoDatabase() { 18 | 19 | } 20 | 21 | void doEverything() { 22 | downloadFromInternet(); 23 | parseData(); 24 | storeIntoDatabase(); 25 | } 26 | } 27 | 28 | public class CohesionExampleProblem { 29 | 30 | } 31 | ``` 32 | ### /com/in28minutes/java/oops/cohesion/solution/CohesionExampleSolution.java 33 | ``` 34 | package com.in28minutes.java.oops.cohesion.solution; 35 | 36 | //This is a better way of approaching the problem. Different classes have their 37 | //own responsibilities. 38 | 39 | class InternetDownloader { 40 | public void downloadFromInternet() { 41 | 42 | } 43 | } 44 | 45 | class DataParser { 46 | public void parseData(String content) { 47 | } 48 | } 49 | 50 | class DatabaseStorer { 51 | public void storeIntoDatabase(String data) { 52 | } 53 | } 54 | 55 | class DownloadAndStore { 56 | void doEverything() { 57 | new InternetDownloader().downloadFromInternet(); 58 | new DataParser().parseData(""); 59 | new DatabaseStorer().storeIntoDatabase(""); 60 | } 61 | } 62 | 63 | public class CohesionExampleSolution { 64 | 65 | } 66 | ``` 67 | ### /com/in28minutes/java/oops/coupling/problem/CouplingExamplesProblem.java 68 | ``` 69 | package com.in28minutes.java.oops.coupling.problem; 70 | 71 | //Coupling is a measure of how much a class is dependent on other classes. 72 | //There should minimal dependencies between classes. 73 | //Consider the example below: 74 | 75 | class ShoppingCartEntry { 76 | public float price; 77 | public int quantity; 78 | } 79 | 80 | class ShoppingCart { 81 | public ShoppingCartEntry[] items; 82 | } 83 | 84 | class Order { 85 | private ShoppingCart cart; 86 | private float salesTax; 87 | 88 | public Order(ShoppingCart cart, float salesTax) { 89 | this.cart = cart; 90 | this.salesTax = salesTax; 91 | } 92 | 93 | // This method know the internal details of ShoppingCartEntry and 94 | // ShoppingCart classes. If there is any change in any of those 95 | // classes, this method also needs to change. 96 | public float orderTotalPrice() { 97 | float cartTotalPrice = 0; 98 | for (int i = 0; i < cart.items.length; i++) { 99 | cartTotalPrice += cart.items[i].price * cart.items[i].quantity; 100 | } 101 | cartTotalPrice += cartTotalPrice * salesTax; 102 | return cartTotalPrice; 103 | } 104 | } 105 | 106 | public class CouplingExamplesProblem { 107 | 108 | } 109 | ``` 110 | ### /com/in28minutes/java/oops/coupling/solution/CouplingExamplesSolution.java 111 | ``` 112 | package com.in28minutes.java.oops.coupling.solution; 113 | 114 | class ShoppingCartEntry { 115 | float pricedummy; 116 | int quantity; 117 | 118 | public float getTotalPrice() { 119 | return pricedummy * quantity; 120 | } 121 | } 122 | 123 | class CartContents { 124 | ShoppingCartEntry[] items; 125 | 126 | public float getTotalPrice() { 127 | float totalPrice = 0; 128 | for (ShoppingCartEntry item : items) { 129 | totalPrice += item.getTotalPrice(); 130 | } 131 | return totalPrice; 132 | } 133 | } 134 | 135 | class Order { 136 | private CartContents cart; 137 | private float salesTax; 138 | 139 | public Order(CartContents cart, float salesTax) { 140 | this.cart = cart; 141 | this.salesTax = salesTax; 142 | } 143 | 144 | public float totalPrice() { 145 | return cart.getTotalPrice() * (1.0f + salesTax); 146 | } 147 | } 148 | 149 | public class CouplingExamplesSolution { 150 | 151 | } 152 | ``` 153 | ### /com/in28minutes/java/oops/encapsulation/EncapsulationExample.java 154 | ``` 155 | package com.in28minutes.java.oops.encapsulation; 156 | 157 | class CricketScorer { 158 | private int score = 0; 159 | 160 | public int getScore() { 161 | return score; 162 | } 163 | 164 | public void addRuns(int score) { 165 | this.score = this.score + score; 166 | } 167 | 168 | public void six() { 169 | addRuns(6); 170 | } 171 | 172 | public void four() { 173 | addRuns(4); 174 | } 175 | 176 | public void single() { 177 | addRuns(1); 178 | } 179 | 180 | public void printScore() { 181 | System.out.println("Score : " + score); 182 | } 183 | 184 | } 185 | 186 | public class EncapsulationExample { 187 | public static void main(String[] args) { 188 | CricketScorer scorer = new CricketScorer(); 189 | scorer.four(); 190 | scorer.four(); 191 | scorer.single(); 192 | scorer.six(); 193 | scorer.six(); 194 | scorer.six(); 195 | scorer.printScore(); 196 | } 197 | } 198 | ``` 199 | -------------------------------------------------------------------------------- /docs/others-assert.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/others/assertexample/AssertExamples.java 2 | ``` 3 | package com.in28minutes.java.others.assertexample; 4 | 5 | public class AssertExamples { 6 | // Assertions are introduced in Java 1.4. They enable you to validate 7 | // assumptions. 8 | // If an assert fails (i.e. returns false), AssertionError is thrown (if 9 | // assertions are enabled). 10 | 11 | // assert is a keyword in java since 1.4. Before 1.4, assert can be used as 12 | // identifier. 13 | // To compile code using 1.3 you can use the command below 14 | // javac -source 1.3 OldCode.java => assert can be used as identifier 15 | // with -source 1.4,1.5,5,1.6,6 => assert cannot be used as identifier 16 | 17 | // assertions can easily be enabled and disabled. 18 | 19 | // assertions are disabled by default. 20 | 21 | // Enable assertions : java -ea com.rithus.AssertExamples 22 | // (OR) java -enableassertions com.rithus.AssertExamples 23 | 24 | // Disable assertions : java -da com.rithus.AssertExamples 25 | // (OR) java -disableassertions com.rithus.AssertExamples 26 | 27 | // Selectively enable assertions in a package only 28 | // java -ea:com.rithus 29 | 30 | // Selectively enable assertions in a package and its subpackages only 31 | // java -ea:com.rithus... 32 | 33 | // Enable assertions including system classes 34 | // java -ea -esa 35 | 36 | // Basic assert is shown in the example below 37 | private int computerSimpleInterest(int principal, float interest, int years) { 38 | assert (principal > 0); 39 | return 100; 40 | } 41 | 42 | // If needed debugging information can be added to an assert. 43 | // Look at the example below. 44 | private int computeCompoundInterest(int principal, float interest, int years) { 45 | // condition is always boolean 46 | // second parameter can be anything that converts to a String. 47 | assert (principal > 0) : "principal is " + principal; 48 | return 100; 49 | } 50 | 51 | public static void main(String[] args) { 52 | AssertExamples examples = new AssertExamples(); 53 | System.out.println(examples.computerSimpleInterest(-1000, 1.0f, 5)); 54 | } 55 | 56 | // Assertions should not be used to validate input data to a public method 57 | // or command line argument. 58 | // IllegalArgumentException would be a better option. 59 | 60 | // In public method, only use assertions to check for cases which are never 61 | // supposed to happen. 62 | } 63 | ``` 64 | -------------------------------------------------------------------------------- /docs/others-date-calendar.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/others/date/CalendarExamples.java 2 | ``` 3 | package com.in28minutes.java.others.date; 4 | 5 | import java.text.DateFormat; 6 | import java.util.Calendar; 7 | import java.util.GregorianCalendar; 8 | 9 | public class CalendarExamples { 10 | public static void main(String[] args) { 11 | // Calendar is abstract 12 | // Calendar calendar = new Calendar(); //COMPILER ERROR 13 | 14 | Calendar calendar = Calendar.getInstance(); 15 | 16 | calendar.set(Calendar.DATE, 24); 17 | calendar.set(Calendar.MONTH, 8);// 8 - September 18 | calendar.set(Calendar.YEAR, 2010); 19 | 20 | // Get information about 24th September 2010 21 | System.out.println(calendar.get(Calendar.YEAR));// 2010 22 | System.out.println(calendar.get(Calendar.MONTH));// 8 23 | System.out.println(calendar.get(Calendar.DATE));// 24 24 | System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));// 4 25 | System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));// 39 26 | System.out.println(calendar.get(Calendar.DAY_OF_YEAR));// 267 27 | System.out.println(calendar.getFirstDayOfWeek());// 1 -> Calendar.SUNDAY 28 | 29 | // Add/Manipulate date 30 | calendar.add(Calendar.DATE, 5); 31 | System.out.println(calendar.getTime());// Wed Sep 29 2010 32 | calendar.add(Calendar.MONTH, 1); 33 | System.out.println(calendar.getTime());// Fri Oct 29 2010 34 | calendar.add(Calendar.YEAR, 2); 35 | System.out.println(calendar.getTime());// Mon Oct 29 2012 36 | 37 | // Roll method will only the change the value being modified. 38 | // YEAR remains unaffected when MONTH is changed for instance. 39 | calendar.roll(Calendar.MONTH, 5); 40 | System.out.println(calendar.getTime());// Mon Mar 29 2012 41 | 42 | // Other way of creating calendar 43 | Calendar gregorianCalendar = new GregorianCalendar(2011, 7, 15); 44 | 45 | // Formatting Calendar 46 | // Done by getting the date using calendar.getTime() and 47 | // using the usual formatting of dates. 48 | System.out.println(DateFormat.getInstance().format(calendar.getTime()));// 3/29/12 49 | // 11:39 50 | // AM 51 | 52 | } 53 | 54 | } 55 | ``` 56 | ### /com/in28minutes/java/others/date/DateExamples.java 57 | ``` 58 | package com.in28minutes.java.others.date; 59 | 60 | import java.text.DateFormat; 61 | import java.text.ParseException; 62 | import java.text.SimpleDateFormat; 63 | import java.util.Date; 64 | import java.util.Locale; 65 | 66 | public class DateExamples { 67 | public static void main(String[] args) throws ParseException { 68 | // Important points about Date 69 | // Date is no longer the class Java recommends for storing and 70 | // manipulating date and time. Most of methods in Date are deprecated. 71 | // Use Calendar class instead. 72 | // Date internally represents date-time as number of milliseconds (a 73 | // long value) since 1st Jan 1970. 74 | 75 | // Creating Date Object 76 | Date now = new Date(); 77 | System.out.println(now.getTime()); 78 | 79 | // Manipulating Date Object 80 | Date date = new Date(); 81 | 82 | // Increase time by 6 hrs 83 | date.setTime(date.getTime() + 6 * 60 * 60 * 1000); 84 | System.out.println(date); 85 | 86 | // Decrease time by 6 hrs 87 | date = new Date(); 88 | date.setTime(date.getTime() - 6 * 60 * 60 * 1000); 89 | System.out.println(date); 90 | 91 | // Formatting Dates 92 | System.out.println(DateFormat.getInstance().format(date));// 10/16/12 93 | // 5:18 AM 94 | 95 | // Formatting Dates with a locale 96 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL, 97 | new Locale("it", "IT")).format(date));// marted� 16 ottobre 2012 98 | 99 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL, 100 | Locale.ITALIAN).format(date));// marted� 16 ottobre 2012 101 | 102 | // This uses default locale US 103 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL).format( 104 | date));// Tuesday, October 16, 2012 105 | 106 | System.out.println(DateFormat.getDateInstance().format(date));// Oct 16, 107 | // 2012 108 | System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format( 109 | date));// 10/16/12 110 | System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM) 111 | .format(date));// Oct 16, 2012 112 | 113 | System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format( 114 | date));// October 16, 2012 115 | 116 | // Formatting Dates Using SimpleDateFormat 117 | System.out.println(new SimpleDateFormat("yy-MM-dd").format(date));// 12-10-16 118 | System.out.println(new SimpleDateFormat("yy-MMM-dd").format(date));// 12-Oct-16 119 | System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));// 2012-10-16 120 | 121 | // Parse Dates using DateFormat 122 | Date date2 = DateFormat.getDateInstance(DateFormat.SHORT).parse( 123 | "10/16/12"); 124 | System.out.println(date2);// Tue Oct 16 00:00:00 GMT+05:30 2012 125 | 126 | // Creating Dates using SimpleDateFormat 127 | Date date1 = new SimpleDateFormat("yy-MM-dd").parse("12-10-16"); 128 | System.out.println(date1);// Tue Oct 16 00:00:00 GMT+05:30 2012 129 | 130 | // Print the country of locale 131 | Locale defaultLocale = Locale.getDefault(); 132 | 133 | System.out.println(defaultLocale.getDisplayCountry());// United States 134 | System.out.println(defaultLocale.getDisplayLanguage());// English 135 | } 136 | } 137 | ``` 138 | -------------------------------------------------------------------------------- /docs/serialization.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/serialization/SerializationExamples.java 2 | ``` 3 | package com.in28minutes.java.serialization; 4 | 5 | import java.io.FileInputStream; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.ObjectInputStream; 9 | import java.io.ObjectOutputStream; 10 | import java.io.Serializable; 11 | 12 | class Rectangle implements Serializable { 13 | public Rectangle(int length, int breadth) { 14 | this.length = length; 15 | this.breadth = breadth; 16 | area = length * breadth; 17 | } 18 | 19 | int length; 20 | int breadth; 21 | transient int area; 22 | 23 | private void writeObject(ObjectOutputStream os) throws IOException { 24 | // Do whatever java does usually when serialization is called 25 | os.defaultWriteObject(); 26 | } 27 | 28 | private void readObject(ObjectInputStream is) throws IOException, 29 | ClassNotFoundException { 30 | // Do whatever java does usually when de-serialization is called 31 | is.defaultReadObject(); 32 | // In addition, calculate area also 33 | area = this.length * this.breadth; 34 | } 35 | } 36 | 37 | public class SerializationExamples { 38 | 39 | public static void main(String[] args) throws IOException, 40 | ClassNotFoundException { 41 | // Serialization helps us to save and retrieve the state of an object. 42 | // Serialization => Convert object state to some internal object 43 | // representation. 44 | // De-Serialization => The reverse. Convert internal representation to 45 | // object. 46 | // Two important methods 47 | // ObjectOutputStream.writeObject() // serialize and write to file 48 | // ObjectInputStream.readObject() // read from file and deserialize 49 | 50 | // To serialize an object it should implement Serializable interface 51 | // class Rectangle implements Serializable 52 | 53 | // Serializing an object 54 | FileOutputStream fileStream = new FileOutputStream("Rectangle.ser"); 55 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 56 | objectStream.writeObject(new Rectangle(5, 6)); 57 | objectStream.close(); 58 | 59 | // Deserializing an object 60 | FileInputStream fileInputStream = new FileInputStream("Rectangle.ser"); 61 | ObjectInputStream objectInputStream = new ObjectInputStream( 62 | fileInputStream); 63 | Rectangle rectangle = (Rectangle) objectInputStream.readObject(); 64 | objectInputStream.close(); 65 | System.out.println(rectangle.length);// 5 66 | System.out.println(rectangle.breadth);// 6 67 | System.out.println(rectangle.area);// 30 68 | } 69 | } 70 | ``` 71 | ### /com/in28minutes/java/serialization/SerializationExamples2.java 72 | ``` 73 | package com.in28minutes.java.serialization; 74 | 75 | import java.io.FileOutputStream; 76 | import java.io.IOException; 77 | import java.io.ObjectOutputStream; 78 | import java.io.Serializable; 79 | 80 | class House implements Serializable { 81 | public House(int number) { 82 | super(); 83 | this.number = number; 84 | } 85 | 86 | Wall wall; 87 | int number; 88 | } 89 | 90 | class Wall implements Serializable { 91 | int length; 92 | int breadth; 93 | int color; 94 | } 95 | 96 | public class SerializationExamples2 { 97 | 98 | public static void main(String[] args) throws IOException { 99 | 100 | FileOutputStream fileStream = new FileOutputStream("House.ser"); 101 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 102 | House house = new House(10); 103 | house.wall = new Wall(); 104 | // Exception in thread "main" java.io.NotSerializableException: 105 | // com.rithus.serialization.Wall 106 | objectStream.writeObject(house); 107 | objectStream.close(); 108 | } 109 | } 110 | ``` 111 | ### /com/in28minutes/java/serialization/SerializationExamples3.java 112 | ``` 113 | package com.in28minutes.java.serialization; 114 | 115 | import java.io.FileInputStream; 116 | import java.io.FileOutputStream; 117 | import java.io.IOException; 118 | import java.io.ObjectInputStream; 119 | import java.io.ObjectOutputStream; 120 | import java.io.Serializable; 121 | 122 | class Actor { 123 | String name; 124 | 125 | Actor() { 126 | name = "Default"; 127 | } 128 | } 129 | 130 | class Hero extends Actor implements Serializable { 131 | String danceType; 132 | 133 | Hero() { 134 | danceType = "Default"; 135 | } 136 | } 137 | 138 | public class SerializationExamples3 { 139 | 140 | public static void main(String[] args) throws IOException, 141 | ClassNotFoundException { 142 | 143 | FileOutputStream fileStream = new FileOutputStream("Hero.ser"); 144 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 145 | 146 | Hero hero = new Hero(); 147 | hero.danceType = "Ganganam"; 148 | hero.name = "Hero1"; 149 | 150 | // Before -> DanceType :Ganganam Name:Hero1 151 | System.out.println("Before -> DanceType :" + hero.danceType + " Name:" 152 | + hero.name); 153 | // Exception in thread "main" java.io.NotSerializableException: 154 | // com.rithus.serialization.Wall 155 | objectStream.writeObject(hero); 156 | objectStream.close(); 157 | 158 | FileInputStream fileInputStream = new FileInputStream("Hero.ser"); 159 | ObjectInputStream objectInputStream = new ObjectInputStream( 160 | fileInputStream); 161 | hero = (Hero) objectInputStream.readObject(); 162 | objectInputStream.close(); 163 | 164 | // When subclass is serializable and superclass is not, the state of 165 | // subclass variables is retained. However, for the super class, 166 | // initialization 167 | // constructors and initializers are run again. 168 | // After -> DanceType :Ganganam Name:Default 169 | System.out.println("After -> DanceType :" + hero.danceType + " Name:" 170 | + hero.name); 171 | } 172 | } 173 | ``` 174 | -------------------------------------------------------------------------------- /docs/string-and-string-buffer-builder.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/string/StringBufferBuilderExamples.java 2 | ``` 3 | package com.in28minutes.java.string; 4 | 5 | public class StringBufferBuilderExamples { 6 | public static void main(String[] args) { 7 | // StringBuffer and StringBuilder are used when you want to modify 8 | // object values. 9 | StringBuffer stringbuffer = new StringBuffer("12345"); 10 | stringbuffer.append("6789"); 11 | System.out.println(stringbuffer); // 123456789 12 | // All StringBuffer methods modify the value of the object. 13 | 14 | StringBuilder sb = new StringBuilder("0123456789"); 15 | // StringBuilder delete(int startIndex, int endIndexPlusOne) 16 | System.out.println(sb.delete(3, 7));// 012789 17 | 18 | StringBuilder sb1 = new StringBuilder("abcdefgh"); 19 | // StringBuilder insert(int indext, String whatToInsert) 20 | System.out.println(sb1.insert(3, "ABCD"));// abcABCDdefgh 21 | 22 | StringBuilder sb2 = new StringBuilder("abcdefgh"); 23 | // StringBuilder reverse() 24 | System.out.println(sb2.reverse());// hgfedcba 25 | 26 | // Similar functions exist in StringBuffer also 27 | 28 | // All functions also return a reference to the object after modifying 29 | // it. 30 | // This allows a concept called method chaining. 31 | StringBuilder sb3 = new StringBuilder("abcdefgh"); 32 | System.out.println(sb3.reverse().delete(5, 6).insert(3, "---"));// hgf---edba 33 | 34 | } 35 | } 36 | ``` 37 | ### /com/in28minutes/java/string/StringExamples.java 38 | ``` 39 | package com.in28minutes.java.string; 40 | 41 | public class StringExamples { 42 | public static void main(String[] args) { 43 | // Strings are immutable 44 | String str3 = "value1"; 45 | str3.concat("value2"); 46 | System.out.println(str3); // value1 47 | 48 | // The result should be assigned to a new reference variable (or same 49 | // variable) can be reused. 50 | String concat = str3.concat("value2"); 51 | System.out.println(concat); // value1value2 52 | 53 | // String on Heap.xls 54 | // A String value once created, cannot be changed. 55 | // If a method is invoked on string object, it returns a new object and 56 | // will not modify the original object. 57 | 58 | // All strings literals are stored in "String constant pool". 59 | // If compiler finds a String literal,it checks if it exists in the 60 | // pool. 61 | // If it exists, it is reused. 62 | 63 | // 1 string object (created on the pool) and 1 reference variable 64 | String str1 = "value"; 65 | 66 | // However, if new operator is used to create string object, 67 | // the new object is created on the heap 68 | 69 | // Following piece of code create 2 objects 70 | // 1. String Literal "value" - created in the "String constant pool" 71 | // 2. String Object - created on the heap 72 | String str2 = new String("value"); 73 | 74 | // String methods 75 | String str = "abcdefghijk"; 76 | // 01234567890 77 | 78 | // char charAt(int paramInt) 79 | System.out.println(str.charAt(2)); // prints a char - c 80 | 81 | // String concat(String paramString) 82 | System.out.println(str.concat("lmn"));// abcdefghijklmn 83 | 84 | System.out.println("ABC".equalsIgnoreCase("abc"));// true 85 | System.out.println("ABCDEFGH".length());// 8 86 | 87 | // String replace(char paramChar1, char paramChar2) 88 | System.out.println("012301230123".replace('0', '4'));// 412341234123 89 | 90 | // String replace(CharSequence paramCharSequence1, CharSequence 91 | // paramCharSequence2) 92 | System.out.println("012301230123".replace("01", "45"));// 452345234523 93 | 94 | // All characters from index paramInt 95 | // String substring(int paramInt) 96 | System.out.println("abcdefghij".substring(3)); // cdefghij 97 | // 0123456789 98 | 99 | // All characters from index 3 to 6 100 | System.out.println("abcdefghij".substring(3, 7)); // defg 101 | // 0123456789 102 | 103 | System.out.println("ABCDEFGHIJ".toLowerCase()); // abcdefghij 104 | 105 | System.out.println("abcdefghij".toUpperCase()); // ABCDEFGHIJ 106 | 107 | System.out.println("abcdefghij".toString()); // abcdefghij 108 | 109 | // trim removes leading and trailings spaces 110 | System.out.println(" abcd ".trim()); // abcd 111 | } 112 | } 113 | ``` 114 | -------------------------------------------------------------------------------- /docs/variable-arguments.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/varargs/VariableArgumentExamples.java 2 | ``` 3 | package com.in28minutes.java.varargs; 4 | 5 | //Variable Arguments allow calling a method with different number of parameters. 6 | //Lets look at a basic example: 7 | public class VariableArgumentExamples { 8 | 9 | // int(type) followed ... (three dot's) is syntax of a variable argument. 10 | public int sum(int... numbers) { 11 | // inside the method a variable argument is similar to an array. 12 | // number can be treated as if it is declared as int[] numbers; 13 | int sum = 0; 14 | for (int number : numbers) { 15 | sum += number; 16 | } 17 | return sum; 18 | } 19 | 20 | public static void main(String[] args) { 21 | VariableArgumentExamples example = new VariableArgumentExamples(); 22 | // 3 Arguments 23 | System.out.println(example.sum(1, 4, 5));// 10 24 | // 4 Arguments 25 | System.out.println(example.sum(1, 4, 5, 20));// 30 26 | // 0 Arguments 27 | System.out.println(example.sum());// 0 28 | } 29 | 30 | // Variable Argument should be always the last parameter (or only parameter) 31 | // of a method. 32 | // Below example gives a compilation error 33 | /* 34 | * public int sum(int... numbers, float value) {//COMPILER ERROR } 35 | */ 36 | 37 | // Even a class can be used a variable argument. In the example below, bark 38 | // method 39 | // is overloaded with a variable argument method. 40 | class Animal { 41 | void bark() { 42 | System.out.println("Bark"); 43 | } 44 | 45 | void bark(Animal... animals) { 46 | for (Animal animal : animals) { 47 | animal.bark(); 48 | } 49 | } 50 | } 51 | 52 | } 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/variables-initialization-and-more.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/variables/PassingVariablesToMethods.java 2 | ``` 3 | package com.in28minutes.java.variables; 4 | 5 | public class PassingVariablesToMethods { 6 | public static void main(String[] args) { 7 | PassingVariablesToMethods ref = new PassingVariablesToMethods(); 8 | 9 | int n = 50; 10 | ref.incrementBy2(n); 11 | System.out.println("Passing primitive " + n);// Passing primitive 50 12 | 13 | Cricketer cric = new Cricketer(); 14 | cric.runs = 50; 15 | ref.modifyCricketer(cric); 16 | System.out.println("Passing reference variable " + cric.runs);// Passing 17 | // reference 18 | // variable 19 | // 150 20 | } 21 | 22 | void incrementBy2(int number) { 23 | number = number + 2; 24 | } 25 | 26 | void modifyCricketer(Cricketer cricketer) { 27 | cricketer.runs += 100; 28 | } 29 | } 30 | 31 | class Cricketer { 32 | String name; 33 | int runs; 34 | } 35 | ``` 36 | ### /com/in28minutes/java/variables/scope/VariablesExample.java 37 | ``` 38 | package com.in28minutes.java.variables.scope; 39 | 40 | public class VariablesExample { 41 | // RULE 1:Static Variable can be used anywhere in the class. 42 | static int staticVariable; 43 | 44 | // RULE 2:Member Variable can be used in any non-static method. 45 | int memberVariable; 46 | 47 | void method1() { 48 | // RULE 3: method1LocalVariable can be used only in method1. 49 | int method1LocalVariable; 50 | 51 | memberVariable = 5;// RULE 2 52 | staticVariable = 5;// RULE 1 53 | 54 | // Some Code 55 | { 56 | // RULE 4:blockVariable can be used only in this block. 57 | int blockVariable; 58 | // Some Code 59 | } 60 | 61 | // blockVariable = 5;//COMPILER ERROR - RULE 4 62 | } 63 | 64 | void method2() { 65 | // method1LocalVariable = 5; //COMPILER ERROR - RULE3 66 | } 67 | 68 | static void staticMethod() { 69 | staticVariable = 5;// RULE 1 70 | // memberVariable = 5; //COMPILER ERROR - RULE 2 71 | } 72 | } 73 | ``` 74 | ### /com/in28minutes/java/variables/StaticAndMemberVariables.java 75 | ``` 76 | package com.in28minutes.java.variables; 77 | 78 | public class StaticAndMemberVariables { 79 | public static void main(String[] args) { 80 | Actor actor1 = new Actor(); 81 | actor1.name = "ACTOR1"; 82 | // Actor.name //Compiler Error 83 | 84 | // Below statement can be written as actor1.count++ 85 | // But NOT recommended. 86 | Actor.count++; 87 | 88 | Actor actor2 = new Actor(); 89 | actor2.name = "ACTOR2"; 90 | 91 | // Below statement can be written as actor2.count++ 92 | // But NOT recommended. 93 | Actor.count++; 94 | 95 | System.out.println(actor1.name);// ACTOR1 96 | System.out.println(actor2.name);// ACTOR2 97 | 98 | // Next 3 statements refer to same variable 99 | System.out.println(actor1.count);// 2 100 | System.out.println(actor2.count);// 2 101 | System.out.println(Actor.count);// 2 102 | } 103 | } 104 | 105 | class Actor { 106 | // RULE 1 : Member Variables can be accessed 107 | // only through object references 108 | String name; 109 | 110 | // RULE 2:Static Variables can be accessed 111 | // through a.Class Name and b.Object Reference 112 | // It is NOT recommended to use object reference 113 | // to refer to static variables. 114 | static int count; 115 | } 116 | ``` 117 | ### /com/in28minutes/java/variables/VariableInitialization.java 118 | ``` 119 | package com.in28minutes.java.variables; 120 | 121 | //RULE1 :Member/Static variables are alway initialized with 122 | //default values.Default values for numeric types is 0, 123 | //floating point types is 0.0, boolean is false, 124 | //char is '\u0000' and object reference variable is null. 125 | 126 | //RULE2 :Local/block variables are NOT initialized by compiler. 127 | 128 | //RULE3 :If local variables are used before initialization, 129 | //it would result in Compilation Error 130 | 131 | public class VariableInitialization { 132 | public static void main(String[] args) { 133 | Player player = new Player(); 134 | 135 | // score is an int member variable - default 0 136 | System.out.println(player.score);// 0 - RULE1 137 | 138 | // name is a member reference variable - default null 139 | System.out.println(player.name);// null - RULE1 140 | 141 | int local; // not initialized 142 | // System.out.println(local);//COMPILER ERROR! RULE3 143 | 144 | String value1;// not initialized 145 | // System.out.println(value1);//COMPILER ERROR! RULE3 146 | 147 | String value2 = null;// initialized 148 | System.out.println(value2);// null - NO PROBLEM. 149 | } 150 | } 151 | 152 | class Player { 153 | String name; 154 | int score; 155 | } 156 | ``` 157 | -------------------------------------------------------------------------------- /docs/wrapper-classes.md: -------------------------------------------------------------------------------- 1 | ### /com/in28minutes/java/wrapper/WrapperExamples.java 2 | ``` 3 | package com.in28minutes.java.wrapper; 4 | 5 | public class WrapperExamples { 6 | 7 | public static void main(String[] args) { 8 | // Boolean,Byte,Character,Double,Float,Integer,Long,Short 9 | // boolean,byte,char ,double,float,int ,long,short 10 | 11 | // Wrapper classes are final 12 | 13 | Integer number = new Integer(55);// int 14 | Integer number2 = new Integer("55");// String 15 | 16 | Float number3 = new Float(55.0);// double argument 17 | Float number4 = new Float(55.0f);// float argument 18 | Float number5 = new Float("55.0f");// String 19 | 20 | Character c1 = new Character('C');// Only char constructor 21 | // Character c2 = new Character(124);//COMPILER ERROR 22 | 23 | Boolean b = new Boolean(true); 24 | 25 | // "true" "True" "tRUe" - all String Values give True 26 | // Anything else gives false 27 | Boolean b1 = new Boolean("true");// value stored - true 28 | Boolean b2 = new Boolean("True");// value stored - true 29 | Boolean b3 = new Boolean("False");// value stored - false 30 | Boolean b4 = new Boolean("SomeString");// value stored - false 31 | 32 | b = false; 33 | 34 | // Wrapper Objects are immutable (like String) 35 | 36 | // valueOfMethods 37 | // Provide another way of creating a Wrapper Object 38 | Integer seven = Integer.valueOf("111", 2);// binary 111 is converted to 39 | // 7 40 | 41 | Integer hundred = Integer.valueOf("100", 10);// 100 is stored in 42 | // variable 43 | 44 | // xxxValue methods help in creating primitives 45 | Integer integer = Integer.valueOf(57); 46 | int primitive = seven.intValue();// 57 47 | float primitiveFloat = seven.floatValue();// 57.0f 48 | 49 | Float floatWrapper = Float.valueOf(57.0f); 50 | int floatToInt = floatWrapper.intValue();// 57 51 | float floatToFloat = floatWrapper.floatValue();// 57.0f 52 | 53 | // parseXxx methods are similar to valueOf but they 54 | // return primitive values 55 | int sevenPrimitive = Integer.parseInt("111", 2);// binary 111 is 56 | // converted to 7 57 | 58 | int hundredPrimitive = Integer.parseInt("100");// 100 is stored in 59 | // variable 60 | 61 | Integer wrapperEight = new Integer(8); 62 | 63 | // Normal static toString method 64 | System.out.println(Integer.toString(wrapperEight));// String Output : 8 65 | 66 | // Overloaded static toString method : 2nd parameter : radix 67 | System.out.println(Integer.toString(wrapperEight, 2));// String Output : 68 | // 1000 69 | 70 | // static toXxxString methods. Xxx can be Hex,Binary,Octal 71 | System.out.println(Integer.toHexString(wrapperEight));// String Output 72 | // :8 73 | System.out.println(Integer.toBinaryString(wrapperEight));// String 74 | // Output 75 | // :1000 76 | System.out.println(Integer.toOctalString(wrapperEight));// String Output 77 | // :10 78 | 79 | // Auto Boxing 80 | Integer ten = new Integer(10); 81 | ten++;// allowed. Java does had work behing the screen for us 82 | 83 | // Two wrapper objects created using new are not same object 84 | Integer nineA = new Integer(9); 85 | Integer nineB = new Integer(9); 86 | System.out.println(nineA == nineB);// false 87 | System.out.println(nineA.equals(nineB));// true 88 | 89 | // Two wrapper objects created using boxing are same object 90 | Integer nineC = 9; 91 | Integer nineD = 9; 92 | System.out.println(nineC == nineD);// true 93 | System.out.println(nineC.equals(nineD));// true 94 | } 95 | } 96 | ``` 97 | -------------------------------------------------------------------------------- /images/JavaClassLoaders.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sriharivaleti/in28minutes_JavaInterviewQuestionsAndAnswers/8aad83f4b6076fe86317517720a2b64723c4414d/images/JavaClassLoaders.png -------------------------------------------------------------------------------- /images/JavaPlatFormIndependence.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sriharivaleti/in28minutes_JavaInterviewQuestionsAndAnswers/8aad83f4b6076fe86317517720a2b64723c4414d/images/JavaPlatFormIndependence.png -------------------------------------------------------------------------------- /images/jvm-jre-jdk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sriharivaleti/in28minutes_JavaInterviewQuestionsAndAnswers/8aad83f4b6076fe86317517720a2b64723c4414d/images/jvm-jre-jdk.jpg -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.in28minutes.java.interview 4 | JavaInterviewGuide 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | in28minutes 9 | 10 | 11 | 12 | org.apache.maven.plugins 13 | maven-compiler-plugin 14 | 3.2 15 | 16 | true 17 | 1.8 18 | 1.8 19 | true 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/arrays/ArrayExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayExamples { 6 | public static void main(String[] args) { 7 | // Declare an Array. All below ways are legal. 8 | int marks[]; // Not Readable 9 | int[] runs; // Not Readable 10 | int[] temperatures;// Recommended 11 | 12 | // Declaration of an Array should not include size. 13 | // int values[5];//Compilation Error! 14 | 15 | // Declaring 2D ArrayExamples 16 | int[][] matrix1; // Recommended 17 | int[] matrix2[]; // Legal but not readable. Avoid. 18 | 19 | // Creating an array 20 | marks = new int[5]; // 5 is size of array 21 | 22 | // Size of an array is mandatory to create an array 23 | // marks = new int[];//COMPILER ERROR 24 | 25 | // Once An Array is created, its size cannot be changed. 26 | 27 | // Declaring and creating an array in same line 28 | int marks2[] = new int[5]; 29 | 30 | // new Arrays are alway initialized with default values 31 | System.out.println(marks2[0]);// 0 32 | 33 | // Default Values 34 | // byte,short,int,long-0 35 | // float,double-0.0 36 | // boolean false 37 | // object-null 38 | 39 | // Assigning values to array 40 | marks[0] = 25; 41 | marks[1] = 30; 42 | marks[2] = 50; 43 | marks[3] = 10; 44 | marks[4] = 5; 45 | 46 | // ArrayOnHeap.xls 47 | 48 | // Note : Index of an array runs from 0 to length - 1 49 | 50 | // Declare, Create and Initialize Array on same line 51 | int marks3[] = { 25, 30, 50, 10, 5 }; 52 | 53 | // Leaving additional comma is not a problem 54 | int marks4[] = { 25, 30, 50, 10, 5, }; 55 | 56 | // Default Values in Array 57 | // numbers - 0 floating point - 0.0 Objects - null 58 | 59 | // Length of an array : Property length 60 | int length = marks.length; 61 | 62 | // Printing a value from array 63 | System.out.println(marks[2]); 64 | 65 | // Looping around an array - Enhanced for loop 66 | for (int mark : marks) { 67 | System.out.println(mark); 68 | } 69 | 70 | // Fill array with same default value 71 | Arrays.fill(marks, 100); // All array values will be 100 72 | 73 | // Access 10th element when array has only length 5 74 | // Runtime Exception : ArrayIndexOutOfBoundsException 75 | // System.out.println(marks[10]); 76 | 77 | // String Array: similar to int array. 78 | String[] daysOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", 79 | "Thursday", "Friday", "Saturday" }; 80 | 81 | // Array can contain only values of same type. 82 | // COMPILE ERROR!! 83 | // int marks4[] = {10,15.0}; //10 is int 15.0 is float 84 | 85 | // Cross assigment of primitive arrays is ILLEGAL 86 | int[] ints = new int[5]; 87 | short[] shorts = new short[5]; 88 | // ints = shorts;//COMPILER ERROR 89 | // ints = (int[])shorts;//COMPILER ERROR 90 | 91 | // 2D Arrays 92 | int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; 93 | 94 | int[][] matrixA = new int[5][6]; 95 | 96 | // First dimension is necessary to create a 2D Array 97 | // Best way to visualize a 2D array is as an array of arrays 98 | // ArrayOnHeap.xls 99 | matrixA = new int[3][];// FINE 100 | // matrixA = new int[][5];//COMPILER ERROR 101 | // matrixA = new int[][];//COMPILER ERROR 102 | 103 | // We can create a ragged 2D Array 104 | matrixA[0] = new int[3]; 105 | matrixA[0] = new int[4]; 106 | matrixA[0] = new int[5]; 107 | 108 | // Above matrix has 2 rows 3 columns. 109 | 110 | // Accessing an element from 2D array: 111 | System.out.println(matrix[0][0]); // 1 112 | System.out.println(matrix[1][2]); // 6 113 | 114 | // Looping a 2D array: 115 | for (int[] array : matrix) { 116 | for (int number : array) { 117 | System.out.println(number); 118 | } 119 | } 120 | 121 | // Printing a 1D Array 122 | int marks5[] = { 25, 30, 50, 10, 5 }; 123 | System.out.println(marks5); // [I@6db3f829 124 | System.out.println(Arrays.toString(marks5));// [25, 30, 50, 10, 5] 125 | 126 | // Printing a 2D Array 127 | int[][] matrix3 = { { 1, 2, 3 }, { 4, 5, 6 } }; 128 | System.out.println(matrix3); // [[I@1d5a0305 129 | System.out.println(Arrays.toString(matrix3)); 130 | // [[I@6db3f829, [I@42698403] 131 | System.out.println(Arrays.deepToString(matrix3)); 132 | // [[1, 2, 3], [4, 5, 6]] 133 | 134 | // matrix3[0] is a 1D Array 135 | System.out.println(matrix3[0]);// [I@86c347 136 | System.out.println(Arrays.toString(matrix3[0]));// [1, 2, 3] 137 | 138 | // Comparing Arrays 139 | int[] numbers1 = { 1, 2, 3 }; 140 | int[] numbers2 = { 4, 5, 6 }; 141 | System.out.println(Arrays.equals(numbers1, numbers2)); // false 142 | int[] numbers3 = { 1, 2, 3 }; 143 | System.out.println(Arrays.equals(numbers1, numbers3)); // true 144 | 145 | // Sorting An Array 146 | int rollNos[] = { 12, 5, 7, 9 }; 147 | Arrays.sort(rollNos); 148 | System.out.println(Arrays.toString(rollNos));// [5, 7, 9, 12] 149 | 150 | // Array of Objects(ArrayOnHeap.xls) 151 | Person[] persons = new Person[3]; 152 | 153 | // Creating an array of Persons creates 154 | // 4 Reference Variables to Person 155 | // It does not create the Person Objects 156 | // ArrayOnHeap.xls 157 | System.out.println(persons[0]);// null 158 | 159 | // to assign objects we would need to create them 160 | persons[0] = new Person(); 161 | persons[1] = new Person(); 162 | persons[2] = new Person(); 163 | 164 | // Other way 165 | // How may objects are created? 166 | Person[] personsAgain = { new Person(), new Person(), new Person() }; 167 | 168 | // How may objects are created? 169 | Person[][] persons2D = { { new Person(), new Person(), new Person() }, 170 | { new Person(), new Person() } }; 171 | 172 | } 173 | } 174 | 175 | class Person { 176 | long ssn; 177 | String name; 178 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/basics/Actor.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.basics; 2 | 3 | public class Actor { 4 | 5 | // name is a Member Variable 6 | private String name; 7 | 8 | public String getName() { 9 | return name; 10 | } 11 | 12 | public void setName(String name) { 13 | // This is called shadowing 14 | // Local variable or parameter with 15 | // same name as a member variable 16 | // this.name refers to member variable 17 | // name refers to local variable 18 | this.name = name; 19 | } 20 | 21 | public static void main(String[] args) { 22 | // bradPitt & tomCruise are objects or instances 23 | // of Class Actor 24 | // Each instance has separate value for the 25 | // member variable name 26 | Actor bradPitt = new Actor(); 27 | bradPitt.setName("Brad Pitt"); 28 | 29 | Actor tomCruise = new Actor(); 30 | tomCruise.setName("Tom Cruise"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/basics/CricketScorer.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.basics; 2 | 3 | public class CricketScorer { 4 | // Instance Variables - constitute the state of an object 5 | private int score; 6 | 7 | // Behavior - all the methods that are part of the class 8 | // An object of this type has behavior based on the 9 | // methods four, six and getScore 10 | public void four() { 11 | score = score + 4; 12 | } 13 | 14 | public void six() { 15 | score = score + 6; 16 | } 17 | 18 | public int getScore() { 19 | return score; 20 | } 21 | 22 | public static void main(String[] args) { 23 | CricketScorer scorer = new CricketScorer(); 24 | scorer.six(); 25 | // State of scorer is (score => 6) 26 | scorer.four(); 27 | // State of scorer is (score => 10) 28 | System.out.println(scorer.getScore()); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/basics/Cricketer.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.basics; 2 | 3 | public class Cricketer { 4 | String name; 5 | int odiRuns; 6 | int testRuns; 7 | int t20Runs; 8 | 9 | public int totalRuns() { 10 | int totalRuns = odiRuns + testRuns + t20Runs; 11 | return totalRuns; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/classmodifiers/defaultaccess/a/AnotherClassInSamePackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.classmodifiers.defaultaccess.a; 2 | 3 | public class AnotherClassInSamePackage { 4 | // DefaultAccessClass and AnotherClassInSamePackage 5 | // are in same package. 6 | // So, DefaultAccessClass is visible. 7 | // An instance of the class can be created. 8 | 9 | DefaultAccessClass defaultAccess; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/classmodifiers/defaultaccess/a/DefaultAccessClass.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.classmodifiers.defaultaccess.a; 2 | 3 | /* No public before class. So this class has default access*/ 4 | class DefaultAccessClass { 5 | // Default access is also called package access 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/classmodifiers/defaultaccess/b/ClassInDifferentPackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.classmodifiers.defaultaccess.b; 2 | 3 | public class ClassInDifferentPackage { 4 | // Class DefaultAccessClass and Class ClassInDifferentPackage 5 | // are in different packages (*.a and *.b) 6 | // So, DefaultAccessClass is not visible to ClassInDifferentPackage 7 | 8 | // Below line of code will cause compilation error if uncommented 9 | // DefaultAccessClass defaultAccess; //COMPILE ERROR!! 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/classmodifiers/nonaccess/abstractclass/AbstractClassExample.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.classmodifiers.nonaccess.abstractclass; 2 | 3 | public abstract class AbstractClassExample { 4 | 5 | // Abstract class can contain instance and static variables 6 | public int publicVariable; 7 | private int privateVariable; 8 | static int staticVariable; 9 | 10 | // Abstract Class can contain 0 or more abstract methods 11 | // Abstract method does not have a body 12 | abstract void abstractMethod1(); 13 | 14 | abstract void abstractMethod2(); 15 | 16 | // Abstract Class can contain 0 or more non-abstract methods 17 | public void nonAbstractMethod() { 18 | System.out.println("Non Abstract Method"); 19 | } 20 | 21 | public static void main(String[] args) { 22 | // An abstract class cannot be instantiated 23 | // Below line gives compilation error if uncommented 24 | // AbstractClassExample ex = new AbstractClassExample(); 25 | } 26 | } 27 | 28 | // A non-abstract sub class of an abstract class should 29 | // implement all the abstract methods 30 | // Below class gives compilation error if uncommented 31 | /* 32 | * class SubClass extends AbstractClassExample { 33 | * 34 | * } 35 | */ 36 | 37 | // This class implements both abstractMethod1 and abstractMethod2 38 | class SubClass2 extends AbstractClassExample { 39 | void abstractMethod1() { 40 | System.out.println("Abstract Method1"); 41 | } 42 | 43 | void abstractMethod2() { 44 | System.out.println("Abstract Method2"); 45 | } 46 | } 47 | 48 | // We can create a subclass of an abstract class which is abstract 49 | // It doesn't need to implement all the abstract methods 50 | abstract class AbstractSubClass extends AbstractClassExample { 51 | void abstractMethod1() { 52 | System.out.println("Abstract Method1"); 53 | } 54 | // abstractMethod2 is not defined at all. 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/classmodifiers/nonaccess/finalclass/FinalClass.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.classmodifiers.nonaccess.finalclass; 2 | 3 | final public class FinalClass { 4 | } 5 | 6 | // Below class will not compile if uncommented 7 | // FinalClass cannot be extended 8 | /* 9 | * class ExtendingFinalClass extends FinalClass{ 10 | * 11 | * } 12 | */ -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/collections/FailFast.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.collections; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | 7 | public class FailFast { 8 | 9 | public static void main(String[] args) { 10 | Map map = new HashMap(); 11 | map.put("key1", "value1"); 12 | map.put("key2", "value2"); 13 | map.put("key3", "value3"); 14 | 15 | Iterator iterator = map.keySet().iterator(); 16 | 17 | while (iterator.hasNext()) { 18 | System.out.println(map.get(iterator.next())); 19 | map.put("key4", "value4"); 20 | } 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/collections/FailSafe.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.collections; 2 | 3 | import java.util.Iterator; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public class FailSafe { 7 | 8 | public static void main(String[] args) { 9 | ConcurrentHashMap map = new ConcurrentHashMap(); 10 | map.put("key1", "value1"); 11 | map.put("key2", "value2"); 12 | map.put("key3", "value3"); 13 | 14 | Iterator iterator = map.keySet().iterator(); 15 | 16 | while (iterator.hasNext()) { 17 | System.out.println(map.get(iterator.next())); 18 | map.put("key4", "value4"); 19 | } 20 | 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/collections/examples/ConcurrentCollectionsExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.collections.examples; 2 | 3 | public class ConcurrentCollectionsExamples { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/enums/Enum.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.enums; 2 | 3 | //Enum can be declared outside a class 4 | enum SeasonOutsideClass { 5 | WINTER, SPRING, SUMMER, FALL 6 | }; 7 | 8 | public class Enum { 9 | // Enum can be declared inside a class 10 | enum Season { 11 | WINTER, SPRING, SUMMER, FALL 12 | }; 13 | 14 | public static void main(String[] args) { 15 | /* 16 | * //Uncommenting gives compilation error //enum cannot be created in a 17 | * method enum InsideMethodNotAllowed { WINTER, SPRING, SUMMER, FALL }; 18 | */ 19 | 20 | // Converting String to Enum 21 | Season season = Season.valueOf("FALL"); 22 | 23 | // Converting Enum to String 24 | System.out.println(season.name());// FALL 25 | 26 | // Default ordinals of enum 27 | // By default java assigns ordinals in order 28 | System.out.println(Season.WINTER.ordinal());// 0 29 | System.out.println(Season.SPRING.ordinal());// 1 30 | System.out.println(Season.SUMMER.ordinal());// 2 31 | System.out.println(Season.FALL.ordinal());// 3 32 | 33 | // Looping an enum => We use method values 34 | for (Season season1 : Season.values()) { 35 | System.out.println(season1.name()); 36 | // WINTER SPRING SUMMER FALL (separate lines) 37 | } 38 | 39 | // Comparing two Enums 40 | Season season1 = Season.FALL; 41 | Season season2 = Season.FALL; 42 | System.out.println(season1 == season2);// true 43 | System.out.println(season1.equals(season2));// true 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/enums/EnumAdvanced.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.enums; 2 | 3 | public class EnumAdvanced { 4 | 5 | // Enum with a variable,method and constructor 6 | enum SeasonCustomized { 7 | WINTER(1), SPRING(2), SUMMER(3), FALL(4); 8 | 9 | // variable 10 | private int code; 11 | 12 | // method 13 | public int getCode() { 14 | return code; 15 | } 16 | 17 | // Constructor-only private or (default) 18 | // modifiers are allowed 19 | SeasonCustomized(int code) { 20 | this.code = code; 21 | } 22 | 23 | // Getting value of enum from code 24 | public static SeasonCustomized valueOf(int code) { 25 | for (SeasonCustomized season : SeasonCustomized.values()) { 26 | if (season.getCode() == code) 27 | return season; 28 | } 29 | throw new RuntimeException("value not found");// Just for kicks 30 | } 31 | 32 | // Using switch statement on an enum 33 | public int getExpectedMaxTemperature() { 34 | switch (this) { 35 | case WINTER: 36 | return 5; 37 | case SPRING: 38 | case FALL: 39 | return 10; 40 | case SUMMER: 41 | return 20; 42 | } 43 | return -1;// Dummy since Java does not recognize this is possible :) 44 | } 45 | 46 | }; 47 | 48 | public static void main(String[] args) { 49 | SeasonCustomized season = SeasonCustomized.WINTER; 50 | 51 | /* 52 | * //Enum constructor cannot be invoked directly //Below line would 53 | * cause COMPILER ERROR SeasonCustomized season2 = new 54 | * SeasonCustomized(1); 55 | */ 56 | 57 | System.out.println(season.getCode());// 1 58 | 59 | System.out.println(season.getExpectedMaxTemperature());// 5 60 | 61 | System.out.println(SeasonCustomized.valueOf(4));// FALL 62 | 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/enums/EnumAdvanced2.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.enums; 2 | 3 | public class EnumAdvanced2 { 4 | 5 | // Enum with a variable,method and constructor 6 | enum SeasonCustomized { 7 | WINTER(1) { 8 | public int getExpectedMaxTemperature() { 9 | return 5; 10 | } 11 | }, 12 | SPRING(2), SUMMER(3) { 13 | public int getExpectedMaxTemperature() { 14 | return 20; 15 | } 16 | }, 17 | FALL(4); 18 | 19 | // variable 20 | private int code; 21 | 22 | // method 23 | public int getCode() { 24 | return code; 25 | } 26 | 27 | // Constructor-only private or (default) 28 | // modifiers are allowed 29 | SeasonCustomized(int code) { 30 | this.code = code; 31 | } 32 | 33 | public int getExpectedMaxTemperature() { 34 | return 10; 35 | } 36 | 37 | }; 38 | 39 | public static void main(String[] args) { 40 | SeasonCustomized season = SeasonCustomized.WINTER; 41 | 42 | System.out.println(season.getExpectedMaxTemperature());// 5 43 | 44 | System.out.println(SeasonCustomized.FALL.getExpectedMaxTemperature());// 10 45 | 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/exceptionhandling/ExceptionHandlingExample1.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.exceptionhandling; 2 | 3 | //Java Interview Questions Exception Handling 4 | //������������������������������������������� 5 | //What is difference between Error and Exception - done? 6 | //What is the Exception Handling Hierarchy - done? 7 | //Difference between runtime exception and checked exception? 8 | //When should we use Checked Exceptions? 9 | //What does Exception propagation mean? 10 | //Why should type 'Exception' not be catched? 11 | //What are the best practices of Exception Handling? 12 | //How do you create a custom exception - checked and unchecked? 13 | //Is try without catch and finally allowed? 14 | //When is finally block NOT executed? 15 | //Let's say there is a return in the try block. Will finally block be executed? 16 | //Exception Handling - Best Practices 17 | 18 | //Runtime Exceptions => Unchecked exceptions 19 | //Checked Exceptions 20 | 21 | class CheckedException extends Exception { 22 | 23 | } 24 | 25 | class RuntimeExceptionExample extends RuntimeException { 26 | 27 | } 28 | 29 | class Test { 30 | void readAFileAndParse() throws RuntimeExceptionExample { 31 | // Reading a file => FileNotFound 32 | // Parses the file => FileIsNotInCorrectFormat 33 | } 34 | } 35 | 36 | class Reuse { 37 | void doSomething() { 38 | Test test = new Test(); 39 | test.readAFileAndParse(); 40 | } 41 | 42 | public void firstMethod() throws RuntimeException { 43 | 44 | } 45 | 46 | public void secondMethod() { 47 | firstMethod(); 48 | } 49 | } 50 | 51 | // Below class definitions show creation of a programmer defined exception in 52 | // Java. 53 | // Programmer defined classes 54 | class CheckedException1 extends Exception { 55 | } 56 | 57 | class CheckedException2 extends CheckedException1 { 58 | } 59 | 60 | class UnCheckedException extends RuntimeException { 61 | } 62 | 63 | class UnCheckedException2 extends UnCheckedException { 64 | } 65 | 66 | class Connection { 67 | void open() { 68 | System.out.println("Connection Opened"); 69 | } 70 | 71 | void close() { 72 | System.out.println("Connection Closed"); 73 | } 74 | } 75 | 76 | public class ExceptionHandlingExample1 { 77 | 78 | public static void methodThrowCheckedException() throws RuntimeException { 79 | throw new RuntimeException(); 80 | } 81 | 82 | public static void methodSomething() { 83 | ExceptionHandlingExample1.methodThrowCheckedException(); 84 | } 85 | 86 | // Exception Handling Example 1 87 | // Let's add a try catch block in method2 88 | public static void main(String[] args) { 89 | method1(); 90 | System.out.println("Line after Exception - Main"); 91 | } 92 | 93 | private static void method1() { 94 | method2(); 95 | System.out.println("Line after Exception - Method 1"); 96 | } 97 | 98 | private static void method2() { 99 | Connection connection = new Connection(); 100 | connection.open(); 101 | try { 102 | return; 103 | } catch (Exception e) { 104 | 105 | } finally { 106 | // 1 107 | // 2 108 | // 3 109 | } 110 | } 111 | } 112 | 113 | // Connection Opened 114 | // Connection Closed 115 | // Exception in thread "main" java.lang.NullPointerException 116 | // at 117 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.method2(ExceptionHandlingExample1.java:33) 118 | // at 119 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.method1(ExceptionHandlingExample1.java:22) 120 | // at 121 | // com.rithus.exceptionhandling.ExceptionHandlingExample1.main(ExceptionHandlingExample1.java:17) 122 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/exceptionhandling/ExceptionHandlingExample2.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.exceptionhandling; 2 | 3 | //PLEASE GIVE ME A BREAK ON CODING STANDARDS 4 | class Amount { 5 | public Amount(String currency, int amount) { 6 | this.currency = currency; 7 | this.amount = amount; 8 | } 9 | 10 | String currency; 11 | int amount;// Should ideally use BigDecimal 12 | } 13 | 14 | class CurrenciesDoNotMatchException extends RuntimeException { 15 | } 16 | 17 | class AmountAdder { 18 | static Amount addAmounts(Amount amount1, Amount amount2) { 19 | if (!amount1.currency.equals(amount2.currency)) { 20 | throw new CurrenciesDoNotMatchException(); 21 | } 22 | return new Amount(amount1.currency, amount1.amount + amount2.amount); 23 | } 24 | } 25 | 26 | public class ExceptionHandlingExample2 { 27 | public static void main(String[] args) { 28 | try { 29 | AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE", 30 | 5)); 31 | String string = null; 32 | string.toString(); 33 | } catch (CurrenciesDoNotMatchException e) { 34 | System.out.println("Handled CurrenciesDoNotMatchException"); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/files/ConsoleExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.files; 2 | 3 | import java.io.Console; 4 | import java.io.IOException; 5 | 6 | public class ConsoleExamples { 7 | public static void main(String[] args) throws IOException { 8 | 9 | // Console is used to read input from keyboard and write output 10 | // This can be easily run from command prompt 11 | 12 | // Console console = new Console(); //COMPILER ERROR 13 | Console console = System.console(); 14 | console.printf("Enter a Line of Text"); 15 | 16 | String text = console.readLine(); 17 | console.printf("Enter a Password"); 18 | 19 | // Doesn't show what is being entered 20 | char[] password = console.readPassword(); 21 | 22 | console.format("\nEntered Text is %s", text); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/files/FileExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.files; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.File; 6 | import java.io.FileReader; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.io.PrintWriter; 10 | import java.util.Arrays; 11 | 12 | public class FileExamples { 13 | public static void main(String[] args) throws IOException { 14 | // File helps us to create, delete, get details about a file. 15 | File file = new File("FileName.txt"); 16 | 17 | // Check if the file exists 18 | System.out.println(file.exists()); 19 | 20 | // If file does not exist creates it and returns true 21 | // If file exists, returns false 22 | System.out.println(file.createNewFile()); 23 | 24 | // Gets the full path of file 25 | System.out.println(file.getAbsolutePath()); 26 | System.out.println(file.isFile());// true 27 | System.out.println(file.isDirectory());// false 28 | 29 | // Renaming a file 30 | File fileWithNewName = new File("NewFileName.txt"); 31 | file.renameTo(fileWithNewName); 32 | // There is no method file.renameTo("NewFileName.txt"); 33 | 34 | // A File class in Java represents a file and directory. 35 | File directory = new File("src/com/rithus"); 36 | 37 | // prints full directory path 38 | System.out.println(directory.getAbsolutePath()); 39 | System.out.println(directory.isDirectory());// true 40 | 41 | File fileInDir = new File(directory, "NewFileInDirectory.txt"); 42 | // This does not create the actual file. 43 | 44 | // Actual file is created when we invoke createNewFile method 45 | System.out.println(fileInDir.createNewFile()); // true - First Time 46 | 47 | // Prints the files and directories present in the folder 48 | System.out.println(Arrays.toString(directory.list())); 49 | 50 | // Creating a directory 51 | File newDirectory = new File("newfolder"); 52 | System.out.println(newDirectory.mkdir());// true - First Time 53 | 54 | // Creating a file in a new directory 55 | File notExistingDirectory = new File("notexisting"); 56 | File newFile = new File(notExistingDirectory, "newFile"); 57 | 58 | // Will throw Exception if uncommented: No such file or directory 59 | // newFile.createNewFile(); 60 | 61 | System.out.println(newDirectory.mkdir());// true - First Time 62 | 63 | // Implementations of Writer and Reader abstract classes help us 64 | // to write and read (content of) files. 65 | 66 | // Writer methods - flush, close, append (text) 67 | // Reader methods - read, close (NO FLUSH) 68 | 69 | // Writer implementations - FileWriter,BufferedWriter,PrintWriter 70 | // Reader implementations - FileReader,BufferedReader 71 | 72 | // Write a string to a file using FileWriter 73 | // FileWriter helps to write stuff into the file 74 | FileWriter fileWriter = new FileWriter(file); 75 | fileWriter.write("How are you doing?"); 76 | // Always flush before close. Writing to file uses Buffering. 77 | fileWriter.flush(); 78 | fileWriter.close(); 79 | 80 | FileReader fileReader = new FileReader(file); 81 | char[] temp = new char[25]; 82 | 83 | // Read from file using FileReader 84 | // fileReader reads entire file and stores it into temp 85 | System.out.println(fileReader.read(temp));// 18 - No of characters Read 86 | // from file 87 | 88 | System.out.println(Arrays.toString(temp));// output below 89 | // [H, o, w, , a, r, e, , y, o, u, , d, o, i, n, g, ?, , , , , , , 90 | // ] 91 | 92 | fileReader.close();// Always close anything you opened :) 93 | 94 | // FileWriter Constructors 95 | // can accept file(File) or the path to file (String) as argument 96 | // When a writer object is created, it creates the file, 97 | // if it does not exist 98 | 99 | FileWriter fileWriter2 = new FileWriter("FileName.txt"); 100 | fileWriter2.write("How are you doing Buddy?"); 101 | // Always flush before close. Writing to file uses Buffering. 102 | fileWriter2.flush(); 103 | fileWriter2.close(); 104 | 105 | // FileReader Constructors 106 | // can accept file(File) or the path to file (String) as argument 107 | FileReader fileReader2 = new FileReader("FileName.txt"); 108 | System.out.println(fileReader2.read(temp));// 24 109 | System.out.println(Arrays.toString(temp));// output below 110 | 111 | // BufferedWriter Constructors only accept another Writer as argument 112 | FileWriter fileWriter3 = new FileWriter("BufferedFileName.txt"); 113 | BufferedWriter bufferedWriter = new BufferedWriter(fileWriter3); 114 | 115 | bufferedWriter.write("How are you doing Buddy?"); 116 | bufferedWriter.newLine(); 117 | bufferedWriter.write("I'm Doing Fine"); 118 | // Always flush before close. Writing to file uses Buffering. 119 | bufferedWriter.flush(); 120 | bufferedWriter.close(); 121 | fileWriter3.close(); 122 | 123 | // BufferedReader helps to read the file line by line 124 | // BufferedReader Constructors only accept another Reader as argument 125 | FileReader fileReader3 = new FileReader("BufferedFileName.txt"); 126 | BufferedReader bufferedReader = new BufferedReader(fileReader3); 127 | 128 | String line; 129 | // readLine returns null when reading the file is completed. 130 | while ((line = bufferedReader.readLine()) != null) { 131 | System.out.println(line); 132 | } 133 | 134 | // PrintWriter helps writing to file in a formatted way. 135 | // PrintWriter constructor supports varied kinds of arguments 136 | // File 137 | // String 138 | // Writer 139 | PrintWriter printWriter = new PrintWriter("PrintWriterFileName.txt"); 140 | // Other than write function you can use format, printf, print, println 141 | // functions to write to PrintWriter file. 142 | 143 | // writes " My Name" to the file 144 | printWriter.format("%15s", "My Name"); 145 | 146 | printWriter.println(); // New Line 147 | printWriter.println("Some Text"); 148 | 149 | // writes "Formatted Number : 4.50000" to the file 150 | printWriter.printf("Formatted Number : %5.5f", 4.5); 151 | printWriter.flush();// Always flush a writer 152 | printWriter.close(); 153 | 154 | FileReader fileReader4 = new FileReader("PrintWriterFileName.txt"); 155 | BufferedReader bufferedReader2 = new BufferedReader(fileReader4); 156 | 157 | String line2; 158 | // readLine returns null when reading the file is completed. 159 | while ((line2 = bufferedReader2.readLine()) != null) { 160 | System.out.println(line2); 161 | } 162 | 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/BreakExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class BreakExamples { 4 | public static void main(String[] args) { 5 | // Break statement breaks out of the loop 6 | for (int i = 0; i < 10; i++) { 7 | System.out.print(i); 8 | if (i == 5) { 9 | break; 10 | } 11 | } 12 | // Output is 012345 13 | 14 | // Break can be used in a while also 15 | int i = 0; 16 | while (i < 10) { 17 | System.out.print(i); 18 | if (i == 5) { 19 | break; 20 | } 21 | i++; 22 | } 23 | // Output is 012345 24 | 25 | System.out.println(); 26 | 27 | // Break statement takes execution out of inner most loop 28 | for (int j = 0; j < 2; j++) { 29 | for (int k = 0; k < 10; k++) { 30 | System.out.print(j + "" + k); 31 | if (k == 5) { 32 | break;// Takes out of loop using k 33 | } 34 | } 35 | } 36 | // Output is 000102030405101112131415 37 | 38 | System.out.println(); 39 | 40 | // To get out of an outer for loop, label's need to be used 41 | outer: for (int j = 0; j < 2; j++) { 42 | for (int k = 0; k < 10; k++) { 43 | System.out.print(j + "" + k); 44 | if (k == 5) { 45 | break outer;// Takes out of loop using j 46 | } 47 | } 48 | } 49 | // Output is 000102030405 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/ContinueExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class ContinueExamples { 4 | public static void main(String[] args) { 5 | // Continue statement skips rest of the statements in the loop 6 | // and starts next iteration 7 | for (int i = 0; i < 10; i++) { 8 | if (i == 5) { 9 | continue; 10 | } 11 | System.out.print(i); 12 | } 13 | // Output is 012346789 14 | // Not that the output does not contain 5 15 | 16 | System.out.println(); 17 | 18 | // Continue can be used in a while also 19 | int i = 0; 20 | while (i < 10) { 21 | i++; 22 | if (i == 5) { 23 | continue; 24 | } 25 | System.out.print(i); 26 | } 27 | // Output is 1234678910 28 | // Not that the output does not contain 5 29 | 30 | System.out.println(); 31 | 32 | // Continue statement takes execution to next iteration of inner most 33 | // loop 34 | for (int j = 0; j < 2; j++) { 35 | for (int k = 0; k < 10; k++) { 36 | if (k == 5) { 37 | continue;// skips to next iteration of k loop 38 | } 39 | System.out.print(j + "" + k); 40 | } 41 | } 42 | // Output is 000102030406070809101112131416171819 43 | // Not that the output does not contain 05,15 44 | 45 | System.out.println(); 46 | 47 | // To get out of an outer for loop, label's need to be used 48 | outer: for (int j = 0; j < 2; j++) { 49 | for (int k = 0; k < 10; k++) { 50 | if (k == 5) { 51 | continue outer;// skips to next iteration of j loop 52 | } 53 | System.out.print(j + "" + k); 54 | } 55 | } 56 | // Output is 00010203041011121314 57 | // Not that the output does not contain anything after 05 and also 15 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/DoWhileLoopExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class DoWhileLoopExamples { 4 | public static void main(String[] args) { 5 | int count = 0; 6 | // do while also is used when it is not clear how many times loop has to 7 | // be executed. 8 | do { 9 | System.out.print(count); 10 | count++; 11 | } while (count < 5);// while this condn is true, loop is executed. 12 | // output is 01234 13 | 14 | // Code in do while is executed atleast once. 15 | count = 5; 16 | do { 17 | System.out.print(count); 18 | count++; 19 | } while (count < 5); 20 | // output is 5 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/ForLoopExample.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class ForLoopExample { 4 | public static void main(String[] args) { 5 | // Example of a For Loop 6 | for (int i = 0; i < 10; i++) { 7 | System.out.print(i); 8 | } 9 | // Output is 0123456789 10 | 11 | // For loop statement has 3 parts 12 | // Initialization => int i=0 13 | // Condition => i<10 14 | // Operation (Increment or Decrement usually) => i++ 15 | 16 | // There can be multiple statements in Initialization 17 | // or Operation seperated by commas 18 | for (int i = 0, j = 0; i < 10; i++, j--) { 19 | System.out.print(j); 20 | } 21 | // Output is 0-1-2-3-4-5-6-7-8-9 22 | 23 | // Enhanced For Loop 24 | int[] numbers = { 1, 2, 3, 4, 5 }; 25 | 26 | for (int number : numbers) { 27 | System.out.print(number); 28 | } 29 | // Output is 12345 30 | 31 | // Any of 3 parts in a for can be empty 32 | for (;;) { 33 | System.out.print("I will be looping for ever.."); 34 | } 35 | // Result : Infinite loop 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/IfElseExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class IfElseExamples { 4 | public static void main(String[] args) { 5 | 6 | // Code inside If is executed only if the condition is true 7 | if (true) { 8 | System.out.println("Will be printed"); 9 | } 10 | 11 | // Statement inside this condition is not executed 12 | if (false) { 13 | System.out.println("Will NOT be printed");// Not executed 14 | } 15 | 16 | // Lets look at an example 17 | int x = 5; 18 | 19 | if (x == 5) { 20 | System.out.println("x is 5");// executed since x==5 is true 21 | } 22 | 23 | x = 6; 24 | if (x == 5) { 25 | System.out.println("x is 5");// Not executed since x==5 is false 26 | } 27 | 28 | // If Else 29 | // If condition is true code in if is executed, else code in else is 30 | // executed 31 | 32 | int y = 10; 33 | 34 | if (y == 10) { 35 | System.out.println("Y is 10");// executed-condn y==10 is true 36 | } else { 37 | System.out.println("Y is Not 10"); 38 | } 39 | 40 | y = 11; 41 | 42 | if (y == 10) { 43 | System.out.println("Y is 10");// NOT executed 44 | } else { 45 | System.out.println("Y is Not 10");// executed-condn y==10 is false 46 | } 47 | 48 | // Nested else if 49 | // The code in the first if condition that is true is executed. 50 | // If none of the if conditions are true, then code in else is executed. 51 | int z = 15; 52 | if (z == 10) { 53 | System.out.println("Z is 10");// NOT executed 54 | } else if (z == 12) { 55 | System.out.println("Z is 12");// NOT executed 56 | } else if (z == 15) { 57 | System.out.println("Z is 15");// executed. Rest of the if else are 58 | // skipped. 59 | } else { 60 | System.out.println("Z is Something Else.");// NOT executed 61 | } 62 | 63 | z = 18; 64 | if (z == 10) { 65 | System.out.println("Z is 10");// NOT executed 66 | } else if (z == 12) { 67 | System.out.println("Z is 12");// NOT executed 68 | } else if (z == 15) { 69 | System.out.println("Z is 15");// NOT executed 70 | } else { 71 | System.out.println("Z is Something Else.");// executed 72 | } 73 | 74 | // Be very careful with formatting 75 | int number = 5; 76 | if (number < 0) // condn is false. So the line in if is not executed. 77 | number = number + 10; // Not executed 78 | number++; // This statement is not part of if 79 | System.out.println(number);// prints 6 80 | 81 | // Guess the output 82 | int k = 15; 83 | if (k > 20) { 84 | System.out.println(1); 85 | } else if (k > 10) { 86 | System.out.println(2); 87 | } else if (k < 20) { 88 | System.out.println(3); 89 | } else { 90 | System.out.println(4); 91 | } 92 | // Output is 2. Once a condition in nested-if-else is true the rest of 93 | // the code is not executed. 94 | 95 | // Guess the output 96 | int l = 15; 97 | 98 | if (l < 20) 99 | System.out.println("l<20"); 100 | if (l > 20) 101 | System.out.println("l>20"); 102 | else 103 | System.out.println("Who am I?"); 104 | // Output is "l<20" followed by "Who am I?" on next line. 105 | // else belong to the last if before it unless brackets ({}) are used. 106 | 107 | // Guess the output 108 | int m = 15; 109 | 110 | if (m > 20) 111 | if (m < 20) 112 | System.out.println("m>20"); 113 | else 114 | System.out.println("Who am I?"); 115 | // Nothing is printed to output. Above code is similar to code below 116 | if (m > 20) {// Condn is false. So, code in if is not executed 117 | if (m < 20) 118 | System.out.println("m>20"); 119 | else 120 | System.out.println("Who am I?"); 121 | } 122 | 123 | int x1 = 0; 124 | // Condition in if should always be boolean 125 | // if(x1) {} //COMPILER ERROR 126 | // if(x1=0) {}//COMPILER ERROR. Using = instead of == 127 | 128 | boolean isTrue = false; 129 | if (isTrue == true) { 130 | System.out.println("TRUE TRUE");// Will not be printed 131 | } 132 | if (isTrue = true) { 133 | System.out.println("TRUE");// Will be printed. 134 | } 135 | // Condition is isTrue=true. This is assignment. Returns true. So, code 136 | // in if is executed. 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/SwitchExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class SwitchExamples { 4 | public static void main(String[] args) { 5 | int number = 2; 6 | // Output of below switch is 2. 7 | // The case which is matched is executed. 8 | switch (number) { 9 | case 1: 10 | System.out.println(1); 11 | break; 12 | case 2: 13 | System.out.println(2); 14 | break; 15 | case 3: 16 | System.out.println(3); 17 | break; 18 | default: 19 | System.out.println("Default"); 20 | break; 21 | } 22 | 23 | // Notice that there is not break after each case. 24 | // If there is no break, then all the case's until we find break are 25 | // executed. 26 | number = 2; 27 | switch (number) { 28 | case 1: 29 | System.out.println(1); 30 | case 2: 31 | System.out.println(2); 32 | case 3: 33 | System.out.println(3); 34 | default: 35 | System.out.println("Default"); 36 | } 37 | // Output of above switch is 2 3 Default on separate lines. 38 | 39 | // Notice that there is not break after case 2. So, it fall through 40 | // to case 3. Prints the statement. After that, the break statement 41 | // takes the execution out of the switch. 42 | number = 2; 43 | switch (number) { 44 | case 1: 45 | System.out.println(1); 46 | break; 47 | case 2: 48 | case 3: 49 | System.out.println("Number is 2 or 3"); 50 | break; 51 | default: 52 | System.out.println("Default"); 53 | break; 54 | } 55 | // Output of above switch is Number is 2 or 3. 56 | 57 | // default is executed if none of the case's match 58 | number = 10; 59 | switch (number) { 60 | case 1: 61 | System.out.println(1); 62 | break; 63 | case 2: 64 | System.out.println(2); 65 | break; 66 | case 3: 67 | System.out.println(3); 68 | break; 69 | default: 70 | System.out.println("Default"); 71 | break; 72 | } 73 | // Output of above is Default 74 | 75 | // default doesn't need to be the last case in an switch. 76 | number = 10; 77 | switch (number) { 78 | default: 79 | System.out.println("Default"); 80 | break; 81 | case 1: 82 | System.out.println(1); 83 | break; 84 | case 2: 85 | System.out.println(2); 86 | break; 87 | case 3: 88 | System.out.println(3); 89 | break; 90 | } 91 | // Output of above is Default 92 | // No change in Result 93 | 94 | // Switch can be used only with char, byte, short, int or enum 95 | long l = 15; 96 | /* 97 | * switch(l){//COMPILER ERROR. Not allowed. } 98 | */ 99 | 100 | // Case value should be a compile time constant. 101 | number = 10; 102 | switch (number) { 103 | // case number>5://COMPILER ERROR. Cannot have a condition 104 | // case number://COMPILER ERROR. Should be constant. 105 | } 106 | 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/flow/WhileLoopExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.flow; 2 | 3 | public class WhileLoopExamples { 4 | public static void main(String[] args) { 5 | int count = 0; 6 | // While is used when it is not clear how many times loop has to be 7 | // executed. 8 | while (count < 5) {// while this condn is true, loop is executed. 9 | System.out.print(count); 10 | count++; 11 | }// output is 01234 12 | 13 | // Depending on the condition, code in while might not be executed at 14 | // all. 15 | count = 5; 16 | while (count < 5) {// condn is false. So, code in while is not executed. 17 | System.out.print(count); 18 | count++; 19 | }// Nothing is printed to output 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/generics/GenericsExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.generics; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class GenericsExamples { 6 | 7 | static ArrayList multiplyNumbersBy2(ArrayList numbers) { 8 | ArrayList result = new ArrayList(); 9 | 10 | for (int i = 0; i < numbers.size(); i++) { 11 | // TYPE CAST is required 12 | int value = (Integer) numbers.get(i); 13 | result.add(value * 2); 14 | } 15 | 16 | return result; 17 | } 18 | 19 | static void addElement(ArrayList something) { 20 | something.add(new String("String")); 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | // Older code - Before Java 5 26 | ArrayList numbers = new ArrayList(); 27 | numbers.add(5); 28 | numbers.add(6); 29 | 30 | // javac gives warning because multiplyNumbersBy2(ArrayList) is invoked 31 | // with a Specific ArrayList 32 | // and in the method multiplyNumbersBy2 an element is added to ArrayList 33 | // com/rithus/generics/GenericsExamples.java uses unchecked or unsafe 34 | // operations. 35 | // Recompile with -Xlint:unchecked for details. 36 | 37 | System.out.println(multiplyNumbersBy2(numbers));// [10, 12] 38 | 39 | // javac gives warning because addElement(ArrayList) is invoked with a 40 | // Specific ArrayList 41 | // and in the method addElement, an element is added to the list. 42 | // com/rithus/generics/GenericsExamples.java uses unchecked or unsafe 43 | // operations. 44 | addElement(numbers); 45 | 46 | // Throws runtime exception - java.lang.ClassCastException 47 | System.out.println(multiplyNumbersBy2(numbers)); 48 | 49 | // New code - After 50 | 51 | } 52 | 53 | // javac -Xlint:unchecked com/rithus/generics/GenericsExamples.java 54 | // com/rithus/generics/GenericsExamples.java:14: warning: [unchecked] 55 | // unchecked call to add(E) as a member of the raw type java.util.ArrayList 56 | // result.add(value * 2); 57 | // ^ 58 | // com/rithus/generics/GenericsExamples.java:21: warning: [unchecked] 59 | // unchecked call to add(E) as a member of the raw type java.util.ArrayList 60 | // something.add(new String("String")); 61 | // ^ 62 | // 2 warnings 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/generics/GenericsExamples2.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.generics; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | class Animal { 9 | } 10 | 11 | class Dog extends Animal { 12 | } 13 | 14 | public class GenericsExamples2 { 15 | 16 | static void doSomethingArray(Animal[] animals) { 17 | // do Something with Animals 18 | } 19 | 20 | static void doSomethingList(List animals) { 21 | // do Something with Animals 22 | } 23 | 24 | static void doSomethingListModified(List animals) { 25 | // Adding an element into a list declared with ? is prohibited. 26 | 27 | // animals.add(new Animal());//COMPILER ERROR! 28 | // animals.add(new Dog());//COMPILER ERROR! 29 | } 30 | 31 | static void doSomethingListModifiedSuper(List animals) { 32 | // Adding an element into a list declared with ? is prohibited. 33 | // animals.add(new Animal());//COMPILER ERROR! 34 | // animals.add(new Dog());//COMPILER ERROR! 35 | } 36 | 37 | /* even for interfaces extends keyword should be used */ 38 | static void doSomethingListInterface(List animals) { 39 | // Adding an element into a list declared with ? is prohibited. 40 | 41 | // animals.add(new Animal());//COMPILER ERROR! 42 | // animals.add(new Dog());//COMPILER ERROR! 43 | } 44 | 45 | public static void main(String[] args) { 46 | Animal[] animalsArray = { new Animal(), new Dog() }; 47 | Dog[] dogsArray = { new Dog(), new Dog() }; 48 | 49 | List animalsList = Arrays.asList(animalsArray); 50 | List dogsList = Arrays.asList(dogsArray); 51 | 52 | // Array method can be called with Animal[] or Dog[] 53 | doSomethingArray(animalsArray); 54 | doSomethingArray(dogsArray); 55 | 56 | // List method works with List 57 | // Gives compilation error with List. 58 | doSomethingList(animalsList); 59 | // List not compatible with List 60 | // doSomethingList(dogsList);//COMPILER ERROR 61 | 62 | // Method declared with List compiles 63 | // with both List and List 64 | doSomethingListModified(animalsList); 65 | doSomethingListModified(dogsList); 66 | 67 | // Method declared with List compiles 68 | // with both List and List 69 | // List of any super class of Dog is fine. 70 | // List of any Subclass of Dog is not valid parameter. 71 | doSomethingListModifiedSuper(animalsList); 72 | doSomethingListModifiedSuper(dogsList); 73 | 74 | // A method declared with List can only be called with a List 75 | // declared with type Object. None of the other classes are valid. 76 | // A method declared with List can be called with a List of any type. 77 | // A method declared with List can be called with a 78 | // List of any type - since all classes are sub classes of Object. 79 | 80 | // ? can only be used in Declaring a type. Cannot be used as part of 81 | // definition. 82 | List listAnimals = new ArrayList(); // COMPILES 83 | // List genericList = new ArrayList(); //COMPILER 84 | // ERROR 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/generics/GenericsExamples3.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.generics; 2 | 3 | import java.util.List; 4 | 5 | class MyList { 6 | private List values; 7 | 8 | void add(String value) { 9 | values.add(value); 10 | } 11 | 12 | void remove(String value) { 13 | values.remove(value); 14 | } 15 | } 16 | 17 | class MyListGeneric { 18 | private List values; 19 | 20 | void add(T value) { 21 | values.add(value); 22 | } 23 | 24 | void remove(T value) { 25 | values.remove(value); 26 | } 27 | 28 | T get(int index) { 29 | return values.get(index); 30 | } 31 | } 32 | 33 | class MyListRestricted { 34 | private List values; 35 | 36 | void add(T value) { 37 | values.add(value); 38 | } 39 | 40 | void remove(T value) { 41 | values.remove(value); 42 | } 43 | 44 | T get(int index) { 45 | return values.get(index); 46 | } 47 | } 48 | 49 | public class GenericsExamples3 { 50 | 51 | static X doSomething(X number) { 52 | X result = number; 53 | // do something with result 54 | return result; 55 | } 56 | 57 | public static void main(String[] args) { 58 | 59 | // MyList can be used to store a list of Strings only. 60 | MyList myList = new MyList(); 61 | myList.add("Value 1"); 62 | myList.add("Value 2"); 63 | 64 | // If I would want to create MyList accepting Integer's, I would need to 65 | // create a new Class. 66 | 67 | // Solution to this Problem is generics. 68 | // Replace String with T and create a new class MyListGeneric. 69 | 70 | // Note the declaration of the class "class MyListGeneric". 71 | // Instead of T, We can use any valid identifier(ofcourse the same 72 | // identifier everywhere) 73 | 74 | // If a generic is declared as part of class declaration, it can be used 75 | // any where a type can be used in a class - method (return type or 76 | // argument), member variable etc. 77 | 78 | // Now the MyListGeneric class can be used to create a list of Integers 79 | // or a list of Strings 80 | MyListGeneric myListString = new MyListGeneric(); 81 | myListString.add("Value 1"); 82 | myListString.add("Value 2"); 83 | 84 | MyListGeneric myListInteger = new MyListGeneric(); 85 | myListInteger.add(1); 86 | myListInteger.add(2); 87 | 88 | // In MyListGeneric, Type P is defined as part of class declaration. Any 89 | // Java Type can be used a type for this class. 90 | // If we would want to restrict the types allowed for a Generic Type, we 91 | // can use a Generic Restriction 92 | 93 | // In declaration of the class, we specified a constraint 94 | // "T extends Number" 95 | // class MyListRestricted 96 | // Now, we can use the class MyListRestricted with any class extending 97 | // Number - Float, Integer, Double etc. 98 | 99 | // String not valid substitute for constraint "T extends Number" 100 | // MyListRestricted restrictedStringList = 101 | // new MyListRestricted();//COMPILER ERROR 102 | MyListRestricted restrictedListInteger = new MyListRestricted(); 103 | restrictedListInteger.add(1); 104 | restrictedListInteger.add(2); 105 | 106 | // A generic type can be declared as part of method declaration as well. 107 | // Then the generic type can be used anywhere in the method (return 108 | // type, parameter type, local or block variable type) 109 | Integer i = 5; 110 | Integer k = doSomething(i); 111 | } 112 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/initializers/InitializerExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.initializers; 2 | 3 | public class InitializerExamples { 4 | static int count; 5 | int i; 6 | { 7 | // This is an instance initializers. Run every time an object is 8 | // created. 9 | // static and instance variables can be accessed 10 | System.out.println("Instance Initializer"); 11 | i = 6; 12 | count = count + 1; 13 | System.out 14 | .println("Count when Instance Initializer is run is " + count); 15 | } 16 | 17 | static { 18 | // This is a static initializers. Run only when Class is first loaded. 19 | // Only static variables can be accessed 20 | System.out.println("Static Initializer"); 21 | // i = 6;//COMPILER ERROR 22 | System.out.println("Count when Static Initializer is run is " + count); 23 | } 24 | 25 | public static void main(String[] args) { 26 | InitializerExamples example = new InitializerExamples();// Output below 27 | // Static Initializer 28 | // Count when Static Initializer is run is 0 29 | // Instance Initializer 30 | // Count when Instance Initializer is run is 1 31 | 32 | InitializerExamples example1 = new InitializerExamples();// Output below 33 | // Instance Initializer 34 | // Count when Instance Initializer is run is 2 35 | 36 | InitializerExamples example2 = new InitializerExamples();// Output below 37 | // Instance Initializer 38 | // Count when Instance Initializer is run is 3 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/innerclass/AnonymousClass.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.innerclass; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | class Animal { 7 | void bark() { 8 | System.out.println("Animal Bark"); 9 | } 10 | }; 11 | 12 | public class AnonymousClass { 13 | 14 | private static String[] reverseSort(String[] array) { 15 | 16 | Comparator reverseComparator = new Comparator() { 17 | /* Anonymous Class */ 18 | @Override 19 | public int compare(String string1, String string2) { 20 | return string2.compareTo(string1); 21 | } 22 | 23 | }; 24 | 25 | Arrays.sort(array, reverseComparator); 26 | 27 | return array; 28 | } 29 | 30 | public static void main(String[] args) { 31 | 32 | String[] array = { "Apple", "Cat", "Boy" }; 33 | 34 | System.out.println(Arrays.toString(reverseSort(array)));// [Cat, Boy, 35 | // Apple] 36 | 37 | /* Second Anonymous Class - SubClass of Animal */ 38 | Animal animal = new Animal() { 39 | void bark() { 40 | System.out.println("Subclass bark"); 41 | } 42 | }; 43 | 44 | animal.bark();// Subclass bark 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/innerclass/InnerClassExamples.java: -------------------------------------------------------------------------------- 1 | 2 | package com.in28minutes.java.innerclass; 3 | class OuterClass { 4 | private int outerClassInstanceVariable; 5 | 6 | public void exampleMethod() { 7 | int localVariable; 8 | final int finalVariable = 5; 9 | 10 | class MethodLocalInnerClass { 11 | public void method() { 12 | // Can access class instance variables 13 | System.out.println(outerClassInstanceVariable); 14 | 15 | // Cannot access method's non-final local variables 16 | // localVariable = 5;//Compiler Error 17 | System.out.println(finalVariable);// Final variable is fine.. 18 | } 19 | } 20 | 21 | // MethodLocalInnerClass can be instantiated only in this method 22 | MethodLocalInnerClass m1 = new MethodLocalInnerClass(); 23 | m1.method(); 24 | } 25 | 26 | // MethodLocalInnerClass can be instantiated only in the method where it is 27 | // declared 28 | // MethodLocalInnerClass m1 = new MethodLocalInnerClass();//COMPILER ERROR 29 | 30 | public static class StaticNestedClass { 31 | private int staticNestedClassVariable; 32 | 33 | public int getStaticNestedClassVariable() { 34 | return staticNestedClassVariable; 35 | } 36 | 37 | public void setStaticNestedClassVariable(int staticNestedClassVariable) { 38 | this.staticNestedClassVariable = staticNestedClassVariable; 39 | } 40 | 41 | public void privateVariablesOfOuterClassAreNOTAvailable() { 42 | // outerClassInstanceVariable = 5; //COMPILE ERROR 43 | } 44 | } 45 | 46 | public class InnerClass { 47 | private int innerClassVariable; 48 | 49 | public int getInnerClassVariable() { 50 | return innerClassVariable; 51 | } 52 | 53 | public void setInnerClassVariable(int innerClassVariable) { 54 | this.innerClassVariable = innerClassVariable; 55 | } 56 | 57 | public void privateVariablesOfOuterClassAreAvailable() { 58 | outerClassInstanceVariable = 5; // we can access the value and 59 | // change it 60 | 61 | System.out.println("Inner class ref is " + this); 62 | 63 | // Accessing outer class reference variable 64 | System.out.println("Outer class ref is " + OuterClass.this); 65 | } 66 | } 67 | 68 | public void createInnerClass() { 69 | // Just use the inner class name to create it 70 | InnerClass inner = new InnerClass(); 71 | } 72 | 73 | } 74 | 75 | public class InnerClassExamples { 76 | public static void main(String[] args) { 77 | // Static Nested Class can be created without needing to create its 78 | // parent. Without creating NestedClassesExample, we created 79 | // StaticNestedClass 80 | OuterClass.StaticNestedClass staticNestedClass1 = new OuterClass.StaticNestedClass(); 81 | staticNestedClass1.setStaticNestedClassVariable(5); 82 | 83 | OuterClass.StaticNestedClass staticNestedClass2 = new OuterClass.StaticNestedClass(); 84 | staticNestedClass2.setStaticNestedClassVariable(10); 85 | 86 | // Static Nested Class member variables are not static. They can have 87 | // different values. 88 | System.out.println(staticNestedClass1.getStaticNestedClassVariable()); // 5 89 | System.out.println(staticNestedClass2.getStaticNestedClassVariable()); // 10 90 | 91 | // COMPILER ERROR! You cannot create an inner class on its own. 92 | // InnerClass innerClass = new InnerClass(); 93 | OuterClass example = new OuterClass(); 94 | 95 | // To create an Inner Class you need an instance of Outer Class 96 | OuterClass.InnerClass innerClass = example.new InnerClass(); 97 | 98 | } 99 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/access/ExampleClass.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.access; 2 | 3 | public class ExampleClass { 4 | int defaultVariable; 5 | public int publicVariable; 6 | private int privateVariable; 7 | protected int protectedVariable; 8 | 9 | void defaultMethod() { 10 | privateVariable = 5; 11 | } 12 | 13 | public void publicMethod() { 14 | 15 | } 16 | 17 | private void privateMethod() { 18 | 19 | } 20 | 21 | protected void protectedMethod() { 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/access/SubClassInSamePackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.access; 2 | 3 | public class SubClassInSamePackage extends ExampleClass { 4 | 5 | void subClassMethod() { 6 | publicVariable = 5; 7 | publicMethod(); 8 | 9 | // privateVariable is not visible to SubClass 10 | // Below Line, uncommented, would give compiler error 11 | // privateVariable=5; //COMPILE ERROR 12 | // privateMethod(); 13 | 14 | protectedVariable = 5; 15 | protectedMethod(); 16 | 17 | defaultVariable = 5; 18 | defaultMethod(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/access/TestClassInSamePackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.access; 2 | 3 | public class TestClassInSamePackage { 4 | public static void main(String[] args) { 5 | ExampleClass example = new ExampleClass(); 6 | 7 | example.publicVariable = 5; 8 | example.publicMethod(); 9 | 10 | // privateVariable is not visible 11 | // Below Line, uncommented, would give compiler error 12 | // example.privateVariable=5; //COMPILE ERROR 13 | // example.privateMethod(); 14 | 15 | example.protectedVariable = 5; 16 | example.protectedMethod(); 17 | 18 | example.defaultVariable = 5; 19 | example.defaultMethod(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/access/different/SubClassInDifferentPackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.access.different; 2 | 3 | import com.in28minutes.java.membermodifiers.access.ExampleClass; 4 | 5 | public class SubClassInDifferentPackage extends ExampleClass { 6 | 7 | void subClassMethod() { 8 | publicVariable = 5; 9 | publicMethod(); 10 | 11 | // privateVariable is not visible to SubClass 12 | // Below Line, uncommented, would give compiler error 13 | // privateVariable=5; //COMPILE ERROR 14 | // privateMethod(); 15 | 16 | protectedVariable = 5; 17 | protectedMethod(); 18 | 19 | // privateVariable is not visible to SubClass 20 | // Below Line, uncommented, would give compiler error 21 | // defaultVariable = 5; //COMPILE ERROR 22 | // defaultMethod(); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/access/different/TestClassInDifferentPackage.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.access.different; 2 | 3 | import com.in28minutes.java.membermodifiers.access.ExampleClass; 4 | 5 | public class TestClassInDifferentPackage { 6 | public static void main(String[] args) { 7 | ExampleClass example = new ExampleClass(); 8 | 9 | example.publicVariable = 5; 10 | example.publicMethod(); 11 | 12 | // privateVariable,privateMethod are not visible 13 | // Below Lines, uncommented, would give compiler error 14 | // example.privateVariable=5; //COMPILE ERROR 15 | // example.privateMethod();//COMPILE ERROR 16 | 17 | // protectedVariable,protectedMethod are not visible 18 | // Below Lines, uncommented, would give compiler error 19 | // example.protectedVariable = 5; //COMPILE ERROR 20 | // example.protectedMethod();//COMPILE ERROR 21 | 22 | // defaultVariable,defaultMethod are not visible 23 | // Below Lines, uncommented, would give compiler error 24 | // example.defaultVariable = 5;//COMPILE ERROR 25 | // example.defaultMethod();//COMPILE ERROR 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/nonaccess/FinalMemberModifiersExample.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.nonaccess; 2 | 3 | public class FinalMemberModifiersExample { 4 | final int FINAL_VALUE = 5; 5 | 6 | final void finalMethod() { 7 | // final value cannot be modified 8 | // Below line, uncommented, causes compilation Error 9 | // FINAL_VALUE = 6;//COMPILER ERROR 10 | } 11 | 12 | void testMethod(final int finalArgument) { 13 | // final argument cannot be modified 14 | // Below line, uncommented, causes compilation Error 15 | // finalArgument = 5;//COMPILER ERROR 16 | } 17 | } 18 | 19 | class SubClass extends FinalMemberModifiersExample { 20 | // final method cannot be over-riddent 21 | // Below method, uncommented, causes compilation Error 22 | /* 23 | * final void finalMethod(){ 24 | * 25 | * } 26 | */ 27 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/membermodifiers/nonaccess/StaticModifierExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.membermodifiers.nonaccess; 2 | 3 | class Cricketer { 4 | private static int count; 5 | 6 | public Cricketer() { 7 | count++; 8 | } 9 | 10 | static int getCount() { 11 | return count; 12 | } 13 | } 14 | 15 | class Animal { 16 | static void StaticMethod() { 17 | System.out.println("Animal Static Method"); 18 | } 19 | } 20 | 21 | class Dog extends Animal { 22 | static void StaticMethod() { 23 | System.out.println("Dog Static Method"); 24 | } 25 | } 26 | 27 | public class StaticModifierExamples { 28 | private static int staticVariable; 29 | private int instanceVariable; 30 | 31 | public static void staticMethod() { 32 | // instance variables are not accessible in static methods 33 | // instanceVariable = 10; //COMPILER ERROR 34 | 35 | // Also, this Keyword is not accessible.this refers to object. 36 | // static methods are class methods 37 | 38 | // static variables are accessible in static methods 39 | staticVariable = 10; 40 | } 41 | 42 | public void instanceMethod() { 43 | // static and instance variables are accessible in instance methods 44 | instanceVariable = 10; 45 | staticVariable = 10; 46 | } 47 | 48 | public static void main(String[] args) { 49 | // static int i =5; //COMPILER ERROR 50 | StaticModifierExamples example = new StaticModifierExamples(); 51 | 52 | // instance variables and methods are only accessible through object 53 | // references 54 | example.instanceVariable = 10; 55 | example.instanceMethod(); 56 | // StaticModifierExamples.instanceVariable = 10;//COMPILER ERROR 57 | // StaticModifierExamples.instanceMethod();//COMPILER ERROR 58 | 59 | // static variables and methods are accessible through object references 60 | // and Class Name. 61 | example.staticVariable = 10; 62 | example.staticMethod(); 63 | StaticModifierExamples.staticVariable = 10; 64 | StaticModifierExamples.staticMethod(); 65 | 66 | // It is always recommended to use Class Name to access a static 67 | // variable or method. 68 | // This is because static methods are class level methods. It is not 69 | // appropriate 70 | // to use instance references to call static methods (even though it 71 | // compiles and works). 72 | 73 | Cricketer cricketer1 = new Cricketer(); 74 | Cricketer cricketer2 = new Cricketer(); 75 | Cricketer cricketer3 = new Cricketer(); 76 | Cricketer cricketer4 = new Cricketer(); 77 | 78 | System.out.println(Cricketer.getCount());// 4 79 | 80 | Animal animal = new Dog(); 81 | animal.StaticMethod();// Animal Static Method 82 | 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/object/EqualsHashCodeExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.object; 2 | 3 | class Client { 4 | private int id; 5 | 6 | public Client(int id) { 7 | this.id = id; 8 | } 9 | 10 | @Override 11 | public int hashCode() { 12 | final int prime = 31; 13 | int result = 1; 14 | result = prime * result + id; 15 | return result; 16 | } 17 | 18 | @Override 19 | public boolean equals(Object obj) { 20 | if (this == obj) 21 | return true; 22 | if (obj == null) 23 | return false; 24 | if (getClass() != obj.getClass()) 25 | return false; 26 | Client other = (Client) obj; 27 | if (id != other.id) 28 | return false; 29 | return true; 30 | } 31 | 32 | } 33 | 34 | public class EqualsHashCodeExamples { 35 | 36 | public static void main(String[] args) { 37 | 38 | // == comparison operator checks if the object references are pointing 39 | // to the same object. It does NOT look at the content of the object. 40 | Client client1 = new Client(25); 41 | Client client2 = new Client(25); 42 | Client client3 = client1; 43 | 44 | System.out.println(client1.equals(client2));// true 45 | System.out.println(client1.equals(client3));// true 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/object/ToStringExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.object; 2 | 3 | class Animal { 4 | 5 | public Animal(String name, String type) { 6 | this.name = name; 7 | this.type = type; 8 | } 9 | 10 | String name; 11 | String type; 12 | 13 | @Override 14 | public String toString() { 15 | return "Animal [name=" + name + ", type=" + type + "]"; 16 | } 17 | } 18 | 19 | public class ToStringExamples { 20 | public static void main(String[] args) { 21 | Animal animal = new Animal("Tommy", "Dog"); 22 | System.out.println(animal);// Animal [name=Tommy, type=Dog] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/object/constructors/ConstructorExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.object.constructors; 2 | 3 | class Animal { 4 | String name; 5 | 6 | public Animal(String name) { 7 | this.name = name; 8 | System.out.println("Animal Constructor with name"); 9 | } 10 | } 11 | 12 | class Dog extends Animal { 13 | public Dog(String name) { 14 | super(name); 15 | } 16 | 17 | public Dog() { 18 | super("Default Dog Name"); 19 | } 20 | } 21 | 22 | public class ConstructorExamples { 23 | public static void main(String[] args) { 24 | Dog dog = new Dog("Terry"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/cohesion/problem/CohesionExampleProblem.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.cohesion.problem; 2 | 3 | //Cohesion is a measure of how related the responsibilities of a class are. 4 | //This class is downloading from internet, parsing data and storing data to database. 5 | //The responsibilities of this class are not really related. This is not cohesive class. 6 | class DownloadAndStore { 7 | void downloadFromInternet() { 8 | 9 | } 10 | 11 | void parseData() { 12 | 13 | } 14 | 15 | void storeIntoDatabase() { 16 | 17 | } 18 | 19 | void doEverything() { 20 | downloadFromInternet(); 21 | parseData(); 22 | storeIntoDatabase(); 23 | } 24 | } 25 | 26 | public class CohesionExampleProblem { 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/cohesion/solution/CohesionExampleSolution.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.cohesion.solution; 2 | 3 | //This is a better way of approaching the problem. Different classes have their 4 | //own responsibilities. 5 | 6 | class InternetDownloader { 7 | public void downloadFromInternet() { 8 | 9 | } 10 | } 11 | 12 | class DataParser { 13 | public void parseData(String content) { 14 | } 15 | } 16 | 17 | class DatabaseStorer { 18 | public void storeIntoDatabase(String data) { 19 | } 20 | } 21 | 22 | class DownloadAndStore { 23 | void doEverything() { 24 | new InternetDownloader().downloadFromInternet(); 25 | new DataParser().parseData(""); 26 | new DatabaseStorer().storeIntoDatabase(""); 27 | } 28 | } 29 | 30 | public class CohesionExampleSolution { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/coupling/problem/CouplingExamplesProblem.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.coupling.problem; 2 | 3 | //Coupling is a measure of how much a class is dependent on other classes. 4 | //There should minimal dependencies between classes. 5 | //Consider the example below: 6 | 7 | class ShoppingCartEntry { 8 | public float price; 9 | public int quantity; 10 | } 11 | 12 | class ShoppingCart { 13 | public ShoppingCartEntry[] items; 14 | } 15 | 16 | class Order { 17 | private ShoppingCart cart; 18 | private float salesTax; 19 | 20 | public Order(ShoppingCart cart, float salesTax) { 21 | this.cart = cart; 22 | this.salesTax = salesTax; 23 | } 24 | 25 | // This method know the internal details of ShoppingCartEntry and 26 | // ShoppingCart classes. If there is any change in any of those 27 | // classes, this method also needs to change. 28 | public float orderTotalPrice() { 29 | float cartTotalPrice = 0; 30 | for (int i = 0; i < cart.items.length; i++) { 31 | cartTotalPrice += cart.items[i].price * cart.items[i].quantity; 32 | } 33 | cartTotalPrice += cartTotalPrice * salesTax; 34 | return cartTotalPrice; 35 | } 36 | } 37 | 38 | public class CouplingExamplesProblem { 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/coupling/solution/CouplingExamplesSolution.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.coupling.solution; 2 | 3 | class ShoppingCartEntry { 4 | float pricedummy; 5 | int quantity; 6 | 7 | public float getTotalPrice() { 8 | return pricedummy * quantity; 9 | } 10 | } 11 | 12 | class CartContents { 13 | ShoppingCartEntry[] items; 14 | 15 | public float getTotalPrice() { 16 | float totalPrice = 0; 17 | for (ShoppingCartEntry item : items) { 18 | totalPrice += item.getTotalPrice(); 19 | } 20 | return totalPrice; 21 | } 22 | } 23 | 24 | class Order { 25 | private CartContents cart; 26 | private float salesTax; 27 | 28 | public Order(CartContents cart, float salesTax) { 29 | this.cart = cart; 30 | this.salesTax = salesTax; 31 | } 32 | 33 | public float totalPrice() { 34 | return cart.getTotalPrice() * (1.0f + salesTax); 35 | } 36 | } 37 | 38 | public class CouplingExamplesSolution { 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/encapsulation/EncapsulationExample.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.encapsulation; 2 | 3 | class CricketScorer { 4 | private int score = 0; 5 | 6 | public int getScore() { 7 | return score; 8 | } 9 | 10 | public void addRuns(int score) { 11 | this.score = this.score + score; 12 | } 13 | 14 | public void six() { 15 | addRuns(6); 16 | } 17 | 18 | public void four() { 19 | addRuns(4); 20 | } 21 | 22 | public void single() { 23 | addRuns(1); 24 | } 25 | 26 | public void printScore() { 27 | System.out.println("Score : " + score); 28 | } 29 | 30 | } 31 | 32 | public class EncapsulationExample { 33 | public static void main(String[] args) { 34 | CricketScorer scorer = new CricketScorer(); 35 | scorer.four(); 36 | scorer.four(); 37 | scorer.single(); 38 | scorer.six(); 39 | scorer.six(); 40 | scorer.six(); 41 | scorer.printScore(); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/EveryClassExtendsObject.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance; 2 | 3 | //Every Java class extends Object class 4 | public class EveryClassExtendsObject { 5 | public void testMethod() throws CloneNotSupportedException { 6 | // toString,hashCode,clone methods are 7 | // inherited from Object class 8 | System.out.println(this.toString()); 9 | System.out.println(this.hashCode()); 10 | System.out.println(this.clone()); 11 | } 12 | 13 | public static void main(String[] args) throws CloneNotSupportedException { 14 | EveryClassExtendsObject example1 = new EveryClassExtendsObject(); 15 | 16 | EveryClassExtendsObject example2 = new EveryClassExtendsObject(); 17 | 18 | if (example1 instanceof Object) { 19 | System.out.println("I extend Object");// Will be printed 20 | } 21 | 22 | // equals method is inherited from Object class 23 | System.out.println(example1.equals(example2));// false 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/InheritanceExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance; 2 | 3 | abstract class Animal { 4 | String name; 5 | 6 | // cool functionality 7 | abstract String bark(); 8 | } 9 | 10 | class Dog extends Animal { 11 | String bark() { 12 | return "Bow Bow"; 13 | } 14 | } 15 | 16 | class Cat extends Animal { 17 | String bark() { 18 | return "Meow Meow"; 19 | } 20 | } 21 | 22 | public class InheritanceExamples { 23 | public static void main(String[] args) { 24 | Animal animal = new Dog(); 25 | System.out.println(animal.bark()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/overloading/OverloadingRules.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.overloading; 2 | 3 | public class OverloadingRules { 4 | } 5 | 6 | class Foo { 7 | public void doIt(int number) { 8 | System.out.println("test"); 9 | } 10 | } 11 | 12 | class Bar extends Foo { 13 | public void doIt(String str) { 14 | System.out.println("test"); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/overriding/OverridingRules.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.overriding; 2 | 3 | import java.io.FileNotFoundException; 4 | 5 | public class OverridingRules { 6 | } 7 | 8 | class SuperClass { 9 | public void publicMethod() throws FileNotFoundException { 10 | 11 | } 12 | 13 | void protectedMethod() { 14 | 15 | } 16 | } 17 | 18 | class SubClass { 19 | // Cannot reduce visibility of SuperClass Method 20 | // So, only option is public 21 | // Cannot throw bigger exceptions than Super Class 22 | public void publicMethod() /* throws IOException */{ 23 | 24 | } 25 | 26 | // Can be overridden with public,(default) or protected 27 | // private would give COMPILE ERROR! 28 | public void protectedMethod() { 29 | 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/polymorphism/Animal.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.polymorphism; 2 | 3 | public class Animal { 4 | public String shout() { 5 | return "Don't Know!"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/polymorphism/Cat.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.polymorphism; 2 | 3 | class Cat extends Animal { 4 | // This is method overriding. 5 | // Method shout in Animal is being overridden. 6 | 7 | // Overriding Class cannot reduce visibility of the method. 8 | // So, shout method cannot be declared as protected. 9 | public String shout() { 10 | return "Meow Meow"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/polymorphism/Dog.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.polymorphism; 2 | 3 | class Dog extends Animal { 4 | public String shout() { 5 | return "BOW BOW"; 6 | } 7 | 8 | public void run() { 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/polymorphism/TestPolymorphism.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.polymorphism; 2 | 3 | public class TestPolymorphism { 4 | 5 | public static void main(String[] args) { 6 | Animal animal1 = new Animal(); 7 | System.out.println(animal1.shout()); // Don't Know! 8 | 9 | Animal animal2 = new Dog(); 10 | 11 | // Reference variable type => Animal 12 | // Object referred to => Dog 13 | // Dog's bark method is called. 14 | System.out.println(animal2.shout()); // BOW BOW 15 | 16 | // Even though dog has a method run,it cannot be 17 | // invoked using super class reference variable 18 | // animal2.run();//COMPILE ERROR 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/reuse/Actor.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.reuse; 2 | 3 | public class Actor { 4 | public void act() { 5 | System.out.println("Act"); 6 | }; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/reuse/Comedian.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.reuse; 2 | 3 | //IS-A relationship. Comedian is-a Actor 4 | public class Comedian extends Actor { 5 | public void performComedy() { 6 | System.out.println("Comedy"); 7 | }; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/reuse/Hero.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.reuse; 2 | 3 | //IS-A relationship. Hero is-a Actor 4 | public class Hero extends Actor { 5 | public void fight() { 6 | System.out.println("fight"); 7 | }; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/inheritance/reuse/TestReuse.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.inheritance.reuse; 2 | 3 | public class TestReuse { 4 | public static void main(String[] args) { 5 | Hero hero = new Hero(); 6 | // act method inherited from Actor 7 | hero.act();// Act 8 | hero.fight();// fight 9 | 10 | Comedian comedian = new Comedian(); 11 | // act method inherited from Actor 12 | comedian.act();// Act 13 | comedian.performComedy();// Comedy 14 | 15 | // Super class reference variable can hold 16 | // an object of sub class 17 | Actor actor1 = new Comedian(); 18 | Actor actor2 = new Hero(); 19 | 20 | // Object is super class of all java classes 21 | Object object = new Hero(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/Aeroplane.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | 3 | public class Aeroplane implements Flyable { 4 | public void fly() { 5 | System.out.println("Aeroplane is flying"); 6 | } 7 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/Bird.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | public class Bird implements Flyable { 3 | public void fly() { 4 | System.out.println("Bird is flying"); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/Flyable.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | 3 | public interface Flyable { 4 | void fly(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/IntefaceRules.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | 3 | public class IntefaceRules { 4 | } 5 | 6 | interface ExampleInterface1 { 7 | // By default - public static final. No other modifier allowed 8 | // value1,value2,value3,value4 all are - public static final 9 | int value1 = 10; 10 | public int value2 = 15; 11 | public static int value3 = 20; 12 | public static final int value4 = 25; 13 | 14 | // private int value5 = 10;//COMPILER ERROR 15 | 16 | // By default - public abstract. No other modifier allowed 17 | void method1();// method1 is public and abstract 18 | // private void method6();//COMPILER ERROR! 19 | 20 | //Interface can have a default definition of method. 21 | //NEW FEATURE 22 | default void method5() { 23 | System.out.println("Method5"); 24 | } 25 | } 26 | 27 | interface ExampleInterface2 { 28 | void method2(); 29 | } 30 | 31 | // An interface can extend another interface 32 | // Class implementing SubInterface1 should 33 | // implement method3 and method1(from ExampleInterface1) 34 | interface SubInterface1 extends ExampleInterface1 { 35 | void method3(); 36 | } 37 | 38 | /* 39 | * //COMPILE ERROR IF UnCommented //Interface cannot extend a Class interface 40 | * SubInterface2 extends InterfaceRules{ void method3(); } 41 | */ 42 | 43 | /* A Class can implement multiple interfaces */ 44 | class SampleImpl implements ExampleInterface1, ExampleInterface2 { 45 | /* 46 | * A class should implement all the methods in an interface. If either of 47 | * method1 or method2 is commented, it would result in compilation error. 48 | */ 49 | public void method2() { 50 | System.out.println("Sample Implementation for Method2"); 51 | } 52 | 53 | public void method1() { 54 | System.out.println("Sample Implementation for Method1"); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/InterfaceExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | 3 | public class InterfaceExamples { 4 | public static void main(String[] args) { 5 | Flyable flyable = new Bird(); 6 | flyable.fly(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/oops/interfaces/InterfaceWithMain.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.oops.interfaces; 2 | 3 | 4 | public class InterfaceWithMain { 5 | public static void main(String[] args) { 6 | Bird bird = new Bird(); 7 | bird.fly();// Bird is flying 8 | 9 | Aeroplane aeroplane = new Aeroplane(); 10 | aeroplane.fly();// Aeroplane is flying 11 | 12 | // An interface reference variable can hold 13 | // objects of any implementation of interface 14 | Flyable flyable1 = new Bird(); 15 | Flyable flyable2 = new Aeroplane(); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/IncrementAndDecrementOperators.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | //1.D 2.C 3.B 4.C 5.E 6.C 7.E 8.B 9.D 10.A 11.D 12.D 13.B 14.A 15.C 16.B 17.D 18.C 19.E 20.D 21.D 22.A 23.A 24.C 25.B 4 | class IncrementAndDecrementOperators { 5 | public static void main(String[] args) { 6 | // Except for a minor difference 7 | // ++i,i++ is similar to i = i+1 8 | // --i,i-- is similar to i = i-1 9 | // ++i is called pre-increment,i++ post increment 10 | // pre-increment statement returns value after increment 11 | // post-increment statement returns value before increment 12 | int i = 25; 13 | int j = ++i;// i is incremented to 26, assigned to j 14 | System.out.println(i + " " + j);// 26 26 15 | 16 | i = 25; 17 | j = i++;// i value(25) is assigned to j, then incremented to 26 18 | System.out.println(i + " " + j);// 26 25 19 | 20 | i = 25; 21 | j = --i;// i is decremented to 24, assigned to j 22 | System.out.println(i + " " + j);// 24 24 23 | 24 | i = 25; 25 | j = i--;// i value(25) is assigned to j, then decremented to 24 26 | System.out.println(i + " " + j);// 24 25 27 | 28 | final int k = 100; 29 | // j=k++;//COMPILER ERROR! Final value cannot be modified 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/InstanceOfExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | public class InstanceOfExamples { 4 | public static void main(String[] args) { 5 | 6 | // instanceof is used to check if an object is of a particular type. 7 | SubClass subClass = new SubClass(); 8 | Object subClassObj = new SubClass(); 9 | 10 | SubClass2 subClass2 = new SubClass2(); 11 | SomeOtherClass someOtherClass = new SomeOtherClass(); 12 | 13 | System.out.println(subClass instanceof SubClass);// true 14 | System.out.println(subClass instanceof SuperClass);// true 15 | System.out.println(subClassObj instanceof SuperClass);// true 16 | 17 | System.out.println(subClass2 instanceof SuperClassImplementingInteface);// true 18 | 19 | // Since Super Class implements the interface, this is true 20 | System.out.println(subClass2 instanceof Interface);// true 21 | 22 | // Compile Error : If the type compared is unrelated 23 | // System.out.println(subClass 24 | // instanceof SomeOtherClass);//Compiler Error 25 | 26 | // Object referred by subClassObj(SubClass)-NOT of type SomeOtherClass 27 | System.out.println(subClassObj instanceof SomeOtherClass);// false 28 | 29 | } 30 | } 31 | 32 | class SuperClass { 33 | }; 34 | 35 | class SubClass extends SuperClass { 36 | }; 37 | 38 | interface Interface { 39 | }; 40 | 41 | class SuperClassImplementingInteface implements Interface { 42 | }; 43 | 44 | class SubClass2 extends SuperClassImplementingInteface { 45 | }; 46 | 47 | class SomeOtherClass { 48 | }; -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/LogicalOperators.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | //1.D 2.C 3.B 4.C 5.E 6.C 7.E 8.B 9.D 10.A 11.D 12.D 13.B 14.A 15.C 16.B 17.D 18.C 19.E 20.D 21.D 22.A 23.A 24.C 25.B 4 | class LogicalOperators { 5 | public static void main(String[] args) { 6 | // Short Circuit And Operator - && 7 | // True when both operands are true 8 | System.out.println(true && true);// true 9 | System.out.println(true && false);// false 10 | System.out.println(false && true);// false 11 | System.out.println(false && false);// false 12 | 13 | // Short Circuit Or Operator - || 14 | // True when atleast one of operands are true 15 | System.out.println(true || true);// true 16 | System.out.println(true || false);// true 17 | System.out.println(false || true);// true 18 | System.out.println(false || false);// false 19 | 20 | // Logical Operators work only with boolean's not number's 21 | // System.out.println(5 || 6);//COMPILER ERROR 22 | 23 | // Short circuit operators are Lazy. 24 | // They stop execution the moment result is clear. 25 | // For &&, if first expression is false,result is false. 26 | // For ||, if first expression is true, the result is true. 27 | // In above 2 situations, second expressions are not executed. 28 | int i = 10; 29 | System.out.println(true || ++i == 11);// true 30 | System.out.println(false && ++i == 11);// false 31 | 32 | // i remains 10, as ++i expressions are not executed 33 | System.out.println(i);// 10 34 | 35 | // Logical Operators &, | are similar to &&, || except 36 | // that they don't short ciruit. They execute the second 37 | // expression even if the result is clear. 38 | 39 | int j = 10; 40 | System.out.println(true | ++j == 11);// true 41 | System.out.println(false & ++j == 12);// false 42 | 43 | // j becomes 12, as both ++j expressions are executed 44 | System.out.println(j);// 12 45 | 46 | // Operator exclusive-OR 47 | // Result is true only if one of the operands is true 48 | System.out.println(true ^ false);// true 49 | System.out.println(false ^ true);// true 50 | System.out.println(true ^ true);// false 51 | System.out.println(false ^ false);// false 52 | 53 | // Not Operator (!) 54 | // Result is the negation of the expression 55 | System.out.println(!false);// true 56 | System.out.println(!true);// false 57 | 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/RelationalOperators.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | public class RelationalOperators { 4 | public static void main(String[] args) { 5 | int number = 7; 6 | // Always return true or false 7 | // <, <=, >, >=, ==, and != 8 | 9 | // greater than operator 10 | System.out.println(number > 5);// true 11 | System.out.println(number > 7);// false 12 | 13 | // greater than equal to operator 14 | System.out.println(number >= 7);// true 15 | 16 | // less than operator 17 | System.out.println(number < 9);// true 18 | System.out.println(number < 7);// false 19 | 20 | // less than equal to operator 21 | System.out.println(number <= 7);// true 22 | 23 | // is equal to operator 24 | System.out.println(number == 7);// true 25 | System.out.println(number == 9);// false 26 | 27 | // NOT equal to operator 28 | System.out.println(number != 9);// true 29 | System.out.println(number != 7);// false 30 | 31 | // NOTE : single = is assignment operator 32 | // == is comparison. Below statement uses =. 33 | System.out.println(number = 7);// 7 34 | 35 | // Equality for Primitives only compares values 36 | int a = 5; 37 | int b = 5; 38 | 39 | // compares if they have same value 40 | System.out.println(a == b);// true 41 | 42 | // Equality for Reference Variables. 43 | Integer aReference = new Integer(5); 44 | Integer bReference = new Integer(5); 45 | 46 | // compares if they are refering to the same object 47 | System.out.println(aReference == bReference);// false 48 | 49 | bReference = aReference; 50 | // Now both are referring to same object 51 | System.out.println(aReference == bReference);// true 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/StringConcatenationExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | //1.D 2.C 3.B 4.C 5.E 6.C 7.E 8.B 9.D 10.A 11.D 12.D 13.B 14.A 15.C 16.B 17.D 18.C 19.E 20.D 21.D 22.A 23.A 24.C 25.B 4 | class StringConcatenationExamples { 5 | public static void main(String[] args) { 6 | // RULE1 : Expressions are evaluated from left to right. 7 | // Except if there are parenthesis. 8 | // RULE2 : number + number = number 9 | // RULE3 : number + String = String 10 | System.out.println(5 + "Test" + 5); // 5Test5 11 | System.out.println(5 + 5 + "Test"); // 10Test 12 | System.out.println("5" + 5 + "Test"); // 55Test 13 | System.out.println("5" + "5" + "25"); // 5525 14 | System.out.println(5 + 5 + "25"); // 1025 15 | System.out.println("" + 5 + 5 + "25"); // 5525 16 | System.out.println(5 + (5 + "25")); // 5525 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/operators/TernaryOperator.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.operators; 2 | 3 | //1.D 2.C 3.B 4.C 5.E 6.C 7.E 8.B 9.D 10.A 11.D 12.D 13.B 14.A 15.C 16.B 17.D 18.C 19.E 20.D 21.D 22.A 23.A 24.C 25.B 4 | class TernaryOperator { 5 | public static void main(String[] args) { 6 | int age = 18; 7 | // syntax - booleanCondition?ResultIfTrue:ResultIfFalse; 8 | System.out.println(age >= 18 ? "Can Vote" : "Cannot Vote");// Can Vote 9 | 10 | age = 15; 11 | System.out.println(age >= 18 ? "Can Vote" : "Cannot Vote");// Cannot 12 | // Vote 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/PrintfExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others; 2 | 3 | public class PrintfExamples { 4 | public static void main(String[] args) { 5 | 6 | // Let's look at a few examples to quickly understand printf function. 7 | System.out.printf("%d", 5);// 5 8 | System.out.printf("My name is %s", "Rithu");// My name is Rithu 9 | System.out.printf("%s is %d Years old", "Rithu", 5);// Rithu is 5 Years 10 | // old 11 | 12 | // In the simplest form, string to be formatted starts with % followed 13 | // by conversion indicator 14 | // b - boolean c - char d - integer f - floating point s - string. 15 | 16 | // Prints 12 using minimum 5 character spaces. 17 | System.out.printf("|%5d|", 12); // prints | 12| 18 | // Prints 1234 using minimum 5 character spaces. 19 | System.out.printf("|%5d|", 1234); // prints | 1234| 20 | // In above example 5 is called width specifier. 21 | 22 | // Left Justification can be done by using - 23 | System.out.printf("|%-5d|", 12); // prints |12 | 24 | 25 | // Using 0 pads the number with 0's 26 | System.out.printf("%05d", 12); // prints 00012 27 | 28 | // Using , format the number using comma's 29 | System.out.printf("%,d", 12345); // prints 12,345 30 | 31 | // Using ( prints negative numbers between ( and ) 32 | System.out.printf("%(d", -12345); // prints (12345) 33 | System.out.printf("%(d", 12345); // prints 12345 34 | 35 | // Using + prints + or - before the number 36 | System.out.printf("%+d", -12345); // prints -12345 37 | System.out.printf("%+d", 12345); // prints +12345 38 | 39 | // For floating point numbers, precision can be specified after. 40 | // Below example uses a precision of 2, so .5678 gets changed to .57 41 | System.out.printf("%5.2f", 1234.5678); // prints 1234.57 42 | 43 | // An error in specifying would give a RuntimeException 44 | // In below example a string is passed to %d argument. 45 | // System.out.printf("%5d","Test"); 46 | // Throws java.util.IllegalFormatConversionException 47 | 48 | // To change the order of printing and passing of arguments, argument 49 | // index can be used 50 | System.out.printf("%3$.1f %2$s %1$d", 123, "Test", 123.4); // prints 51 | // 123.4 52 | // Test 123 53 | 54 | // format method has the same behavior as printf method 55 | System.out.format("%5.2f", 1234.5678);// prints 1234.57 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/SameType.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others; 2 | 3 | public class SameType { 4 | } 5 | 6 | class SuperClass { 7 | 8 | } 9 | 10 | class SubClass extends SuperClass { 11 | 12 | } 13 | 14 | abstract class Abstract { 15 | abstract SuperClass method1(); 16 | } 17 | 18 | interface Interface { 19 | SuperClass method2(); 20 | } 21 | 22 | class ConcreteClass extends Abstract implements Interface { 23 | 24 | public SubClass method2() { 25 | return null; 26 | } 27 | 28 | SubClass method1() { 29 | return null; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/assertexample/AssertExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others.assertexample; 2 | 3 | public class AssertExamples { 4 | // Assertions are introduced in Java 1.4. They enable you to validate 5 | // assumptions. 6 | // If an assert fails (i.e. returns false), AssertionError is thrown (if 7 | // assertions are enabled). 8 | 9 | // assert is a keyword in java since 1.4. Before 1.4, assert can be used as 10 | // identifier. 11 | // To compile code using 1.3 you can use the command below 12 | // javac -source 1.3 OldCode.java => assert can be used as identifier 13 | // with -source 1.4,1.5,5,1.6,6 => assert cannot be used as identifier 14 | 15 | // assertions can easily be enabled and disabled. 16 | 17 | // assertions are disabled by default. 18 | 19 | // Enable assertions : java -ea com.rithus.AssertExamples 20 | // (OR) java -enableassertions com.rithus.AssertExamples 21 | 22 | // Disable assertions : java -da com.rithus.AssertExamples 23 | // (OR) java -disableassertions com.rithus.AssertExamples 24 | 25 | // Selectively enable assertions in a package only 26 | // java -ea:com.rithus 27 | 28 | // Selectively enable assertions in a package and its subpackages only 29 | // java -ea:com.rithus... 30 | 31 | // Enable assertions including system classes 32 | // java -ea -esa 33 | 34 | // Basic assert is shown in the example below 35 | private int computerSimpleInterest(int principal, float interest, int years) { 36 | assert (principal > 0); 37 | return 100; 38 | } 39 | 40 | // If needed debugging information can be added to an assert. 41 | // Look at the example below. 42 | private int computeCompoundInterest(int principal, float interest, int years) { 43 | // condition is always boolean 44 | // second parameter can be anything that converts to a String. 45 | assert (principal > 0) : "principal is " + principal; 46 | return 100; 47 | } 48 | 49 | public static void main(String[] args) { 50 | AssertExamples examples = new AssertExamples(); 51 | System.out.println(examples.computerSimpleInterest(-1000, 1.0f, 5)); 52 | } 53 | 54 | // Assertions should not be used to validate input data to a public method 55 | // or command line argument. 56 | // IllegalArgumentException would be a better option. 57 | 58 | // In public method, only use assertions to check for cases which are never 59 | // supposed to happen. 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/date/CalendarExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others.date; 2 | 3 | import java.text.DateFormat; 4 | import java.util.Calendar; 5 | import java.util.GregorianCalendar; 6 | 7 | public class CalendarExamples { 8 | public static void main(String[] args) { 9 | // Calendar is abstract 10 | // Calendar calendar = new Calendar(); //COMPILER ERROR 11 | 12 | Calendar calendar = Calendar.getInstance(); 13 | 14 | calendar.set(Calendar.DATE, 24); 15 | calendar.set(Calendar.MONTH, 8);// 8 - September 16 | calendar.set(Calendar.YEAR, 2010); 17 | 18 | // Get information about 24th September 2010 19 | System.out.println(calendar.get(Calendar.YEAR));// 2010 20 | System.out.println(calendar.get(Calendar.MONTH));// 8 21 | System.out.println(calendar.get(Calendar.DATE));// 24 22 | System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));// 4 23 | System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));// 39 24 | System.out.println(calendar.get(Calendar.DAY_OF_YEAR));// 267 25 | System.out.println(calendar.getFirstDayOfWeek());// 1 -> Calendar.SUNDAY 26 | 27 | // Add/Manipulate date 28 | calendar.add(Calendar.DATE, 5); 29 | System.out.println(calendar.getTime());// Wed Sep 29 2010 30 | calendar.add(Calendar.MONTH, 1); 31 | System.out.println(calendar.getTime());// Fri Oct 29 2010 32 | calendar.add(Calendar.YEAR, 2); 33 | System.out.println(calendar.getTime());// Mon Oct 29 2012 34 | 35 | // Roll method will only the change the value being modified. 36 | // YEAR remains unaffected when MONTH is changed for instance. 37 | calendar.roll(Calendar.MONTH, 5); 38 | System.out.println(calendar.getTime());// Mon Mar 29 2012 39 | 40 | // Other way of creating calendar 41 | Calendar gregorianCalendar = new GregorianCalendar(2011, 7, 15); 42 | 43 | // Formatting Calendar 44 | // Done by getting the date using calendar.getTime() and 45 | // using the usual formatting of dates. 46 | System.out.println(DateFormat.getInstance().format(calendar.getTime()));// 3/29/12 47 | // 11:39 48 | // AM 49 | 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/date/DateExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others.date; 2 | 3 | import java.text.DateFormat; 4 | import java.text.ParseException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | import java.util.Locale; 8 | 9 | public class DateExamples { 10 | public static void main(String[] args) throws ParseException { 11 | // Important points about Date 12 | // Date is no longer the class Java recommends for storing and 13 | // manipulating date and time. Most of methods in Date are deprecated. 14 | // Use Calendar class instead. 15 | // Date internally represents date-time as number of milliseconds (a 16 | // long value) since 1st Jan 1970. 17 | 18 | // Creating Date Object 19 | Date now = new Date(); 20 | System.out.println(now.getTime()); 21 | 22 | // Manipulating Date Object 23 | Date date = new Date(); 24 | 25 | // Increase time by 6 hrs 26 | date.setTime(date.getTime() + 6 * 60 * 60 * 1000); 27 | System.out.println(date); 28 | 29 | // Decrease time by 6 hrs 30 | date = new Date(); 31 | date.setTime(date.getTime() - 6 * 60 * 60 * 1000); 32 | System.out.println(date); 33 | 34 | // Formatting Dates 35 | System.out.println(DateFormat.getInstance().format(date));// 10/16/12 36 | // 5:18 AM 37 | 38 | // Formatting Dates with a locale 39 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL, 40 | new Locale("it", "IT")).format(date));// marted� 16 ottobre 2012 41 | 42 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL, 43 | Locale.ITALIAN).format(date));// marted� 16 ottobre 2012 44 | 45 | // This uses default locale US 46 | System.out.println(DateFormat.getDateInstance(DateFormat.FULL).format( 47 | date));// Tuesday, October 16, 2012 48 | 49 | System.out.println(DateFormat.getDateInstance().format(date));// Oct 16, 50 | // 2012 51 | System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format( 52 | date));// 10/16/12 53 | System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM) 54 | .format(date));// Oct 16, 2012 55 | 56 | System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format( 57 | date));// October 16, 2012 58 | 59 | // Formatting Dates Using SimpleDateFormat 60 | System.out.println(new SimpleDateFormat("yy-MM-dd").format(date));// 12-10-16 61 | System.out.println(new SimpleDateFormat("yy-MMM-dd").format(date));// 12-Oct-16 62 | System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));// 2012-10-16 63 | 64 | // Parse Dates using DateFormat 65 | Date date2 = DateFormat.getDateInstance(DateFormat.SHORT).parse( 66 | "10/16/12"); 67 | System.out.println(date2);// Tue Oct 16 00:00:00 GMT+05:30 2012 68 | 69 | // Creating Dates using SimpleDateFormat 70 | Date date1 = new SimpleDateFormat("yy-MM-dd").parse("12-10-16"); 71 | System.out.println(date1);// Tue Oct 16 00:00:00 GMT+05:30 2012 72 | 73 | // Print the country of locale 74 | Locale defaultLocale = Locale.getDefault(); 75 | 76 | System.out.println(defaultLocale.getDisplayCountry());// United States 77 | System.out.println(defaultLocale.getDisplayLanguage());// English 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/others/garbagecollection/GarbageCollectionExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.others.garbagecollection; 2 | 3 | import java.util.Calendar; 4 | import java.util.GregorianCalendar; 5 | 6 | public class GarbageCollectionExamples { 7 | void method() { 8 | Calendar calendar = new GregorianCalendar(2000, 10, 30); 9 | System.out.println(calendar); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/serialization/SerializationExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | 10 | class Rectangle implements Serializable { 11 | public Rectangle(int length, int breadth) { 12 | this.length = length; 13 | this.breadth = breadth; 14 | area = length * breadth; 15 | } 16 | 17 | int length; 18 | int breadth; 19 | transient int area; 20 | 21 | private void writeObject(ObjectOutputStream os) throws IOException { 22 | // Do whatever java does usually when serialization is called 23 | os.defaultWriteObject(); 24 | } 25 | 26 | private void readObject(ObjectInputStream is) throws IOException, 27 | ClassNotFoundException { 28 | // Do whatever java does usually when de-serialization is called 29 | is.defaultReadObject(); 30 | // In addition, calculate area also 31 | area = this.length * this.breadth; 32 | } 33 | } 34 | 35 | public class SerializationExamples { 36 | 37 | public static void main(String[] args) throws IOException, 38 | ClassNotFoundException { 39 | // Serialization helps us to save and retrieve the state of an object. 40 | // Serialization => Convert object state to some internal object 41 | // representation. 42 | // De-Serialization => The reverse. Convert internal representation to 43 | // object. 44 | // Two important methods 45 | // ObjectOutputStream.writeObject() // serialize and write to file 46 | // ObjectInputStream.readObject() // read from file and deserialize 47 | 48 | // To serialize an object it should implement Serializable interface 49 | // class Rectangle implements Serializable 50 | 51 | // Serializing an object 52 | FileOutputStream fileStream = new FileOutputStream("Rectangle.ser"); 53 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 54 | objectStream.writeObject(new Rectangle(5, 6)); 55 | objectStream.close(); 56 | 57 | // Deserializing an object 58 | FileInputStream fileInputStream = new FileInputStream("Rectangle.ser"); 59 | ObjectInputStream objectInputStream = new ObjectInputStream( 60 | fileInputStream); 61 | Rectangle rectangle = (Rectangle) objectInputStream.readObject(); 62 | objectInputStream.close(); 63 | System.out.println(rectangle.length);// 5 64 | System.out.println(rectangle.breadth);// 6 65 | System.out.println(rectangle.area);// 30 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/serialization/SerializationExamples2.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.serialization; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.io.ObjectOutputStream; 6 | import java.io.Serializable; 7 | 8 | class House implements Serializable { 9 | public House(int number) { 10 | super(); 11 | this.number = number; 12 | } 13 | 14 | Wall wall; 15 | int number; 16 | } 17 | 18 | class Wall implements Serializable { 19 | int length; 20 | int breadth; 21 | int color; 22 | } 23 | 24 | public class SerializationExamples2 { 25 | 26 | public static void main(String[] args) throws IOException { 27 | 28 | FileOutputStream fileStream = new FileOutputStream("House.ser"); 29 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 30 | House house = new House(10); 31 | house.wall = new Wall(); 32 | // Exception in thread "main" java.io.NotSerializableException: 33 | // com.rithus.serialization.Wall 34 | objectStream.writeObject(house); 35 | objectStream.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/serialization/SerializationExamples3.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.serialization; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | 10 | class Actor { 11 | String name; 12 | 13 | Actor() { 14 | name = "Default"; 15 | } 16 | } 17 | 18 | class Hero extends Actor implements Serializable { 19 | String danceType; 20 | 21 | Hero() { 22 | danceType = "Default"; 23 | } 24 | } 25 | 26 | public class SerializationExamples3 { 27 | 28 | public static void main(String[] args) throws IOException, 29 | ClassNotFoundException { 30 | 31 | FileOutputStream fileStream = new FileOutputStream("Hero.ser"); 32 | ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); 33 | 34 | Hero hero = new Hero(); 35 | hero.danceType = "Ganganam"; 36 | hero.name = "Hero1"; 37 | 38 | // Before -> DanceType :Ganganam Name:Hero1 39 | System.out.println("Before -> DanceType :" + hero.danceType + " Name:" 40 | + hero.name); 41 | // Exception in thread "main" java.io.NotSerializableException: 42 | // com.rithus.serialization.Wall 43 | objectStream.writeObject(hero); 44 | objectStream.close(); 45 | 46 | FileInputStream fileInputStream = new FileInputStream("Hero.ser"); 47 | ObjectInputStream objectInputStream = new ObjectInputStream( 48 | fileInputStream); 49 | hero = (Hero) objectInputStream.readObject(); 50 | objectInputStream.close(); 51 | 52 | // When subclass is serializable and superclass is not, the state of 53 | // subclass variables is retained. However, for the super class, 54 | // initialization 55 | // constructors and initializers are run again. 56 | // After -> DanceType :Ganganam Name:Default 57 | System.out.println("After -> DanceType :" + hero.danceType + " Name:" 58 | + hero.name); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/string/StringBufferBuilderExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.string; 2 | 3 | public class StringBufferBuilderExamples { 4 | public static void main(String[] args) { 5 | // StringBuffer and StringBuilder are used when you want to modify 6 | // object values. 7 | StringBuffer stringbuffer = new StringBuffer("12345"); 8 | stringbuffer.append("6789"); 9 | System.out.println(stringbuffer); // 123456789 10 | // All StringBuffer methods modify the value of the object. 11 | 12 | StringBuilder sb = new StringBuilder("0123456789"); 13 | // StringBuilder delete(int startIndex, int endIndexPlusOne) 14 | System.out.println(sb.delete(3, 7));// 012789 15 | 16 | StringBuilder sb1 = new StringBuilder("abcdefgh"); 17 | // StringBuilder insert(int indext, String whatToInsert) 18 | System.out.println(sb1.insert(3, "ABCD"));// abcABCDdefgh 19 | 20 | StringBuilder sb2 = new StringBuilder("abcdefgh"); 21 | // StringBuilder reverse() 22 | System.out.println(sb2.reverse());// hgfedcba 23 | 24 | // Similar functions exist in StringBuffer also 25 | 26 | // All functions also return a reference to the object after modifying 27 | // it. 28 | // This allows a concept called method chaining. 29 | StringBuilder sb3 = new StringBuilder("abcdefgh"); 30 | System.out.println(sb3.reverse().delete(5, 6).insert(3, "---"));// hgf---edba 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/string/StringExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.string; 2 | 3 | public class StringExamples { 4 | public static void main(String[] args) { 5 | // Strings are immutable 6 | String str3 = "value1"; 7 | str3.concat("value2"); 8 | System.out.println(str3); // value1 9 | 10 | // The result should be assigned to a new reference variable (or same 11 | // variable) can be reused. 12 | String concat = str3.concat("value2"); 13 | System.out.println(concat); // value1value2 14 | 15 | // String on Heap.xls 16 | // A String value once created, cannot be changed. 17 | // If a method is invoked on string object, it returns a new object and 18 | // will not modify the original object. 19 | 20 | // All strings literals are stored in "String constant pool". 21 | // If compiler finds a String literal,it checks if it exists in the 22 | // pool. 23 | // If it exists, it is reused. 24 | 25 | // 1 string object (created on the pool) and 1 reference variable 26 | String str1 = "value"; 27 | 28 | // However, if new operator is used to create string object, 29 | // the new object is created on the heap 30 | 31 | // Following piece of code create 2 objects 32 | // 1. String Literal "value" - created in the "String constant pool" 33 | // 2. String Object - created on the heap 34 | String str2 = new String("value"); 35 | 36 | // String methods 37 | String str = "abcdefghijk"; 38 | // 01234567890 39 | 40 | // char charAt(int paramInt) 41 | System.out.println(str.charAt(2)); // prints a char - c 42 | 43 | // String concat(String paramString) 44 | System.out.println(str.concat("lmn"));// abcdefghijklmn 45 | 46 | System.out.println("ABC".equalsIgnoreCase("abc"));// true 47 | System.out.println("ABCDEFGH".length());// 8 48 | 49 | // String replace(char paramChar1, char paramChar2) 50 | System.out.println("012301230123".replace('0', '4'));// 412341234123 51 | 52 | // String replace(CharSequence paramCharSequence1, CharSequence 53 | // paramCharSequence2) 54 | System.out.println("012301230123".replace("01", "45"));// 452345234523 55 | 56 | // All characters from index paramInt 57 | // String substring(int paramInt) 58 | System.out.println("abcdefghij".substring(3)); // defghij 59 | // 0123456789 60 | 61 | // All characters from index 3 to 6 62 | System.out.println("abcdefghij".substring(3, 7)); // defg 63 | // 0123456789 64 | 65 | System.out.println("ABCDEFGHIJ".toLowerCase()); // abcdefghij 66 | 67 | System.out.println("abcdefghij".toUpperCase()); // ABCDEFGHIJ 68 | 69 | System.out.println("abcdefghij".toString()); // abcdefghij 70 | 71 | // trim removes leading and trailings spaces 72 | System.out.println(" abcd ".trim()); // abcd 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ExecutorServiceExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.Future; 8 | 9 | public class ExecutorServiceExamples { 10 | public static void main(String[] args) throws InterruptedException, 11 | ExecutionException { 12 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 13 | 14 | executorService.execute(new Runnable() { 15 | public void run() { 16 | System.out.println("From ExecutorService"); 17 | } 18 | }); 19 | 20 | System.out.println("End of Main"); 21 | 22 | executorService.shutdown(); 23 | 24 | // Creates an Executor that uses a single worker thread operating off an 25 | // unbounded queue. 26 | ExecutorService executorService1 = Executors.newSingleThreadExecutor(); 27 | 28 | // Creates a thread pool that reuses a fixed number of threads 29 | // operating off a shared unbounded queue. At any point, the parameter 30 | // specifies the most threads that will be active processing tasks. 31 | 32 | ExecutorService executorService2 = Executors.newFixedThreadPool(10); 33 | 34 | // Creates a thread pool that can schedule commands to run after a 35 | // given delay, or to execute periodically. 36 | ExecutorService executorService3 = Executors.newScheduledThreadPool(10); 37 | 38 | Future future = executorService1.submit(new Runnable() { 39 | public void run() { 40 | System.out.println("From executorService1"); 41 | } 42 | }); 43 | 44 | future.get(); // returns null if the task has finished correctly. 45 | 46 | Future futureFromCallable = executorService1.submit(new Callable() { 47 | public String call() throws Exception { 48 | return "RESULT"; 49 | } 50 | }); 51 | 52 | System.out.println("futureFromCallable.get() = " 53 | + futureFromCallable.get()); 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ThreadDeadlock.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | class Resource { 4 | } 5 | 6 | class SomeOperation { 7 | Resource resource1 = new Resource(); 8 | Resource resource2 = new Resource(); 9 | 10 | void method1() throws InterruptedException { 11 | System.out.println(Thread.currentThread().getName() + "is in method1"); 12 | synchronized (resource1) { 13 | System.out.println(Thread.currentThread().getName() 14 | + "is going to sleep"); 15 | 16 | Thread.sleep(1000); 17 | 18 | System.out.println(Thread.currentThread().getName() 19 | + "is out of sleep and will wait for resource 2"); 20 | synchronized (resource2) { 21 | // SOME CODE GOES IN HERE 22 | } 23 | } 24 | } 25 | 26 | void method2() throws InterruptedException { 27 | System.out.println(Thread.currentThread().getName() + "is in method2"); 28 | synchronized (resource2) { 29 | System.out.println(Thread.currentThread().getName() 30 | + "is going to sleep"); 31 | 32 | Thread.sleep(1000); 33 | 34 | System.out.println(Thread.currentThread().getName() 35 | + "is out of sleep and will wait for resource 1"); 36 | synchronized (resource1) { 37 | // SOME CODE GOES IN HERE 38 | } 39 | } 40 | } 41 | 42 | } 43 | 44 | public class ThreadDeadlock implements Runnable { 45 | 46 | SomeOperation operation = new SomeOperation(); 47 | 48 | @Override 49 | public void run() { 50 | try { 51 | operation.method1(); 52 | operation.method2(); 53 | } catch (InterruptedException e) { 54 | // TODO Auto-generated catch block 55 | e.printStackTrace(); 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | ThreadDeadlock r = new ThreadDeadlock(); 61 | Thread one = new Thread(r); 62 | Thread two = new Thread(r); 63 | one.start(); 64 | two.start(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ThreadExampleSynchronized.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | class SpreadSheet { 4 | int cell1, cell2, cell3; 5 | 6 | int setandGetSum(int a1, int a2, int a3) { 7 | cell1 = a1; 8 | sleepForSomeTime(); 9 | cell2 = a2; 10 | sleepForSomeTime(); 11 | cell3 = a3; 12 | sleepForSomeTime(); 13 | return cell1 + cell2 + cell3; 14 | } 15 | 16 | void sleepForSomeTime() { 17 | try { 18 | Thread.sleep(10 * (int) (Math.random() * 100)); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | 25 | class SynchronizedSyntaxExample { 26 | static int count; 27 | int instanceValue; 28 | 29 | // others.. 30 | synchronized void synchronizedExample1() { 31 | // All code goes here.. 32 | } 33 | 34 | void synchronizedExample2() { 35 | synchronized (this) { 36 | // All code goes here.. 37 | } 38 | } 39 | 40 | synchronized static int getCount() { 41 | return count; 42 | } 43 | 44 | static int getCount2() { 45 | synchronized (SynchronizedSyntaxExample.class) { 46 | return count; 47 | } 48 | } 49 | 50 | } 51 | 52 | public class ThreadExampleSynchronized implements Runnable { 53 | 54 | SpreadSheet spreadSheet = new SpreadSheet(); 55 | 56 | public void run() { 57 | for (int i = 0; i < 4; i++) { 58 | System.out.print(spreadSheet.setandGetSum(i, i * 2, i * 3) + " "); 59 | } 60 | } 61 | 62 | public static void main(String[] args) { 63 | ThreadExampleSynchronized r = new ThreadExampleSynchronized(); 64 | Thread one = new Thread(r); 65 | Thread two = new Thread(r); 66 | one.start(); 67 | two.start(); 68 | // First UnSynchronized Run 69 | // 0 3 6 9 12 15 18 18 70 | // Second UnSynchronized Run 71 | // 0 1 6 7 12 18 18 18 72 | // Synchronized Run 73 | // 0 0 6 6 12 12 18 18 74 | 75 | // A static synchronized method and a non-static synchronized method 76 | // will not block each other, 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ThreadExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | public class ThreadExamples { 4 | public static void main(String[] args) { 5 | // Why do we need threads? 6 | // How can we create and run Threads in Java? 7 | // What is Thread synchronization? 8 | 9 | // Assume a Cricket Statistics Application 10 | // Let's say the steps are 11 | // 1. Download and Store Bowling Statistics => 15 Minutes 12 | // 2. Download and Store Batting Statistics => 15 Minutes 13 | // 3. Download and Store Fielding Statistics => 5 Minutes 14 | // 4. Merge and Analyze => 25 Minutes 15 | 16 | // Steps 1, 2 and 3 are independant and can be run in parallel to make 17 | // them faster. 18 | // If run separately, they take 35 (15 + 15 + 5) minutes. 19 | // If run in parallel, (if you are lucky) they might complete in 20 20 | // minutes. 21 | 22 | // To be able to run different steps in parallel, we make use of 23 | // Threads. 24 | 25 | // Look at the Java code below 26 | downloadAndStoreBattingStatistics(); 27 | downloadAndStoreBowlingStatistics(); 28 | downloadAndStoreFieldingStatistics(); 29 | 30 | mergeAndAnalyze(); 31 | 32 | // downloadAndStoreBowlingStatistics starts only after 33 | // downloadAndStoreBattingStatistics completes execution. 34 | // downloadAndStoreFieldingStatistics starts only after 35 | // downloadAndStoreBowlingStatistics completes execution. 36 | 37 | // What if I want to run them in parallel without waiting for the others 38 | // to complete? 39 | // This is where Threads come into picture. 40 | 41 | // Creating a Thread - Method 1 42 | // Extending Thread class 43 | // Note : You cannot extend any other class. 44 | class BattingStatisticsThread extends Thread { 45 | // run method without parameters 46 | public void run() { 47 | for (int i = 0; i < 1000; i++) 48 | System.out.println("Running Batting Statistics " + i); 49 | } 50 | } 51 | 52 | // Creating a Thread - Method 2 53 | // Implementing Runnable interface 54 | // Note : You cannot extend any other class. 55 | class BowlingStatisticsThread implements Runnable { 56 | // run method without parameters 57 | public void run() { 58 | for (int i = 0; i < 1000; i++) 59 | System.out.println("Running Bowling Statistics " + i); 60 | } 61 | } 62 | 63 | // Starting or Running a Thread 64 | // When using inheritance. Create an object and call start method. 65 | BattingStatisticsThread battingThread1 = new BattingStatisticsThread(); 66 | battingThread1.start(); 67 | 68 | // When implementing RunnableInterface. 69 | // Create an object, then a Thread object having implementation of 70 | // interface as constructor argument 71 | // and call start method on thread object. 72 | BowlingStatisticsThread battingInterfaceImpl = new BowlingStatisticsThread(); 73 | Thread battingThread2 = new Thread(battingInterfaceImpl); 74 | battingThread2.start(); 75 | 76 | } 77 | 78 | private static void mergeAndAnalyze() { 79 | // TODO Auto-generated method stub 80 | 81 | } 82 | 83 | private static void downloadAndStoreBattingStatistics() { 84 | // TODO Auto-generated method stub 85 | 86 | } 87 | 88 | private static void downloadAndStoreFieldingStatistics() { 89 | // TODO Auto-generated method stub 90 | 91 | } 92 | 93 | private static void downloadAndStoreBowlingStatistics() { 94 | // TODO Auto-generated method stub 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ThreadPriority.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | public class ThreadPriority { 4 | public static void main(String[] args) throws InterruptedException { 5 | // Each thread in Java is assigned a default Priority 5. This priority 6 | // can be increased or decreased (Range 1 to 10). 7 | // If two threads are waiting, the scheduler picks the thread with 8 | // highest priority to be run. If all threads have equal priority, the 9 | // scheduler then picks one of them randomly. Design programs so that 10 | // they don't depend on priority. 11 | 12 | // Consider the thread example declared below: 13 | class ThreadExample extends Thread { 14 | public void run() { 15 | for (int i = 0; i < 1000; i++) 16 | System.out.println(this.getName() + " Running " + i); 17 | } 18 | } 19 | 20 | // Priority of thread can be changed by invoking setPriority method on 21 | // the thread. 22 | ThreadExample thread1 = new ThreadExample(); 23 | thread1.setPriority(8); 24 | 25 | // Java also provides predefined constants Thread.MAX_PRIORITY(10), 26 | // Thread.MIN_PRIORITY(1), Thread.NORM_PRIORITY(5) which can be used to 27 | // assign priority to a thread. 28 | 29 | // Thread Join method 30 | // Join method is an instance method on the Thread class. Let's see a 31 | // small example to understand what join method does. 32 | 33 | // Lets consider the thread's declared below : thread2, thread3, thread4 34 | 35 | ThreadExample thread2 = new ThreadExample(); 36 | ThreadExample thread3 = new ThreadExample(); 37 | ThreadExample thread4 = new ThreadExample(); 38 | 39 | // We would want to run thread2 and thread3 in parallel but thread4 can 40 | // only run when thread3 is finished. This can be achieved using join 41 | // method. Look at the example code below. 42 | thread3.start(); 43 | thread2.start(); 44 | thread3.join();// wait for thread 3 to complete 45 | System.out.println("Thread3 is completed."); 46 | thread4.start(); 47 | 48 | // thread3.join() method call force the execution of main method to stop 49 | // until thread3 completes execution. After that, thread4.start() method 50 | // is invoked, putting thread4 into a Runnable State. 51 | 52 | // Overloaded Join method 53 | // Join method also has an overloaded method accepting time in 54 | // milliseconds as a parameter. 55 | thread4.join(2000); 56 | // In above example, main method thread would wait for 2000 ms or the 57 | // end of execution of thread4, whichever is minimum. 58 | 59 | // Thread yield method 60 | // Yield is a static method in the Thread class. It is like a thread 61 | // saying 62 | // " I have enough time in the limelight. Can some other thread run next?". 63 | // A call to yield method changes the state of thread from RUNNING to 64 | // RUNNABLE. However, the scheduler might pick up the same thread to run 65 | // again, especially if it is the thread with highest priority. 66 | // Summary is yield method is a request from a thread to go to Runnable 67 | // state. However, the scheduler can immediately put the thread back to 68 | // RUNNING state. 69 | 70 | // Thread sleep method 71 | // sleep is a static method in Thread class. sleep method can throw a 72 | // InterruptedException. sleep method causes the thread in execution to 73 | // go to sleep for specified number of milliseconds. 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/threads/ThreadWaitAndNotify.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.threads; 2 | 3 | class Calculator extends Thread { 4 | long sum; 5 | 6 | public void run() { 7 | synchronized (this) { 8 | for (int i = 0; i < 1000000; i++) { 9 | sum += i;//499999500000 10 | } 11 | notify(); 12 | } 13 | } 14 | } 15 | 16 | public class ThreadWaitAndNotify { 17 | public static void main(String[] args) { 18 | Calculator thread = new Calculator(); 19 | thread.start(); 20 | synchronized (thread) { 21 | try { 22 | thread.wait(); 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | System.out.println(thread.sum); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/varargs/VariableArgumentExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.varargs; 2 | 3 | //Variable Arguments allow calling a method with different number of parameters. 4 | //Lets look at a basic example: 5 | public class VariableArgumentExamples { 6 | 7 | // int(type) followed ... (three dot's) is syntax of a variable argument. 8 | public int sum(int... numbers) { 9 | // inside the method a variable argument is similar to an array. 10 | // number can be treated as if it is declared as int[] numbers; 11 | int sum = 0; 12 | for (int number : numbers) { 13 | sum += number; 14 | } 15 | return sum; 16 | } 17 | 18 | public static void main(String[] args) { 19 | VariableArgumentExamples example = new VariableArgumentExamples(); 20 | // 3 Arguments 21 | System.out.println(example.sum(1, 4, 5));// 10 22 | // 4 Arguments 23 | System.out.println(example.sum(1, 4, 5, 20));// 30 24 | // 0 Arguments 25 | System.out.println(example.sum());// 0 26 | } 27 | 28 | // Variable Argument should be always the last parameter (or only parameter) 29 | // of a method. 30 | // Below example gives a compilation error 31 | /* 32 | * public int sum(int... numbers, float value) {//COMPILER ERROR } 33 | */ 34 | 35 | // Even a class can be used a variable argument. In the example below, bark 36 | // method 37 | // is overloaded with a variable argument method. 38 | class Animal { 39 | void bark() { 40 | System.out.println("Bark"); 41 | } 42 | 43 | void bark(Animal... animals) { 44 | for (Animal animal : animals) { 45 | animal.bark(); 46 | } 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/variables/PassingVariablesToMethods.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.variables; 2 | 3 | public class PassingVariablesToMethods { 4 | public static void main(String[] args) { 5 | PassingVariablesToMethods ref = new PassingVariablesToMethods(); 6 | 7 | int n = 50; 8 | ref.incrementBy2(n); 9 | System.out.println("Passing primitive " + n);// Passing primitive 50 10 | 11 | Cricketer cric = new Cricketer(); 12 | cric.runs = 50; 13 | ref.modifyCricketer(cric); 14 | System.out.println("Passing reference variable " + cric.runs);// Passing 15 | // reference 16 | // variable 17 | // 150 18 | } 19 | 20 | void incrementBy2(int number) { 21 | number = number + 2; 22 | } 23 | 24 | void modifyCricketer(Cricketer cricketer) { 25 | cricketer.runs += 100; 26 | } 27 | } 28 | 29 | class Cricketer { 30 | String name; 31 | int runs; 32 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/variables/StaticAndMemberVariables.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.variables; 2 | 3 | public class StaticAndMemberVariables { 4 | public static void main(String[] args) { 5 | Actor actor1 = new Actor(); 6 | actor1.name = "ACTOR1"; 7 | // Actor.name //Compiler Error 8 | 9 | // Below statement can be written as actor1.count++ 10 | // But NOT recommended. 11 | Actor.count++; 12 | 13 | Actor actor2 = new Actor(); 14 | actor2.name = "ACTOR2"; 15 | 16 | // Below statement can be written as actor2.count++ 17 | // But NOT recommended. 18 | Actor.count++; 19 | 20 | System.out.println(actor1.name);// ACTOR1 21 | System.out.println(actor2.name);// ACTOR2 22 | 23 | // Next 3 statements refer to same variable 24 | System.out.println(actor1.count);// 2 25 | System.out.println(actor2.count);// 2 26 | System.out.println(Actor.count);// 2 27 | } 28 | } 29 | 30 | class Actor { 31 | // RULE 1 : Member Variables can be accessed 32 | // only through object references 33 | String name; 34 | 35 | // RULE 2:Static Variables can be accessed 36 | // through a.Class Name and b.Object Reference 37 | // It is NOT recommended to use object reference 38 | // to refer to static variables. 39 | static int count; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/variables/VariableInitialization.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.variables; 2 | 3 | //RULE1 :Member/Static variables are alway initialized with 4 | //default values.Default values for numeric types is 0, 5 | //floating point types is 0.0, boolean is false, 6 | //char is '\u0000' and object reference variable is null. 7 | 8 | //RULE2 :Local/block variables are NOT initialized by compiler. 9 | 10 | //RULE3 :If local variables are used before initialization, 11 | //it would result in Compilation Error 12 | 13 | public class VariableInitialization { 14 | public static void main(String[] args) { 15 | Player player = new Player(); 16 | 17 | // score is an int member variable - default 0 18 | System.out.println(player.score);// 0 - RULE1 19 | 20 | // name is a member reference variable - default null 21 | System.out.println(player.name);// null - RULE1 22 | 23 | int local; // not initialized 24 | // System.out.println(local);//COMPILER ERROR! RULE3 25 | 26 | String value1;// not initialized 27 | // System.out.println(value1);//COMPILER ERROR! RULE3 28 | 29 | String value2 = null;// initialized 30 | System.out.println(value2);// null - NO PROBLEM. 31 | } 32 | } 33 | 34 | class Player { 35 | String name; 36 | int score; 37 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/variables/scope/VariablesExample.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.variables.scope; 2 | 3 | public class VariablesExample { 4 | // RULE 1:Static Variable can be used anywhere in the class. 5 | static int staticVariable; 6 | 7 | // RULE 2:Member Variable can be used in any non-static method. 8 | int memberVariable; 9 | 10 | void method1() { 11 | // RULE 3: method1LocalVariable can be used only in method1. 12 | int method1LocalVariable; 13 | 14 | memberVariable = 5;// RULE 2 15 | staticVariable = 5;// RULE 1 16 | 17 | // Some Code 18 | { 19 | // RULE 4:blockVariable can be used only in this block. 20 | int blockVariable; 21 | // Some Code 22 | } 23 | 24 | // blockVariable = 5;//COMPILER ERROR - RULE 4 25 | } 26 | 27 | void method2() { 28 | // method1LocalVariable = 5; //COMPILER ERROR - RULE3 29 | } 30 | 31 | static void staticMethod() { 32 | staticVariable = 5;// RULE 1 33 | // memberVariable = 5; //COMPILER ERROR - RULE 2 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/java/wrapper/WrapperExamples.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.java.wrapper; 2 | 3 | public class WrapperExamples { 4 | 5 | public static void main(String[] args) { 6 | // Boolean,Byte,Character,Double,Float,Integer,Long,Short 7 | // boolean,byte,char ,double,float,int ,long,short 8 | 9 | // Wrapper classes are final 10 | 11 | Integer number = new Integer(55);// int 12 | 13 | Integer value = 10; 14 | value = value + 1; 15 | 16 | Integer number2 = new Integer("55");// String 17 | 18 | Float number3 = new Float(55.0);// double argument 19 | Float number4 = new Float(55.0f);// float argument 20 | Float number5 = new Float("55.0f");// String 21 | 22 | Character c1 = new Character('C');// Only char constructor 23 | // Character c2 = new Character(124);//COMPILER ERROR 24 | 25 | Boolean b = new Boolean(true); 26 | 27 | // "true" "True" "tRUe" - all String Values give True 28 | // Anything else gives false 29 | Boolean b1 = new Boolean("true");// value stored - true 30 | Boolean b2 = new Boolean("True");// value stored - true 31 | Boolean b3 = new Boolean("False");// value stored - false 32 | Boolean b4 = new Boolean("SomeString");// value stored - false 33 | 34 | b = false; 35 | 36 | // Wrapper Objects are immutable (like String) 37 | 38 | int i = 5; 39 | i = 6; 40 | i = 7; 41 | 42 | //Immutability 43 | //Wrapper Classes and String 44 | Integer integer = 6; 45 | integer = 7; 46 | 47 | //######### 48 | //# 6 # 49 | //######### 50 | 51 | //######### 52 | //# 7 # 53 | //######### 54 | 55 | // valueOfMethods 56 | // Provide another way of creating a Wrapper Object 57 | Integer seven = Integer.valueOf("111", 2);// binary 111 is converted to 58 | // 7 59 | 60 | Integer hundred = Integer.valueOf("100", 10);// 100 is stored in 61 | // variable 62 | 63 | // xxxValue methods help in creating primitives 64 | //Integer integer = Integer.valueOf(57); 65 | int primitive = seven.intValue();// 57 66 | float primitiveFloat = seven.floatValue();// 57.0f 67 | 68 | Float floatWrapper = Float.valueOf(57.0f); 69 | int floatToInt = floatWrapper.intValue();// 57 70 | float floatToFloat = floatWrapper.floatValue();// 57.0f 71 | 72 | // parseXxx methods are similar to valueOf but they 73 | // return primitive values 74 | int sevenPrimitive = Integer.parseInt("111", 2);// binary 111 is 75 | // converted to 7 76 | 77 | int hundredPrimitive = Integer.parseInt("100");// 100 is stored in 78 | // variable 79 | 80 | //Creates new Integer object 81 | Integer wrapperEight = new Integer(8); 82 | 83 | // Normal static toString method 84 | System.out.println(Integer.toString(wrapperEight));// String Output : 8 85 | 86 | // Overloaded static toString method : 2nd parameter : radix 87 | System.out.println(Integer.toString(wrapperEight, 2));// String Output : 88 | // 1000 89 | 90 | // static toXxxString methods. Xxx can be Hex,Binary,Octal 91 | System.out.println(Integer.toHexString(wrapperEight));// String Output 92 | // :8 93 | System.out.println(Integer.toBinaryString(wrapperEight));// String 94 | // Output 95 | // :1000 96 | System.out.println(Integer.toOctalString(wrapperEight));// String Output 97 | // :10 98 | 99 | // Auto Boxing 100 | Integer ten = new Integer(10); 101 | ten++;// allowed. Java does had work behing the screen for us 102 | 103 | // Two wrapper objects created using new are not same object 104 | Integer nineA = new Integer(9); 105 | Integer nineB = new Integer(9); 106 | System.out.println(nineA == nineB);// false 107 | System.out.println(nineA.equals(nineB));// true 108 | 109 | // Two wrapper objects created using boxing are same object 110 | Integer nineC = 9; 111 | Integer nineD = 9; 112 | System.out.println(nineC == nineD);// true 113 | System.out.println(nineC.equals(nineD));// true 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/LambdaExpressionsTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import org.junit.Test; 7 | 8 | public class LambdaExpressionsTest { 9 | 10 | @Test 11 | public void sumOfOddNumbers_Usual() { 12 | List numbers = Arrays.asList(1, 3, 4, 6, 2, 7); 13 | 14 | int sum = 0; 15 | 16 | for (int number : numbers) 17 | if (number % 2 != 0) 18 | sum += number; 19 | 20 | assertEquals(11, sum); 21 | } 22 | 23 | //No changes to state 24 | @Test 25 | public void sumOfOddNumbers_FunctionalProgrammingExample() { 26 | 27 | List numbers = Arrays.asList(1, 3, 4, 6, 2, 7); 28 | 29 | int sum = numbers.stream() // Create Stream 30 | .filter(number -> (number % 2 != 0)) // Intermediate Operation 31 | .reduce(0, Integer::sum); // Terminal Operation 32 | 33 | // number -> (number % 2 != 0) => Lambda Expression 34 | // Integer::sum => Method Reference 35 | // What is Functional Interface 36 | 37 | assertEquals(11, sum); 38 | } 39 | 40 | @Test 41 | public void lambdaExpression_predicate() { 42 | List numbers = Arrays.asList(1, 3, 4, 6, 2, 7); 43 | numbers.stream() 44 | .filter((number) -> (number % 2 != 0)) //Predicate 45 | .forEach(number -> System.out.print(number)); //Consumer 46 | // 137 47 | } 48 | 49 | static boolean isOdd(int number) { 50 | return number % 2 != 0; 51 | } 52 | 53 | int i = 1_000_000; 54 | //.map(String::toLowerCase) 55 | //.map(s -> String.toLowerCase(s)) 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/StringVsStringBuffer.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | public class StringVsStringBuffer { 4 | 5 | @Test 6 | public void testWithStringBuffer() { 7 | StringBuffer s3 = new StringBuffer("Value1"); 8 | String s2 = "Value2"; 9 | for (int i = 0; i < 100000; ++i) { 10 | s3.append(s2); 11 | } 12 | System.out.println(s3); 13 | } 14 | 15 | @Test 16 | public void testWithString() { 17 | String s3 = "Value1"; 18 | String s2 = "Value2"; 19 | for (int i = 0; i < 100000; ++i) { 20 | s3 = s3 + s2; 21 | } 22 | System.out.println(s3); 23 | } 24 | 25 | } 26 | --------------------------------------------------------------------------------