From ec51217bbaed887a28deff68bb46c05858e67cd8 Mon Sep 17 00:00:00 2001 From: Krunal Patel Date: Mon, 13 Mar 2023 18:38:34 +0530 Subject: [PATCH] Java basics Class & Object Abstract class, Inheritance Operators Method Constructor OOP concepts (Inheritance, Polymorphism, Abstraction, Encapsulation) Control flow loops Decision Condition Java practice Fix line breaks --- .../demo/javaPractice/CollectionsDemo.java | 79 ++++++++++ .../krunal/demo/javaPractice/Conditions.java | 44 ++++++ .../javaPractice/DifferentObjCreation.java | 59 ++++++++ .../demo/javaPractice/DummyPackage.java | 8 + .../com/krunal/demo/javaPractice/Enums.java | 78 ++++++++++ .../demo/javaPractice/ExceptionHandling.java | 142 ++++++++++++++++++ .../com/krunal/demo/javaPractice/Lambda.java | 70 +++++++++ .../demo/javaPractice/NumGuessGame.java | 37 +++++ .../com/krunal/demo/javaPractice/OopDemo.java | 76 ++++++++++ .../krunal/demo/javaPractice/Operators.java | 71 +++++++++ 10 files changed, 664 insertions(+) create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/CollectionsDemo.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/Conditions.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/DifferentObjCreation.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/DummyPackage.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/Enums.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/ExceptionHandling.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/Lambda.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/NumGuessGame.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/OopDemo.java create mode 100644 Demo/app/src/main/java/com/krunal/demo/javaPractice/Operators.java diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/CollectionsDemo.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/CollectionsDemo.java new file mode 100644 index 0000000..26d5624 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/CollectionsDemo.java @@ -0,0 +1,79 @@ +package com.krunal.demo.javaPractice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CollectionsDemo { + public static void main(String[] args) { + // List + List numList = Arrays.asList(1, 7, 5, 2, 0); +// numList.add(5); UnsupportedOperationException + numList.set(1, 9); + System.out.println(numList.getClass().getName() + " " + numList); + + final List newNumList = new LinkedList<>(numList); + newNumList.remove(0); + System.out.println(newNumList.getClass().getName() + " " + newNumList); + newNumList.clear(); + newNumList.add(3); + newNumList.add(2); + newNumList.add(4); + newNumList.add(0); + + System.out.println("4 at" + newNumList.indexOf(4)); + Iterator iterator = newNumList.iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next() + " "); + } + System.out.println(); + + for (int n: numList) { + System.out.print(n + " "); + } + System.out.println(); + + newNumList.addAll(numList); + + // Map - calculate occurrence + Map map = new HashMap<>(); + Character[] arr = {'a', 'b', 'a', 'c', 'd', 'c', 'c', 'c'}; + Arrays.stream(arr).forEach(ch -> { + if (map.containsKey(ch)) { + map.put(ch, map.get(ch) + 1); + } else { + map.put(ch, 1); + } + }); + System.out.println(map); + map.remove('c'); + map.remove('b', 4); + System.out.println("keys: " + map.keySet()); + System.out.println("values: " + map.values()); + + System.out.println(map.getOrDefault('h', 0)); + map.computeIfAbsent('h', character -> { + System.out.println(character + " is absent"); + return 6; + }); + map.putIfAbsent('h', 5); + + // Set + Set set = new HashSet<>(Arrays.asList(1, 2, 2, 3, 1, 0)); + System.out.println(set); + + // Collection methods + System.out.println("max: " + Collections.min(newNumList)); + Collections.shuffle(newNumList); + System.out.println(newNumList); + Collections.sort(newNumList); + System.out.println(newNumList); + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/Conditions.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Conditions.java new file mode 100644 index 0000000..cc39aa9 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Conditions.java @@ -0,0 +1,44 @@ +package com.krunal.demo.javaPractice; + +import java.util.Random; + +public class Conditions { + + public static void main(String[] args) { + if (false) { + if (4 >= 5) { + System.out.println("4 > 5"); + } else { + System.out.println("5 > 4"); + } + } else if (new Random().nextBoolean()) { + System.out.println("In else-if"); + } else { + System.out.println("In else"); + } + + isVowel('a'); + isVowel('E'); + isVowel('0'); + } + + public static void isVowel(char ch) { + switch (ch) { + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': + System.out.println("small case"); + case 'A': + case 'E': + case 'I': + case 'O': + case 'U': + System.out.println("Vowel"); + break; + default: + System.out.println("Constant"); + } + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/DifferentObjCreation.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/DifferentObjCreation.java new file mode 100644 index 0000000..f6c52a0 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/DifferentObjCreation.java @@ -0,0 +1,59 @@ +package com.krunal.demo.javaPractice; + +import androidx.annotation.NonNull; + +import java.io.FileInputStream; +import java.io.ObjectInputStream; +import java.io.Serializable; + +public class DifferentObjCreation { + + public static void main(String[] args) { + System.out.println("Hello World"); + createObjs(); + } + + public static void createObjs() { + Demo2 obj = new Demo2(); + + try { + obj = (Demo2) Class.forName("com.krunal.demo.javaPractice.Demo2").newInstance(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + + try { + Demo2 obj2 = (Demo2) obj.clone(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + + try { + ObjectInputStream is = new ObjectInputStream(new FileInputStream("demo2")); + Demo2 obj4 = (Demo2) is.readObject(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} + +class Demo2 implements Serializable, Cloneable { + + static { + System.out.println("Class initialized"); + } + + { + System.out.println("Class obj initialized"); + } + + Demo2() { + System.out.println("Demo2 constructor"); + } + + @NonNull + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/DummyPackage.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/DummyPackage.java new file mode 100644 index 0000000..d147825 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/DummyPackage.java @@ -0,0 +1,8 @@ +package com.krunal.demo.notExist.javaPractice; + +public class DummyPackage { + + public DummyPackage() { + System.out.println("Dummy Package constructed"); + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/Enums.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Enums.java new file mode 100644 index 0000000..d3fc1c9 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Enums.java @@ -0,0 +1,78 @@ +package com.krunal.demo.javaPractice; + +public class Enums { + + public static void main(String[] args) { + Signal sig = Signal.valueOf("GREEN"); + checkSignal(sig); + sig = sig.next(); + checkSignal(sig); + sig = sig.next(); + checkSignal(sig); + } + + public static void checkSignal(Signal sig) { + switch (sig) { + case GREEN: + System.out.println("\u001B[32m" + sig.action); + break; + case YELLOW: + System.out.println("\u001B[33m" + sig.action); + break; + case RED: + System.out.println("\u001B[31m" + sig.action); + break; + } + } +} + +enum Signal { + + GREEN("Go"), + YELLOW("Slow down"), + RED("Stop"); + + final String action; + + Signal(String action) { + this.action = action; + } + + public Signal next() { + switch (this) { + case GREEN: + return YELLOW; + case YELLOW: + return RED; + case RED: + return GREEN; + } + return null; + } +} + +// Internal implementation of enum + +class SignalClass { + + public static final SignalClass GREEN = new SignalClass("Go"); + public static final SignalClass YELLOW = new SignalClass("Slow down"); + public static final SignalClass RED = new SignalClass("Stop"); + + final String action; + + SignalClass(String action) { + this.action = action; + } + + public SignalClass next() { + if (GREEN.equals(this)) { + return YELLOW; + } else if (YELLOW.equals(this)) { + return RED; + } else if (RED.equals(this)) { + return GREEN; + } + return null; + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/ExceptionHandling.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/ExceptionHandling.java new file mode 100644 index 0000000..87eb555 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/ExceptionHandling.java @@ -0,0 +1,142 @@ +package com.krunal.demo.javaPractice; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.UUID; + +public class ExceptionHandling { + + public static void main(String[] args) { + Repository repo = Repository.getInstance(); + + try { + repo.login("KrunalPate1", "Krunal@123"); + } catch (UserNotFoundException e) { + e.printStackTrace(); + } catch (EmptyPasswordException | InvalidPasswordException e) { + System.out.println(e.getMessage()); + } + + try { + String token = repo.login("Kruna1Pate1", "Krunal@123").toString(); + System.out.println("Your unique id is " + token); + } catch (Exception e) { + System.out.println(e.getMessage()); + } finally { + System.out.println("Login attempt"); + } + + // Try with resource + try { + URL url = new URL("https://jsonplaceholder.typicode.com/todos/1"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + String line = reader.readLine(); + while (line != null) { + System.out.println(line); + line = reader.readLine(); + } + } finally { + System.out.println("Done reading"); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} + +class Repository { + + private final UserDetails userDetails; + private static Repository repository; + + public static Repository getInstance() { + if (repository == null) { + Repository.UserDetails userDetails = new Repository.UserDetails("Kruna1Pate1"); + userDetails.setPassword("Krunal@123"); + repository = new Repository(userDetails); + } + return repository; + } + + private Repository(UserDetails userDetails) { + this.userDetails = userDetails; + } + + static class UserDetails { + + private final String user; + private String password; + + UserDetails(String user) { + this.user = user; + } + + public String getUser() { + return user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + } + + public UUID login(String user, String password) throws EmptyPasswordException, InvalidPasswordException, UserNotFoundException { + validate(password); + if (!userDetails.user.equals(user)) { + throw new UserNotFoundException("Invalid user"); + } + System.out.println("Login successful"); + return UUID.randomUUID(); + } + + public boolean validate(String password) throws InvalidPasswordException, EmptyPasswordException { + if (password.isEmpty()) { + throw new EmptyPasswordException("Password is empty"); + } else if (!userDetails.password.equals(password)) { + throw new InvalidPasswordException("Password does not match"); + } else { + System.out.println("valid password"); + return true; + } + } +} + +class UserNotFoundException extends Exception { + + public UserNotFoundException() { + super(); + } + + public UserNotFoundException(String message) { + super(message); + } +} + +class InvalidPasswordException extends Exception { + + public InvalidPasswordException() { + super(); + } + + public InvalidPasswordException(String message) { + super(message); + } +} + +class EmptyPasswordException extends Exception { + + public EmptyPasswordException() { + super(); + } + + public EmptyPasswordException(String message) { + super(message); + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/Lambda.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Lambda.java new file mode 100644 index 0000000..21fef13 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Lambda.java @@ -0,0 +1,70 @@ +package com.krunal.demo.javaPractice; + +import java.util.Arrays; +import java.util.Random; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.IntConsumer; +import java.util.function.Predicate; + +public class Lambda { + + public static void main(String[] args) { + // Body with a single expression + Runnable greet = () -> System.out.println("Hello World!!"); + greet.run(); + + // Return without parameter + GetValue piValue = () -> 3.14; + System.out.println(piValue.value()); + + // Body with parameter + Consumer greetName = (String name) -> System.out.println("Hello " + name); + Consumer greetName2 = System.out::println; + greetName.accept("Krunal"); + greetName2.accept("Hello Krunal!!"); + + // Accept and return modified data + Function toInt = (String num) -> Integer.parseInt(num); + Function toInt2 = Integer::parseInt; + System.out.println(toInt.apply("5")); + System.out.println(toInt2.apply("5")); + + // Check condition + Predicate isEven = (Integer n) -> n % 2 == 0; + Integer[] numArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Arrays.stream(numArr).filter(isEven).forEach(System.out::print); + System.out.println(); + + new Controller(); + } +} + +@FunctionalInterface +interface GetValue { + + T value(); +} + +class Util { + + Function capitalize = (String str) -> str.toUpperCase(); + Runnable contentBreak = () -> System.out.println("**************************"); + + public void randomValue(GetValue getValue) { + System.out.println("value: " + getValue.value()); + } +} + +class Controller { + + final Util util = new Util(); + String name = "Demogorgon"; + + Controller() { + System.out.println(util.capitalize.apply(name)); + GetValue random = () -> new Random().nextInt(); + util.randomValue(random); + util.contentBreak.run(); + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/NumGuessGame.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/NumGuessGame.java new file mode 100644 index 0000000..29917dd --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/NumGuessGame.java @@ -0,0 +1,37 @@ +package com.krunal.demo.javaPractice; + +import java.util.Random; +import java.util.Scanner; + +public class NumGuessGame { + + public static void main(String[] args) { + new Game().start(); + } +} + +class Game { + + private final Scanner sc = new Scanner(System.in); + private final int num = new Random().nextInt(100); + private int tries = 0; + + public void start() { + guess: + while (true) { + System.out.print("Guess no: "); + int guess = sc.nextInt(); + + if (guess == num) { + System.out.println("Guessed correct in " + tries + " try" ); + break guess; + } else if (guess < num) { + System.out.println("Try larger number"); + tries++; + } else { + System.out.println("Try smaller number"); + tries++; + } + } + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/OopDemo.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/OopDemo.java new file mode 100644 index 0000000..cf2a3b7 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/OopDemo.java @@ -0,0 +1,76 @@ +package com.krunal.demo.javaPractice; + +import com.krunal.demo.notExist.javaPractice.DummyPackage; + +public class OopDemo { + + public static void main(String[] args) { + Animal animal = new Animal() { + @Override + public boolean canProtect() { + return false; + } + }; + System.out.println(animal.speak()); + + animal = new Dog(); + ((Dog) animal).setName("Tommy"); + System.out.println(animal.speak()); + + animal = new Lion(); + System.out.println(animal.speak()); + + DummyPackage dp = new DummyPackage(); + } +} + +interface Animal { + + boolean canProtect(); + default String speak() { + System.out.println("Default method"); + return "Hello world!!"; + } +} + +abstract class Domestic implements Animal { + + abstract public String getName(); + + @Override + public String speak() { + return "Hello!!"; + } +} + +class Dog extends Domestic { + + private String name = ""; + + @Override + public boolean canProtect() { + return true; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} + +class Lion implements Animal { + + @Override + public boolean canProtect() { + return false; + } + + @Override + public String speak() { + return "Roar"; + } +} diff --git a/Demo/app/src/main/java/com/krunal/demo/javaPractice/Operators.java b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Operators.java new file mode 100644 index 0000000..7f34409 --- /dev/null +++ b/Demo/app/src/main/java/com/krunal/demo/javaPractice/Operators.java @@ -0,0 +1,71 @@ +package com.krunal.demo.javaPractice; + +import java.util.Map; + +import kotlin.Triple; + +public class Operators { + + public static void main(String[] args) { + int n1 = 5; + int n2 = 10; + + // Arithmetic Operators + int sum = n1 + n2; + System.out.println("sum: " + sum); + int sub = n1 - n2; + System.out.println("sub: " + sub); + int mul = n1 * n2; + System.out.println("mul: " + mul); + float div = ((float) n1) / n2; + System.out.println("div: " + div); + int mod = n2-- % ++n1; + System.out.println("div: " + mod); + + // Relational Operators + if (n1 == n2) { + System.out.println("Both are same"); + } else if (n1 > n2) { + System.out.println("N1 is larger"); + } else if (n1 <= n2) { + System.out.println("N1 is same or smaller"); + } + + // Logical Operators + if (echo(true) || echo(false)) { + System.out.println("Inside ||"); + } + + if (!echo(true) && echo(false)) { + System.out.println("Inside &&"); + } + + // Assignment Operators + int num = n1; + System.out.println("num: " + num); + num += num; + System.out.println("num: " + num); + num /= --num; + System.out.println("num: " + num); + + // Ternary Operator + System.out.println(n1 > n2 ? "n1" : "n2"); + + // instance of + String s = "Hello"; + if (s instanceof String) { + System.out.println("It's String"); + } + + // Round off error + double a = 1.2; + double b = 1.1; + double c = a - b; + System.out.println(c); + } + + static boolean echo(boolean flag) { + System.out.println("flag is " + flag); + return flag; + } +}