diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 13275f1..0000000 --- a/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -### IntelliJ IDEA ### -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ -.kotlin - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ - -### Mac OS ### -.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index ab1f416..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Ignored default folder with query files -/queries/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml -# Editor-based HTTP Client requests -/httpRequests/ diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index e0844bc..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index aa1b35f..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Prime Program.iml b/Prime Program.iml deleted file mode 100644 index c90834f..0000000 --- a/Prime Program.iml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..adb9772 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# JavaTutorials diff --git a/src/Hello.java b/src/Hello.java deleted file mode 100644 index 9d02ab8..0000000 --- a/src/Hello.java +++ /dev/null @@ -1,14 +0,0 @@ - -// In a file, there can be multiple classes but there will be just one public class -// multiple classes in the same Java file can have a main method -// Java does NOT automatically start from the main method of the public class. -// It starts from the class you explicitly tell the JVM to run - -public class Hello { // this is a block - - public static void main (String[] args) { - System.out.println("Hello World!"); - System.out.println(4 + 3); - System.out.println(); - } -} diff --git a/src/Variables.java b/src/Variables.java deleted file mode 100644 index 7547c54..0000000 --- a/src/Variables.java +++ /dev/null @@ -1,29 +0,0 @@ -public class Variables { - public static void main(String[] args) { - - boolean isPassed = true; - long count = 12; - int countInt = (int)count; - - byte marks = 13; - short studentsCount = 1235; - - float pi = 3.14f; - - double secondPi = 3.143213241123; // will print all precision - - float x = 3.143213241123f; // will print till 7 decimal points - - System.out.println(pi); - System.out.println(secondPi); - System.out.println(x); - - char myLetter = 'a'; - System.out.println(myLetter); - - int age = 128; - byte newAge = (byte)age; // explicit typecasting, lossy conversion - - System.out.println(newAge); // -128 -> rotation - } -} diff --git a/src/animals/Animal.java b/src/animals/Animal.java deleted file mode 100644 index f3d8b1e..0000000 --- a/src/animals/Animal.java +++ /dev/null @@ -1,14 +0,0 @@ -package animals; - -public class Animal { - - // protected constructor - protected Animal() { - System.out.println("Animal constructor"); - } - - // protected method - protected void eat () { - System.out.println("Animal is eating"); - } -} diff --git a/src/arrays/BasicsOfArray.java b/src/arrays/BasicsOfArray.java deleted file mode 100644 index da9b0bd..0000000 --- a/src/arrays/BasicsOfArray.java +++ /dev/null @@ -1,35 +0,0 @@ -package arrays; - -public class BasicsOfArray { - public static void main(String[] args) { -// int age[]; // declaration -// age = new int[5]; // allocation - -// int age[] = new int[5]; -// -// age[0] = 5; -// age[1] = 2; -// -// System.out.println(age[0]); -// System.out.println(age[1]); -// System.out.println(age[2]); -// -// System.out.println(age.length); - - -// int marks[] = {98, 12, 45, 12, 65}; -// -// System.out.println(marks[0]); - - - String names[] = {"Rahul", "Prateek", "Mayank", "Ravi"}; - - for(int i = 0; i < names.length; i++) { - System.out.println("Name is " + names[i]); - } - - for (String name: names) { - System.out.println("for each " + name); - } - } -} diff --git a/src/arrays/ProblemOnArrays.java b/src/arrays/ProblemOnArrays.java deleted file mode 100644 index e5b5eeb..0000000 --- a/src/arrays/ProblemOnArrays.java +++ /dev/null @@ -1,16 +0,0 @@ -package arrays; - -public class ProblemOnArrays { - public static void main(String[] args) { - - int numbers[] = {23, 12, 6, 7, 15, 3, 2, 56}; - - int min = Integer.MAX_VALUE; - - for(int num: numbers) { - if(num < min) min = num; - } - - System.out.println(min); - } -} diff --git a/src/basics2/LearnMath.java b/src/basics2/LearnMath.java deleted file mode 100644 index 6b4a666..0000000 --- a/src/basics2/LearnMath.java +++ /dev/null @@ -1,13 +0,0 @@ -package basics2; - -public class LearnMath { - public static void main(String[] args) { - System.out.println(getRandom(10, 20)); - } - - public static int getRandom(int l, int r) { - return l + (int)(Math.random() * (r - l + 1)); - } -} - -// Math.random() -> 0.0 ≤ value < 1.0 diff --git a/src/basics2/Operators.java b/src/basics2/Operators.java deleted file mode 100644 index d5ba6bf..0000000 --- a/src/basics2/Operators.java +++ /dev/null @@ -1,11 +0,0 @@ -package basics2; - -public class Operators { - public static void main(String[] args) { - int a = 12; - int b = 7; - double c = (double)a/b; // typecast at-least one to double - System.out.println(c); - - } -} diff --git a/src/basics2/UserInput.java b/src/basics2/UserInput.java deleted file mode 100644 index 2a4c0eb..0000000 --- a/src/basics2/UserInput.java +++ /dev/null @@ -1,20 +0,0 @@ -package basics2; - -import java.util.Scanner; - -public class UserInput { - public static void main(String[] args) { - - Scanner sc = new Scanner(System.in); -// System.out.println("Enter your age:"); -// int age = sc.nextInt(); -// System.out.println("Your age is " + age); - - float firstNumber = sc.nextFloat(); - long secondNumber = sc.nextLong(); - float result = (firstNumber + secondNumber); - System.out.println(result); - - sc.close(); // garbage collector will remove this since it will be unused - } -} diff --git a/src/conditionalStatements/LearnSwitch.java b/src/conditionalStatements/LearnSwitch.java deleted file mode 100644 index d847a34..0000000 --- a/src/conditionalStatements/LearnSwitch.java +++ /dev/null @@ -1,37 +0,0 @@ -package conditionalStatements; - -import java.util.Scanner; - -public class LearnSwitch { - public static void main(String[] args) { - - Scanner sc = new Scanner(System.in); - System.out.println("Enter the day"); - int day = sc.nextInt(); - - switch (day) { - // day -> primitive data types, String, enum - case 1: case 2: - System.out.println("Today is Sunday"); - System.out.println("Today is Monday"); - break; - case 3: - System.out.println("Today is Tuesday"); - break; - case 4: - System.out.println("Today is Wednesday"); - break; - case 5: - System.out.println("Today is Thursday"); - break; - case 6: - System.out.println("Today is Friday"); - break; - case 7: - System.out.println("Today is Saturday"); - break; - default: - System.out.println("Invalid day"); - } - } -} diff --git a/src/enums/Day.java b/src/enums/Day.java deleted file mode 100644 index d6e73dd..0000000 --- a/src/enums/Day.java +++ /dev/null @@ -1,11 +0,0 @@ -package enums; - - -// at compile time , Day is final class -// we don't wanna extend Day since we are giving fixed set of constants -public enum Day { - - // SUNDAY is a day - // these are final instances of Day Class - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY -} diff --git a/src/enums/LearnEnums.java b/src/enums/LearnEnums.java deleted file mode 100644 index 8cd0749..0000000 --- a/src/enums/LearnEnums.java +++ /dev/null @@ -1,13 +0,0 @@ -package enums; - -public class LearnEnums { - public static void main(String[] args) { - System.out.println(Day.TUESDAY); // TUESDAY - System.out.println(Day.MONDAY); - - Day monday = Day.MONDAY; - int ordinal = monday.ordinal(); - System.out.println(ordinal); // 1 - System.out.println(monday.name()); // MONDAY - } -} diff --git a/src/exceptions/BankAccount.java b/src/exceptions/BankAccount.java deleted file mode 100644 index bb6c16b..0000000 --- a/src/exceptions/BankAccount.java +++ /dev/null @@ -1,16 +0,0 @@ -package exceptions; - -public class BankAccount { - private double balance; - - public BankAccount(double amount) { - this.balance = amount; - } - - public void withdraw(double amount) throws InsufficientFundsException { - if(amount > balance) { - throw new InsufficientFundsException(amount); - } - balance -= amount; - } -} diff --git a/src/exceptions/InsufficientFundsException.java b/src/exceptions/InsufficientFundsException.java deleted file mode 100644 index e622364..0000000 --- a/src/exceptions/InsufficientFundsException.java +++ /dev/null @@ -1,15 +0,0 @@ -package exceptions; - -public class InsufficientFundsException extends Exception { - - private double amount; - - public InsufficientFundsException (double amount) { - super("What do you want ? You don't have money."); - this.amount = amount; - } - - public double getAmount() { - return amount; - } -} diff --git a/src/exceptions/LearnCustomExceptions.java b/src/exceptions/LearnCustomExceptions.java deleted file mode 100644 index a0d5eef..0000000 --- a/src/exceptions/LearnCustomExceptions.java +++ /dev/null @@ -1,12 +0,0 @@ -package exceptions; - -public class LearnCustomExceptions { - public static void main(String[] args) { - BankAccount bankAccount = new BankAccount(10); - try { - bankAccount.withdraw(11); - } catch (InsufficientFundsException e) { - System.out.println(e); - } - } -} diff --git a/src/exceptions/LearnExceptions.java b/src/exceptions/LearnExceptions.java deleted file mode 100644 index 3c6bc34..0000000 --- a/src/exceptions/LearnExceptions.java +++ /dev/null @@ -1,40 +0,0 @@ -package exceptions; - -// Types of errors -// - Syntax error, Logical error, Runtime error - -// Program will crash during run time errors -// so we will handle those exceptions - -// Exception handling is a way to handle the runtime errors so that -// normal flow of application can be maintained - -// Exception is an event that disrupts the normal flow of program, -// It is an object which is thrown at runtime - -public class LearnExceptions { - public static void main(String[] args) { - int numerators[] = {10, 200, 30, 40}; - int denominators[] = {1, 2, 0, 4}; - for(int i = 0; i < 10; i++) { - try { - System.out.println(divide(numerators[i], denominators[i])); - } catch (Exception e) { - System.out.println(e); - } - } - System.out.println("Good job :)"); - } - - public static int divide(int a, int b) { - try { - return a/b; - } catch (ArithmeticException e) { - System.out.println("Arithmetic exception :("); - return -1; - } catch (Exception e) { - System.out.println(e); - return -1; - } - } -} diff --git a/src/exceptions/LearnStackTrace.java b/src/exceptions/LearnStackTrace.java deleted file mode 100644 index 1fcc3ad..0000000 --- a/src/exceptions/LearnStackTrace.java +++ /dev/null @@ -1,87 +0,0 @@ -package exceptions; - -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -class Student { - int id; - - void setId (int id) { - this.id = id; - } -} - -public class LearnStackTrace { - public static void main(String[] args) throws IOException { - try { - level1(); - } catch (Exception o) { -// StackTraceElement stackTrace[] = o.getStackTrace(); -// for(StackTraceElement st: stackTrace) { -// System.out.println(st); -// } - - o.printStackTrace(); - } - - // null-pointer exception - // unchecked exception -> these exceptions are not checked at compile time - Student a = null; - a.setId(123); - - - method2(); - System.out.println("Hello"); - } - - public static void method2() throws FileNotFoundException { - method1(); - } - - public static void method1() throws FileNotFoundException { - // checked exception -> checked at compile time - // either handle this using try catch - // or make it's caller responsible, write "throws Exception" in method in which its present - // FileReader fileReader = new FileReader("a.txt"); - - try { - FileReader fileReader = new FileReader("a.txt"); - } catch (FileNotFoundException e) { - System.out.println("File not found"); - throw new FileNotFoundException("oops!"); - } - } - - // not needed to do that throws etc. here since its unchecked exception - public static void someMethod() { - throw new ArithmeticException(); - } - - public static void level3() { - int[] array = new int[5]; - array[5] = 10; - } - - public static void level2() { - level3(); - } - - public static void level1() { - level2(); - } - - public static int divide (int a, int b) { - try { - return a/b; - } catch (Exception e) { - return -1; - } - finally { - // this will execute, no matter try or catch which is executing - // we can print even when return statements are there in try/catch - System.out.println("Bye"); - } -// System.out.println("Bye"); - } -} diff --git a/src/exceptions/LearningTryWith.java b/src/exceptions/LearningTryWith.java deleted file mode 100644 index 2349a54..0000000 --- a/src/exceptions/LearningTryWith.java +++ /dev/null @@ -1,36 +0,0 @@ -package exceptions; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; - -// BufferedReader is using system resources which needs to be closed -// to make sure its closed, we can use finally block - -public class LearningTryWith { - public static void main(String[] args) { -// BufferedReader reader = null; -// try { -// reader = new BufferedReader(new FileReader("example.txt")); - - // object which will be created inside the parenthesis, will get auto closed - // - only the objects of class which is implementing AutoClosable interface - try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) { - String line; - while((line = reader.readLine()) != null) { - System.out.println(line); - } - } catch (IOException e) { - System.out.println("IOException caught: " + e.getMessage()); - } -// finally { -// try { -// if (reader != null) { -// reader.close(); -// } -// } catch (IOException e) { -// System.out.println("Error closing reader: " + e.getMessage()); -// } -// } - } -} diff --git a/src/learnCollections/LearnArrayList.java b/src/learnCollections/LearnArrayList.java deleted file mode 100644 index 33e9b3a..0000000 --- a/src/learnCollections/LearnArrayList.java +++ /dev/null @@ -1,142 +0,0 @@ -package learnCollections; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/* -1. Unlike a regular array, an ArrayList can grow and shrink as elements are added or removed. - This dynamic resizing is achieved by creating a new array and copying the elements to the new array. - -2. Internally, the ArrayList is implemented as an array of Object references. - When you add elements to an ArrayList, you're essentially storing these elements in this internal array. - -3. When you create an ArrayList, it has an initial capacity (default is 10). - The capacity refers to the size of the internal array that can hold elements before needing to resize. - -4. When we add an element to an ArrayList, the following steps occur: - - Check Capacity: Before adding the new element, ArrayList checks if there is enough space in the internal array (elementData). If the array is full, it needs to be resized. - - Resize if Necessary: If the internal array is full, ArrayList creates a new array with a larger capacity (usually 1.5 times the current capacity) and copies the elements from the old array to the new array. - - Add the Element: The new element is then added to the internal array at the appropriate index, and the size of the ArrayList is incremented. - -5. Resizing the Array: - - Initial Capacity: By default, the initial capacity is 10. This means the internal array can hold 10 elements before it needs to grow. - - Growth Factor: When the internal array is full, a new array is created with a size 1.5 times the old array. This growth factor balances memory efficiency & resizing cost. - - Copying Elements: When resizing occurs, all existing elements are copied from the old array to the new array, which is O(n) operation, where n is the number of elements in the ArrayList. - -6. Removing Elements: - - Check Bounds: The ArrayList first checks if the index is within the valid range. - - Remove the Element: The element is removed, and all elements to the right of the removed element are shifted one position to the left to fill the gap. - - Reduce Size: The size of the ArrayList is decremented by one. - */ - -public class LearnArrayList { - public static void main(String[] args) { - /* - ArrayList list = new ArrayList<>(); // size = 0, capacity = 10 - - ArrayList list2 = new ArrayList<>(1000); // size = 0, capacity = 1000 - - list.add(1); // 0 - list.add(5); // 1 - list.add(80); // 2 - - // remove the element at index 2 - list.remove(2); - - // add 50 at index 2 - list.add(2, 50); - - // replace the element at index 2 with 50 - list.set(2, 50); - - System.out.println(list); // [1, 5, 50] - - - System.out.println(list.get(2)); - System.out.println(list.size()); - - for(int i = 0; i < list.size(); i++) { - System.out.println(list.get(i)); - } - - for(int x: list) { - System.out.println(x); - } - - System.out.println(list.contains(5)); - System.out.println(list.contains(50)); - */ - - List list = new ArrayList<>(); - System.out.println(list.getClass().getName()); // java.util.ArrayList - - - // returns a fixed-size List backed by the specified array, can't add or remove elements from this list, but can modify existing elements - List list1 = Arrays.asList("Monday", "Tuesday"); - System.out.println(list1.getClass().getName()); // java.util.Arrays$ArrayList - list1.set(1, "Wednesday"); // allowed - // list1.add("Thursday"); // throws UnsupportedOperationException - - - String[] array = {"Apple", "Banana", "Cherry"}; - List list2 = Arrays.asList(array); - System.out.println(list2.getClass().getName()); // java.util.Arrays$ArrayList - - List list4 = new ArrayList<>(list2); // creates a new ArrayList with the elements of list2, this list is modifiable - list4.add("Mango"); - System.out.println(list4); - - - List list3 = List.of(1, 2, 3); // return unmodifiable list, can't add, remove or modify elements - // list3.set(1, 33); // throws UnsupportedOperationException - - - - List list5 = new ArrayList<>(); - list5.add(1); - list5.add(2); - list5.add(3); - list5.add(0, 0); - - List list6 = List.of(4, 5, 6, 7, 8, 9); - - list5.addAll(list6); - System.out.println(list5); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - - - - - List list7 = new ArrayList<>(); - list7.add(1); - list7.add(2); - list7.add(3); - - // list7.remove(1); // removes the element at index 1, which is 2 - list7.remove(Integer.valueOf(1)); // removes the object 1, which is at index 0 after the previous removals - System.out.println(list7); // [2, 3] - - - Collections.sort(list7); // sorts the list in natural order - list7.sort(null); // sorts the list in natural order, same as Collections.sort(list7) - - - Object[] array1 = list7.toArray(); - Integer[] array2 = list7.toArray(new Integer[0]); - - - List fruits = new ArrayList<>(); - fruits.add("Apple"); - fruits.add("Apple"); - fruits.add("Banana"); - fruits.add("Cherry"); - fruits.add("Banana"); - fruits.add("Date"); - - fruits.remove("Apple"); // removes the object "Apple", only the first occurrence is removed - - System.out.println(fruits); // [Apple, Banana, Cherry, Banana, Date] - } -} \ No newline at end of file diff --git a/src/learnCollections/LearnComparator.java b/src/learnCollections/LearnComparator.java deleted file mode 100644 index 925506f..0000000 --- a/src/learnCollections/LearnComparator.java +++ /dev/null @@ -1,94 +0,0 @@ -package learnCollections; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -class MyComparator implements Comparator { - - // if we want to get o1 first then o2, then we should return a -ve number - // if we want to get o1 and o2 at the same position, then we should return 0 - // if we want to get o2 first then o1, then we should return a +ve number - @Override - public int compare(Integer o1, Integer o2) { - return o1 - o2; - } -} - -class StringLengthComparator implements Comparator { - - @Override - public int compare(String o1, String o2) { - return o1.length() - o2.length(); - } -} - -class Student { - private String name; - private double gpa; - - public Student(String name, double gpa) { - this.name = name; - this.gpa = gpa; - } - - public String getName() { - return name; - } - - public double getGpa() { - return gpa; - } -} - -public class LearnComparator { - public static void main(String[] args) { - List list = new ArrayList<>(); - list.add(2); - list.add(1); - list.add(3); - - // list.sort(new MyComparator()); - list.sort((a, b) -> a - b); // using lambda expression to sort the list in natural order - System.out.println(list); // [1, 2, 3] - - - List words = Arrays.asList("banana", "apple", "date"); - // words.sort(new StringLengthComparator()); - words.sort((s1, s2) -> s1.length() - s2.length()); // using lambda expression to sort the list based on string length - System.out.println(words); // [date, apple, banana] - - - List students = new ArrayList<>(); - students.add(new Student("Charlie", 3.5)); - students.add(new Student("Bob", 3.7)); - students.add(new Student("Alice", 3.5)); - students.add(new Student("Akshit", 3.9)); - - Comparator comparator = Comparator.comparing(Student::getGpa).reversed().thenComparing(Student::getName); - - students.sort((o1, o2) -> { - if(o2.getGpa() - o1.getGpa() > 0) { - return 1; - } - else if (o2.getGpa() - o1.getGpa() < 0) { - return -1; - } - else { - return o1.getName().compareTo(o2.getName()); - } - }); - - // students.sort(comparator); - - Collections.sort(students, comparator); - - for(Student student : students) { - System.out.println(student.getName() + ": " + student.getGpa()); - } - - } -} diff --git a/src/learnString/LearnString.java b/src/learnString/LearnString.java deleted file mode 100644 index 5c7f861..0000000 --- a/src/learnString/LearnString.java +++ /dev/null @@ -1,62 +0,0 @@ -package learnString; - -import java.util.Scanner; - -public class LearnString { - public static void main(String[] args) { - -// Scanner sc = new Scanner(System.in); -// -// System.out.println("Enter your first name: "); -// String firstName = sc.nextLine(); // will consider whole line -// -// System.out.println("Enter your last name: "); -// String lastName = sc.next(); // will take only the first word before space -// -// System.out.println("Your full name is " + firstName + " " + lastName); -// System.out.println(lastName); - -// int age = 123; -// String stringAge = String.valueOf(age); // to convert int, float etc. to string -// System.out.println(age + 2); // 125 -// System.out.println(stringAge + 2); // 1232 - - -// String sentence = "I love java, java is good"; -// String newSentence = sentence.replace("java", "cpp"); -// -// System.out.println(sentence); // I love java, java is good -// System.out.println(newSentence); // I love cpp, cpp is good - - - String sentence = "I love Java, Java is a good language"; - -// String substring = sentence.substring(2); -// System.out.println(substring); // from index 2 to last -// -// String substring2 = sentence.substring(2, 8); // [2, 8) -// System.out.println(substring2); - -// String words[] = sentence.split(" "); -// for(String word: words) { -// System.out.println(word); -// } - -// String color = "Brown is my fav color!"; -// char letters[] = color.toCharArray(); -// -// for(char letter: letters) { -// System.out.println(letter); -// } - - - String animal = " "; - - if(animal.isEmpty()) { - System.out.println("Empty"); - } else if (animal.isBlank()) { - System.out.println("Blank"); - } - - } -} diff --git a/src/learnString/StringBasics.java b/src/learnString/StringBasics.java deleted file mode 100644 index d6da333..0000000 --- a/src/learnString/StringBasics.java +++ /dev/null @@ -1,36 +0,0 @@ -package learnString; - -public class StringBasics { - public static void main(String[] args) { - String name = "Rahul"; - String sameName = "Rahul"; - String newName = new String("Rahul"); - - System.out.println(name); - System.out.println(newName); - - if(name == sameName) { - System.out.println("Both are same"); - } - - if(name == newName) { - System.out.println("Both are same"); - } else { - System.out.println("Both are not same"); - } - - // while using ==, it's not the object values which gets checked, - // it's references which gets checked - - // in primitive data types, == checks the values even if the values are getting stored separately - // in non-primitive, == checks if references are pointing to same address or not - - // so the question is how do we check values - // .equals() function - // .equalsIgnoreCase() -> ignores the case of the string and then compare - - if(name.equals(newName)) { - System.out.println("name and newName have same values"); - } - } -} diff --git a/src/loops/WhileLoops.java b/src/loops/WhileLoops.java deleted file mode 100644 index cb26235..0000000 --- a/src/loops/WhileLoops.java +++ /dev/null @@ -1,15 +0,0 @@ -package loops; - -import java.util.Scanner; - -public class WhileLoops { - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - boolean hasLearnt = false; - while(!hasLearnt) { - System.out.println("Went to school, tried to learn"); - System.out.println("Have you understood?"); - hasLearnt = sc.nextBoolean(); - } - } -} diff --git a/src/multithreading/LearnMultithreading.java b/src/multithreading/LearnMultithreading.java deleted file mode 100644 index 706c406..0000000 --- a/src/multithreading/LearnMultithreading.java +++ /dev/null @@ -1,129 +0,0 @@ -package multithreading; - -/* -1. CPU -> Brain of the computer. - Responsible for executing instructions from programs. - Performs basic arithmetic, logic, control, and I/O operations specified by instructions. - -2. Core -> An individual processing unit within a CPU. - Modern CPUs can have multiple cores, allowing them to perform multiple tasks simultaneously. - -3. A quad-core processor has four cores, allowing it to perform 4 tasks simultaneously. - Example: One core may handle a web browser, another music player, another a download manager, - and another a background system update. - -4. Program -> A set of instructions written in a programming language that tells the computer - how to perform a specific task. - Example: MS Word is a program used to create and edit documents. - -5. Process -> An instance of a program that is being executed. - When a program runs, the OS creates a process to manage its execution. - Example: When we open MS Word, it becomes a process in the OS. - -6. Thread -> The smallest unit of execution within a process. - A process can have multiple threads which share the same resources but run independently. - Example: A browser like Chrome uses multiple threads for different tabs. - -7. Multitasking -> Allows an OS to run multiple processes simultaneously. - - In single-core CPUs, this is achieved using time-sharing. - - In multi-core CPUs, true parallel execution happens. - - The OS scheduler manages and balances tasks for efficient performance. - Example: Browsing the internet while listening to music and downloading a file. - -8. Multitasking utilizes the CPU and its cores efficiently. - The OS can assign different tasks to different cores, which is more efficient - than executing everything on a single core. - -9. Multithreading -> Ability to execute multiple threads within a single process concurrently. - Example: A browser uses multiple threads for rendering pages, running JavaScript, - and handling user input. - -10. Multithreading improves multitasking by dividing tasks into smaller threads. - These threads can execute simultaneously, improving CPU utilization. - -11. In a single-core system: - - Threads and processes are managed using time slicing and context switching - to simulate parallel execution. - - In a multi-core system: - - Threads and processes can run truly in parallel on different cores. - - The OS scheduler distributes tasks efficiently across cores. - -12. Time Slicing - - Definition: Time Slicing divides CPU time into small intervals called time slices or quanta. - - Function: The OS Scheduler allocates these time slices to different processes and threads, ensuring each gets a fair share of CPU time. - - Purpose: This prevents any single process or thread from monopolizing CPU, improving responsiveness & enabling concurrent execution. - -13. Context Switching - - Definition: Process of saving the state of a currently running process/thread and loading the state of next one to be executed. - - Function: When a process/thread's time slice expires, OS scheduler performs a context switch to move the CPU's focus to another process/thread. - - Purpose: Allows multiple processes/threads to share CPU, giving appearance of simultaneous execution on single-core CPU or improving parallelism on multi-core CPUs. - -14. Multitasking can be achieved through multithreading where each task is divided into threads that are managed concurrently. - While multitasking typically refers to thr running of multiple apps, multithreading is more granular dealing with multiple threads within the same app/process - -15. Multitasking operates at the level of processes, which are the OS's primary units of execution. - Multithreading operates at the level of threads, which are smaller units within a process. - -16. Multitasking involves managing resources b/w completely separate programs, which may have independent memory spaces and system resources. - Multithreading involves managing resources within a single program, where threads share the same memory & resources - -17. Multitasking allows us to run multiple applications simultaneously, improving productivity & system utilization. - Multithreading allows a single app to perform multiple tasks at same time, improving app performance & responsiveness. -*/ - -/* -1. In Java, Multithreading is the concurrent execution of two/more threads to maximize the utilization of CPU. - Java's multithreading capabilities are part of the java.lang package, making it easy to implement concurrent execution. - -2. In a single-core env, Java's Multithreading is managed by JVM & OS, which switch b/w threads to give illusion of concurrency. - The threads share the single core, and time-slicing is used to manage thread execution - -3. In a multi-core env, Java's multithreading can take full advantage of the available cores. - The JVM can distribute threads across multiple cores, allowing true parallel execution of threads - -4. A thread is a lightweight process, the smallest unit of processing. - Java supports multithreading through its - - java.lang.Thread class - - java.lang.Runnable interface - -5. When a Java program starts, one thread begins running immediately, which is called main thread. - This thread is responsible for executing the main method of a program. - -6. To create a new thread in Java, you can either - - extend the Thread class - OR - - implement the Runnable interface - */ - -/* -1. By extending the Thread class: - - A new class World is created that extends Thread - - The run method is overridden to define the code that constitutes the new thread. - - start method is called to initiate the new thread - -2. By implementing Runnable Interface - - A new class World2 is created that implements Runnable - - The run method is overridden to define the code that constitutes the new thread. - - A Thread object is created by passing an instance of World2 - - start method is called on the Thread object to initiate the new thread. - -In both cases, the run method contains the code that will be executed in the new thread - */ - - -public class LearnMultithreading { - public static void main(String[] args) { - -// World world = new World(); -// world.start(); - - World2 world2 = new World2(); - Thread t1 = new Thread(world2); - t1.start(); - - for(; ;) { - System.out.println("Hello"); - } - } -} diff --git a/src/multithreading/MyThread.java b/src/multithreading/MyThread.java deleted file mode 100644 index 43ce5b5..0000000 --- a/src/multithreading/MyThread.java +++ /dev/null @@ -1,28 +0,0 @@ -package multithreading; - -public class MyThread extends Thread{ - @Override - public void run() { - System.out.println("RUNNING"); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] args) throws InterruptedException { - MyThread t1 = new MyThread(); - System.out.println(t1.getState()); // NEW - t1.start(); - System.out.println(t1.getState()); // RUNNABLE -// System.out.println(Thread.currentThread().getState()); // RUNNABLE - - Thread.sleep(100); - System.out.println(t1.getState()); // TIMED_WAITING - - // caller method (main) will wait for t1 to get finished - t1.join(); - System.out.println(t1.getState()); // TERMINATED - } -} diff --git a/src/multithreading/ThreadClassMethods.java b/src/multithreading/ThreadClassMethods.java deleted file mode 100644 index a5a9cb4..0000000 --- a/src/multithreading/ThreadClassMethods.java +++ /dev/null @@ -1,111 +0,0 @@ -package multithreading; - -public class ThreadClassMethods extends Thread{ - - // naming of thread -// public ThreadClassMethods(String name) { -// super(name); -// } - - @Override - public void run() { - /* setPriority() - for(int i = 0; i < 5; i++) { - String a = ""; - for(int j = 0; j < 10000; j++) { - a += "a"; - } - System.out.println(Thread.currentThread().getName() + " - Priority: " + Thread.currentThread().getPriority() + " - count: " + i); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - */ - - - /* interrupt() - try { - Thread.sleep(1000); - System.out.println("Thread is running..."); - } catch (InterruptedException e) { - System.out.println("Thread interrupted: " + e); - } - */ - - - /* yield() - for(int i = 0; i < 5; i++) { - System.out.println(Thread.currentThread().getName() + " is running"); - Thread.yield(); - } - */ - - - while(true) { - System.out.println("Hello World!"); - } - } - - public static void main(String[] args) throws InterruptedException { - /* setPriority() - ThreadClassMethods l = new ThreadClassMethods("Low Priority Thread"); - ThreadClassMethods m = new ThreadClassMethods("Medium Priority Thread"); - ThreadClassMethods h = new ThreadClassMethods("High Priority Thread"); - - l.setPriority(Thread.MIN_PRIORITY); - m.setPriority(Thread.NORM_PRIORITY); - h.setPriority(Thread.MAX_PRIORITY); - - // 1. start() -> when it's called, JVM will execute run method - l.start(); - m.start(); - h.start(); - */ - - - - /* interrupt() - ThreadClassMethods t1 = new ThreadClassMethods(); - t1.start(); - t1.interrupt(); // Thread interrupted: java.lang.InterruptedException: sleep interrupted - - */ - - - - /* yield() - ThreadClassMethods t1 = new ThreadClassMethods(); - ThreadClassMethods t2 = new ThreadClassMethods(); - - t1.start(); - t2.start(); - */ - - - - ThreadClassMethods myThread = new ThreadClassMethods(); - myThread.setDaemon(true); - ThreadClassMethods t1 = new ThreadClassMethods(); - t1.start(); // now JVM will wait for t1, since that's user thread - myThread.start(); - System.out.println("Main done"); - - // main thread's work is completed, but JVM is waiting for the myThread to get completed - // hence by setting that thread as daemon, now that is background threa, JVM will not wait for that and will exit - } -} - -// start, run, sleep, join, setPriority, interrupt, yield, setDaemon - -/* -setPriority -> not strict, will just give hint to JVM and OS Scheduler -interrupt -> if the thread is waiting/ sleeping, interrupt it -yield -> A hint to the scheduler that the current thread is willing to yield its current use of a processor. - The scheduler is free to ignore this hint. - -USER THREADS -> which are actually doing work -DAEMON THREADS -> which runs in background, like Garbage collector - JVM will not wait for these threads -*/ \ No newline at end of file diff --git a/src/multithreading/ThreadLifeCycle.java b/src/multithreading/ThreadLifeCycle.java deleted file mode 100644 index 0bf2704..0000000 --- a/src/multithreading/ThreadLifeCycle.java +++ /dev/null @@ -1,21 +0,0 @@ -package multithreading; - -/* -The lifecycle of a thread in Java consists of several state, which a thread can move through during its execution - -- New: Created but not started -- Runnable: After the start method is called, the thread becomes runnable. - It's ready to run & is waiting for CPU time. -- Running: When it's executing. -- Blocked/Waiting: When it's waiting for a resource or for another thread to perform an action. -- Terminated: When it has finished executing. - */ - -public class ThreadLifeCycle { - public static void main(String[] args) { - - World t1 = new World(); // NEW - t1.start(); // RUNNABLE - System.out.println(); - } -} diff --git a/src/multithreading/World.java b/src/multithreading/World.java deleted file mode 100644 index 1a11946..0000000 --- a/src/multithreading/World.java +++ /dev/null @@ -1,10 +0,0 @@ -package multithreading; - -public class World extends Thread { - @Override - public void run() { - for(; ;) { - System.out.println(Thread.currentThread().getName()); - } - } -} diff --git a/src/multithreading/World2.java b/src/multithreading/World2.java deleted file mode 100644 index 40b9699..0000000 --- a/src/multithreading/World2.java +++ /dev/null @@ -1,10 +0,0 @@ -package multithreading; - -public class World2 implements Runnable { - @Override - public void run() { - for(;;) { - System.out.println("World"); - } - } -} diff --git a/src/multithreading/locks/BankAccount.java b/src/multithreading/locks/BankAccount.java deleted file mode 100644 index d612f3f..0000000 --- a/src/multithreading/locks/BankAccount.java +++ /dev/null @@ -1,83 +0,0 @@ -package multithreading.locks; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/* -ReentrantLock is a class which implements Lock interface - -tryLock(): Acquires the lock only if it's free at time of invocation. - Acquires the lock if it's available and returns immediately with the value true. - If the lock is not available then this method will return immediately with the value false. - -lock(): same as synchronized, will wait for the lock to be available - - -If an InterruptedException or a ThreadDeath error is not handled properly, the information that the thread was interrupted will be lost. -Handling this exception means either to re-throw it or manually re-interrupt the current thread by calling Thread.interrupt(). -Simply logging the exception is not sufficient and counts as ignoring it. -B/w the moment the exception is caught and handled, is the right time to perform cleanup operations on the method's state, if needed. - -What is the potential impact? -- Failing to interrupt the thread (or to re-throw) risks delaying the thread shutdown and losing the information that the thread was interrupted - probably without finishing its task. - */ - -public class BankAccount { - private int balance = 100; - - private final Lock lock = new ReentrantLock(); - - /* - jab hmne esko synchronized kr diya to agar t1 access krrha to t2 access nhi kr payega - chahe hm kitna bhi sleep krwa rhe ho - jb tk t1 esko poora khtm nhi kr lega including this sleep, tab tk t2 nhi aayega - */ -// public synchronized void withdraw(int amount) { - - public void withdraw(int amount) { - System.out.println(Thread.currentThread().getName() + " attempting to withdraw " + amount); - /* - if(balance >= amount) { - System.out.println(Thread.currentThread().getName() + " proceeding with withdrawal"); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - - } - balance -= amount; - System.out.println(Thread.currentThread().getName() + " completed withdrawal. Remaining balance: " + balance); - } else { - System.out.println(Thread.currentThread().getName() + " insufficient balance"); - } - */ - - try { - // Acquires the lock if it's free within the given waiting time & the current thread hasn't been interrupted - if(lock.tryLock(1000, TimeUnit.MILLISECONDS)) { - if(balance >= amount) { - try { - System.out.println(Thread.currentThread().getName() + " proceeding with withdrawal"); - Thread.sleep(3000); // Simulate time taken to process the withdrawal - balance -= amount; - System.out.println(Thread.currentThread().getName() + " completed withdrawal. Remaining balance: " + balance); - } catch (Exception e) { - Thread.currentThread().interrupt(); - } finally { - lock.unlock(); - } - } else { - System.out.println(Thread.currentThread().getName() + " insufficient balance"); - } - } else { - System.out.println(Thread.currentThread().getName() + " couldn't acquire the lock, will try again later"); - } - } catch (Exception e) { - Thread.currentThread().interrupt(); - } - if(Thread.currentThread().isInterrupted()) { - System.out.println(""); - } - } -} diff --git a/src/multithreading/locks/FairnessLockExample.java b/src/multithreading/locks/FairnessLockExample.java deleted file mode 100644 index afd7ae5..0000000 --- a/src/multithreading/locks/FairnessLockExample.java +++ /dev/null @@ -1,60 +0,0 @@ -package multithreading.locks; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/* -locking me fairness hoti hai, order determine hoti hai ki kon se thread ko lock milega, kyuki multiple thread wants lock, -to sbse phle kisko milega fir kisko milega, to wo order jo hai usko fairness kehte - -jo pehle aaya hai usko pehle lock milega - -Fair Lock: Jo pehle aya, usko lock milega (FIFO) -Unfair Lock: Jo fast hai wo ghus jata hai, chahe baad me aaya ho - -let's say 20 threads hai and unme se ek to lock mil hi nhi rha hai baaki sb race krrhe hai, (starvation) -this doesn't happen in fairness, mauka sbko milega, order to FIFO rhega hi but mauka sbko milega - -Disadvantages of synchronization: -- synchronized me fairness ki guarantee nhi hai -- indefinitely blocking hoti hai -- interruptibility bhi nhi hai -- synchronized ko pta hi nhi hai kon sa read / write hai to wo to poora block krke rkhega - */ - -public class FairnessLockExample { -// private final Lock unfairLock = new ReentrantLock(); - private final Lock lock = new ReentrantLock(true); - - public void accessResource() { - lock.lock(); - try { - System.out.println(Thread.currentThread().getName() + " acquired the lock"); - Thread.sleep(1000); - } catch(InterruptedException e) { - Thread.currentThread().interrupt(); - } finally { - System.out.println(Thread.currentThread().getName() + " released the lock"); - lock.unlock(); - } - } - - public static void main(String[] args) { - FairnessLockExample example = new FairnessLockExample(); - - Runnable task = new Runnable() { - @Override - public void run() { - example.accessResource(); - } - }; - - Thread thread1 = new Thread(task, "Thread 1"); - Thread thread2 = new Thread(task, "Thread 2"); - Thread thread3 = new Thread(task, "Thread 3"); - - thread1.start(); - thread2.start(); - thread3.start(); - } -} diff --git a/src/multithreading/locks/Main.java b/src/multithreading/locks/Main.java deleted file mode 100644 index 02e9b0a..0000000 --- a/src/multithreading/locks/Main.java +++ /dev/null @@ -1,25 +0,0 @@ -package multithreading.locks; - -/* -1. Intrinsic: These are built into every object in Java. You don't see them, but they're there. - When you use a synchronized keyword, you're using these automatic locks. - -2. Explicit: These are more advanced locks you can control yourself using the Lock class from java.util.concurrent.locks. - You explicitly say when to lock & unlock, giving you more control over how & when people can write in the notebook. - */ - -public class Main { - public static void main(String[] args) { - BankAccount sbi = new BankAccount(); - Runnable task = new Runnable() { - @Override - public void run() { - sbi.withdraw(50); - } - }; - Thread t1 = new Thread(task, "Thread 1"); - Thread t2 = new Thread(task, "Thread 2"); - t1.start(); - t2.start(); - } -} diff --git a/src/multithreading/locks/ReentrantExample.java b/src/multithreading/locks/ReentrantExample.java deleted file mode 100644 index 90bbc75..0000000 --- a/src/multithreading/locks/ReentrantExample.java +++ /dev/null @@ -1,53 +0,0 @@ -package multithreading.locks; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class ReentrantExample { - private final Lock lock = new ReentrantLock(); - - public void outerMethod() { - - // 1. lock acquired by main thread -// lock.lock(); // t1 ne lock le liya and innerMethod me ghus gya, and t2 wait krrha indefinitely for t1 to get finished, esko bolte hai BLOCKED/WAITING state, agar aap .lock() use krrhe to us waiting thread t2 ko interrupt nhi kr paynge - try { - lock.lockInterruptibly(); // lekin agar aapko usko interrupt krna hai, to lock ko interruptible hona bhi to chahie, to interruptexception throw hoga, to esko try/catch me krna pdega - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - try { - // 2. - System.out.println("Outer method"); - innerMethod(); - } finally { - lock.unlock(); - } - } - - public void innerMethod() { - /* - 3. jo lock phle se lock kr-rkha hai hmne usko fir se mai lock krne ka try krrha hu - mai apna hi wait krrha hu - deadlock - - But since the lock is Reentrant - yani same thread holds it, to fir se whi thread acquire kr lega lock - - - Jb hm Reentrant lock use krte hai to ek count maintain hota hai, ki lock kitni baar acquire kiya gya hai - each lock call must be paired with an unlock call - lock tb release hoga jb hr ek lock match ho jayega uske unlock se - */ - - lock.lock(); - try { - System.out.println("Inner method"); - } finally { - lock.unlock(); - } - } - - public static void main(String[] args) { - ReentrantExample example = new ReentrantExample(); - example.outerMethod(); - } -} diff --git a/src/multithreading/synchronization/Counter.java b/src/multithreading/synchronization/Counter.java deleted file mode 100644 index a3ef7dd..0000000 --- a/src/multithreading/synchronization/Counter.java +++ /dev/null @@ -1,20 +0,0 @@ -package multithreading.synchronization; - -public class Counter { - private int count = 0; - -// public synchronized void increment() { - public void increment() { - - // this ka matlab hai ki yha ek instance ki baat krrhe hai - // ek instance jispe increment method call ho rha hai - // agar usko multiple threads access krrhe hai to ek baar me ek hi thread access kr payega - synchronized (this) { - count++; - } - } - - public int getCount() { - return count; - } -} diff --git a/src/multithreading/synchronization/MyThread.java b/src/multithreading/synchronization/MyThread.java deleted file mode 100644 index b9a74f9..0000000 --- a/src/multithreading/synchronization/MyThread.java +++ /dev/null @@ -1,16 +0,0 @@ -package multithreading.synchronization; - -public class MyThread extends Thread{ - private Counter counter; - - public MyThread(Counter counter) { - this.counter = counter; - } - - @Override - public void run() { - for(int i = 0; i < 1000; i++) { - counter.increment(); - } - } -} diff --git a/src/multithreading/synchronization/Test.java b/src/multithreading/synchronization/Test.java deleted file mode 100644 index f47c9fc..0000000 --- a/src/multithreading/synchronization/Test.java +++ /dev/null @@ -1,19 +0,0 @@ -package multithreading.synchronization; - -public class Test { - public static void main(String[] args) { - Counter counter = new Counter(); - MyThread t1 = new MyThread(counter); - MyThread t2 = new MyThread(counter); - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (Exception e) { - - } - System.out.println(counter.getCount()); - } -} diff --git a/src/oops1/MainClass.java b/src/oops1/MainClass.java deleted file mode 100644 index 2d5fea5..0000000 --- a/src/oops1/MainClass.java +++ /dev/null @@ -1,32 +0,0 @@ -package oops1; - -// only one class with the name of the file, will be public, rest will be non-public -// code execution will only start from main method of public class - -public class MainClass { - public static void main(String[] args) { - - Dog d1 = new Dog(); - d1.name = "Tommy"; - d1.bark(); - d1.walk(); - - Dog d2 = new Dog(); - d2.name = "Leo"; - d2.walk(); - } -} - -class Dog { - String name; - int age; - String color; - - void walk () { - System.out.println(name + " is walking"); - } - - void bark() { - System.out.println(name + " is barking"); - } -} diff --git a/src/oops2/Car.java b/src/oops2/Car.java deleted file mode 100644 index c3337f7..0000000 --- a/src/oops2/Car.java +++ /dev/null @@ -1,35 +0,0 @@ -package oops2; - -// properties and behavior both will get inherited on extending - -// When a class extends another class, it inherits all non-private fields and methods of the parent class, but constructors and private members are not inherited. -// Static methods are not truly inherited, they are hidden. -public class Car extends Vehicle { - - String color; - - void start() { - System.out.println(this); // oops2.Car@5b2133b1 - System.out.println(this.model + " Car is starting"); - } - - Car () { - super(4); - System.out.println("Car is being created"); - } - - public static void main(String[] args) { - - Car obj = new Car(); - obj.wheelsCount = 4; - obj.model = "I10"; - obj.color = "Red"; - obj.start(); - } -} - -// every class in java extends Object Class -// when in multiple inheritance lets say A <-- B <-- C -// if C.start(), then it will check it in C first, if not present then B else A -// multilevel is possible, multiple inheritance is not - diff --git a/src/oops2/MethodHiding.java b/src/oops2/MethodHiding.java deleted file mode 100644 index 7d4a8a6..0000000 --- a/src/oops2/MethodHiding.java +++ /dev/null @@ -1,54 +0,0 @@ -package oops2; - -// static variables and methods get inherited, -// but they do not behave like normal overridden methods - -// static variables is accessible in child - -class Parent { - static int x = 20; - - static void staticMethod() { - System.out.println("Parent static"); - } - - void instanceMethod() { - System.out.println("Parent instance"); - } -} - -// static methods are accessible in child -class Child extends Parent { - -} - -// static methods can't be overridden -// since overriding is run time polymorphism -// static methods belongs to class , not object -// static binding happens at compile time -class Child2 extends Parent { - static void staticMethod() { - System.out.println("Child2 static"); - } - - @Override - void instanceMethod() { - System.out.println("Child2 instance"); - } -} - -public class MethodHiding { - public static void main(String[] args) { - System.out.println(Child.x); // 20 - Child.staticMethod(); // Parent static - - Parent p = new Child2(); - p.staticMethod(); // Parent static - p.instanceMethod(); // Child2 instance - - // because static methods are resolved using ref type, not object type - // Ref type = parent - // so Parent.show() - // this is method hiding - } -} diff --git a/src/oops2/SingletonUsage.java b/src/oops2/SingletonUsage.java deleted file mode 100644 index 3d04dff..0000000 --- a/src/oops2/SingletonUsage.java +++ /dev/null @@ -1,26 +0,0 @@ -package oops2; - -class Singleton { - private static Singleton instance; - - private Singleton() { - System.out.println("Singleton object created"); - } - - public static Singleton getInstance () { - if(instance == null) { - instance = new Singleton(); - } - return instance; - } -} - -public class SingletonUsage { - public static void main(String[] args) { - - Singleton s1 = Singleton.getInstance(); - Singleton s2 = Singleton.getInstance(); - - System.out.println(s1 == s2); - } -} \ No newline at end of file diff --git a/src/oops2/Vehicle.java b/src/oops2/Vehicle.java deleted file mode 100644 index 8f3ee9e..0000000 --- a/src/oops2/Vehicle.java +++ /dev/null @@ -1,57 +0,0 @@ -package oops2; - -public class Vehicle { - - int wheelsCount; - String model; - - void start() { - System.out.println("Vehicle is starting"); - } - - Vehicle() { - System.out.println("Creating a vehicle instance"); - } - - Vehicle(int wheelsCount) { - this.wheelsCount = wheelsCount; - System.out.println("Creating vehicle with wheels"); - } - -// a constructor can't have a return type -// if you add a return type, java treats it as normal method, not a constructor -// void Vehicle() { -// System.out.println("bye"); -// } - -// valid constructor -// by default access modifier of a constructor is package-private (also called default access) -// Vehicle() { -// System.out.println("This is constructor"); -// } - - -// constructors can have access modifier -> public, protected, default, private - -// public constructor -> object can be created from anywhere -// public Vehicle() {} - -// default (package-private) -> object can be created only within same package -// Vehicle() {} - -// protected constructor -// ✔ Same package -// ✔ Subclasses in other packages -// ❌ Other classes -// protected Vehicle() {} - -// private constructor -// ❌ Cannot create object using new from outside -// Used for: Singleton pattern, Utility classes, Factory methods -// private Vehicle() {} - -// Constructor can't be final, static or abstract -// why not final -> cannot override (constructors are not inherited) -// why not static -> constructor belongs to object not a class -// why not abstract -> constructor must have a body -} diff --git a/src/oops3/learnPackage/MainClass.java b/src/oops3/learnPackage/MainClass.java deleted file mode 100644 index fcf7902..0000000 --- a/src/oops3/learnPackage/MainClass.java +++ /dev/null @@ -1,11 +0,0 @@ -package oops3.learnPackage; - -public class MainClass { - public static void main(String[] args) { - - Teacher obj = new Teacher(); - obj.teachingClass = 12; - // obj.id = 123; not accessible even in same package, since its private - obj.degree = "PHD"; // accessible in same package since its default - } -} diff --git a/src/oops3/learnPackage/Teacher.java b/src/oops3/learnPackage/Teacher.java deleted file mode 100644 index a603d73..0000000 --- a/src/oops3/learnPackage/Teacher.java +++ /dev/null @@ -1,19 +0,0 @@ -package oops3.learnPackage; - -public class Teacher { - - public int teachingClass; - - private int id; - - String degree; // default or package private - - protected int studentsCount; - - public static void main(String[] args) { - Teacher obj = new Teacher(); - obj.teachingClass = 12; - obj.id = 123; - } -} - diff --git a/src/oops3/package2/MainInPackage2.java b/src/oops3/package2/MainInPackage2.java deleted file mode 100644 index 0150a20..0000000 --- a/src/oops3/package2/MainInPackage2.java +++ /dev/null @@ -1,18 +0,0 @@ -package oops3.package2; - -import oops3.learnPackage.Teacher; - -public class MainInPackage2 extends Teacher { - - public static void main(String[] args) { - Teacher obj = new Teacher(); -// obj.id = 123; // not accessible since its private - obj.teachingClass = 4; -// obj.degree = "PHD"; // can't use outside package, since its default - - MainInPackage2 mainInPackage2 = new MainInPackage2(); - mainInPackage2.studentsCount = 100; - // accessible, since it's accessing the protected field via inheritance, even if it's in diff package - - } -} diff --git a/src/oops4/InnerClasses.java b/src/oops4/InnerClasses.java deleted file mode 100644 index df6d017..0000000 --- a/src/oops4/InnerClasses.java +++ /dev/null @@ -1,82 +0,0 @@ -package oops4; - -public class InnerClasses { - - public static void main(String[] args) { - // Member Inner Class - Outer outer = new Outer(); - Outer.Inner inner = outer.new Inner(); - inner.show(); - - // Static Nested Class - Outer1.Inner obj = new Outer1.Inner(); - obj.show(); - - // Local Inner Class - Outer2 outer2 = new Outer2(); - outer2.display(); - } -} - -// Member Inner Class -// 1. Has access to all members of outer class (even private) -// 2. Cannot have static members (except constants), since inner class depends on instance and static belongs to class level -// 3. Needs an outer class object - -class Outer { - int x = 10; - - class Inner { - - void show() { - System.out.println(x); - } - } -} - - -// Static Nested Class -// a static class inside another class - -class Outer1 { - static int x = 10; - - static class Inner { - void show() { - System.out.println(x); - } - } -} - -//🔑 Key differences vs Inner Class -// Feature Inner Class Static Nested Class -// Needs outer object ✅ Yes ❌ No -// Access non-static members ✅ Yes ❌ No -// Access static members ✅ Yes ✅ Yes -// Can have static members ❌ No ✅ Yes -// Memory efficient ❌ Less ✅ More - - -// Local Inner Class - A class declared inside a method -// scope is limited to the method -// can't be public, private, protected or static -// can access effectively final local variables - -class Outer2 { - void display() { - int x = 19; - // x = 20; // not effectively final - - class LocalInner { - void show() { - System.out.println("Hello"); - - // can access only effectively final local variables - System.out.println(x); - } - } - - LocalInner obj = new LocalInner(); - obj.show(); - } -} diff --git a/src/oops4/LearnAnonymousClasses.java b/src/oops4/LearnAnonymousClasses.java deleted file mode 100644 index 304b693..0000000 --- a/src/oops4/LearnAnonymousClasses.java +++ /dev/null @@ -1,50 +0,0 @@ -package oops4; - - -// No constructor -// No name -// Used for short implementations -// Replaced mostly by Lambda expressions - -public class LearnAnonymousClasses { - - // this obj is of the anonymous subclass - OuterClass obj = new OuterClass() { - void sing() { - - } - - public void outerMethod() { - - } - }; - - // object of anonymous class implementing SuperInterface - SuperInterface obj2 = new SuperInterface() { - @Override - public void interfaceMethod() { - - } - }; - - // creation of object of anonymous class implementing functional interface - // using lambda functions / expressions - SuperInterface obj3 = () -> { - - }; - -} - - -class OuterClass { - - public void outerMethod() { - - } -} - -@FunctionalInterface -interface SuperInterface { - - void interfaceMethod(); -} \ No newline at end of file diff --git a/src/oops4/LearnInterfaces.java b/src/oops4/LearnInterfaces.java deleted file mode 100644 index 7cefa1e..0000000 --- a/src/oops4/LearnInterfaces.java +++ /dev/null @@ -1,67 +0,0 @@ -package oops4; - -public class LearnInterfaces { - - public static void main(String[] args) { - Monkey monkey = new Monkey(); - monkey.eats(); - monkey.drinks(); - -// Animal.LEGS = 5; // can't do, since its final - - System.out.println(Animal.LEGS); - } -} - -interface Pet { - - void sings(); - void drinks(); -} - -interface Animal { - - // can define only those fields inside interface which are public, static and final - -// public static final int LEGS=4; - int LEGS=4; - - // Modifier 'abstract' is redundant for interface methods - // since methods are by default abstract for interfaces - - // public is also redundant since it has to be accessible inside the inheriting class - // so keep it default -// public abstract void eats(); - - void eats(); - void drinks(); - - // default implementation -> can be overridden - default void walk() { - System.out.println("Animal is walking"); - } -} - -// a class can implement 2 interfaces even if they have same methods -// because implementing class will have to provide the implementation of that function -// so it will not create a deadlock like which interface's function to call - -// but this is not possible when extending 2 classes, i.e. multiple inheritance is not possible - -class Monkey implements Animal, Pet { - - - @Override - public void eats() { - System.out.println("Monkey is eating"); - } - - @Override - public void sings() { - System.out.println("Monkey is singing"); - } - - public void drinks() { - System.out.println("Monkey is drinking"); - } -} \ No newline at end of file diff --git a/src/pets/Dog.java b/src/pets/Dog.java deleted file mode 100644 index 0f9305f..0000000 --- a/src/pets/Dog.java +++ /dev/null @@ -1,61 +0,0 @@ -package pets; - -import animals.Animal; - -public class Dog extends Animal { - - public Dog() { - // If you do not explicitly write super() or this() inside a subclass constructor, - // Java automatically inserts super(). - super(); // ✅ protected constructor accessible via inheritance - System.out.println("Dog constructor"); - } - - public void test() { - - // ✅ protected method via inheritance - eat(); - this.eat(); - - // ❌ NOT allowed: protected constructor via object creation - // Animal a1 = new Animal(); - - // ❌ NOT allowed: protected method via superclass reference - // Animal a2 = this; - // a2.eat(); - - // ✅ allowed: access via subclass reference - Dog d = this; - d.eat(); - } - - public static void main(String[] args) { - Dog dog = new Dog(); - dog.test(); - -// Output: -// Animal constructor -// Dog constructor -// Animal is eating -// Animal is eating -// Animal is eating - -// *V.IMP* -> In a different package, protected members are accessible only through inheritance, -// not through a superclass reference or object creation. - -// 1. Java does NOT match constructors by parameter count automatically -// Having a 1-param constructor in subclass does NOT mean Java will call the 1-param constructor in superclass. - -// 2. Constructor chaining must be explicit when parameters exist -// 3. super(param) must be the first statement - -// TLDR: If a superclass has only parameterized constructors, the subclass must explicitly call super(arguments); -// otherwise, compilation fails. - -// If the superclass has a no-argument constructor, Java automatically inserts super() -// even if the subclass constructor has parameters. - -// A constructor may contain EXACTLY ONE constructor call (this() OR super()), -// and it must be the FIRST line. - } -}