Untitled
unknown
plain_text
a year ago
14 kB
6
Indexable
1. errorlesscode 1.1. debug Techniques.java public class Techniques { public static void main(String[] args) { // logging(); assertions(); } /* Logging/'printf' debugging -> insert additional print statements in the code. */ public static void logging() { int count = 0; for (int i = 0; i < 10; i++) { count++; System.out.printf("count = %d\n", count); } } /* Khi xuat hien loi thi se ngat chuong trinh Chi su dung assertions trong testing/debugging va khong su dung trong production code */ public static void assertions() { // int count = 0; // for (int i = 0; i < 10; i++) { // count++; // assert (count < 9) : "Count >= 10"; // System.out.printf("count = %d\n", count); // } Cat casper = new Cat("Casper", -1); } /* Debugger la cong cu can thiep vao qua trinh thuc thi chuong trinh thong thuong, cho phep lay thong tin runtime va kiem tra cac tinh huong khac nhau de chuan doan loi */ public static void attachingADebugger() { } } class Cat { String name; int age; public Cat(String name, int age) { assert (age >= 0) : "Invalid age"; this.name = name; this.age = age; } } ######################################### 1.2. exceptions 1.2.1. CustomExceptions.java import java.util.Scanner; public class CustomExceptions { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int a = scn.nextInt(); try { Square square = new Square(a); } catch (SquareSizeException sq) { System.out.println(sq.getMessage()); } } } class Square { int a; public Square(int a) throws SquareSizeException { if (a > 0) this.a = a; else throw new SquareSizeException("zero or negative size"); //put you code here } } class SquareSizeException extends Exception { public SquareSizeException(String message) { super(message); } } ######################################### 1.2.2. ExceptionDemo.java import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { NumberFormatException(); } public static void NumberFormatException() { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); if (input.matches("\\d+")) { // it checks if the input line contains only digits int number = Integer.parseInt(input); // an exception is possible here! System.out.println(number + 1); } else { System.out.println("Incorrect number: " + input); } } public static void ArithmeticException() { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); if (b == 0) { System.out.println("Division by zero!"); } else { System.out.println(a / b); // an exception is possible here! } System.out.println("finished"); } } ################################ 1.2.3. Main.java import java.util.Scanner; /* * Khi chuong trinh co loi(do programmer, input,...), Java se dung va tao mot thong bao loi * Thuat ngu ky thuat (technical term): Java se dua ra mot ngoai le (exception) - throw an error * * There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc: */ public class Main { public static void main(String[] args) { try { int[] myNumbers = { 1, 2, 3 }; System.out.println(myNumbers[2]); } catch (Exception e) { System.out.println("Something went wrong!"); } // deposit(0); int a = 10; int b = 0; try { if (b == 0) { throw new ArithmeticException(); } System.out.println(a / b); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } Scanner sc = new Scanner(System.in); int n = 0; try { System.out.println("Nhap so nguyen n: "); n = sc.nextInt(); System.out.println("Nhap du lieu dung!"); } catch (Exception e) { System.out.println("Nhap du lieu khong dung!"); } finally { //du khong bi loi hay bi loi thi van thuc hien cau lenh nay System.out.println("Finally!"); } // neu nhap sai n thi nhung cau lenh duoi se khong duoc thuc thi -> dung // exception System.out.println("Gia tri nhap la: " + n); System.out.println("Ket thuc chuong trinh."); } public static void deposit(long amount) { if (amount <= 0) { throw new IllegalArgumentException("Incorrect sum " + amount); } if (amount >= 100_000_000L) { throw new IllegalArgumentException("Too large amount"); } System.out.println(amount); } } ################################# 1.2.4. NullPointerException.java import java.util.Objects; public class NullPointerException { public static void main(String[] args) { // String str = null; // if (str.equals("abc")) { // it throws an NPE // System.out.println("The same"); // } // if ("abc".equals(str)) { // no NPE here // System.out.println("The same"); // } String s1 = null; String s2 = null; if (Objects.equals(s1, s2)) { // no NPE here System.out.println("Strings are the same"); } int x = 0; switch (x) { case 0 : System.out.println(0); case 1 : System.out.println(1); break; default: System.out.println("Other"); } } } //class MyClass{ // String name; // int age; // // public MyClass(String name, int age) { // this.name = name; // this.age = age; // } // // public String getName() { // return name; // } //} ############################## 2. internals 2.1. jvm 2.2. reflection 2.2.1. Basics.java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /* Reflection is a powerful feature in Java that allows a programmer to examine or modify the structure of a class at runtime. Java Reflection is implemented by the java.lang.reflect package. Although java.lang.reflect package includes many interfaces, classes, and exceptions, there are only four classes that you need to know at this level: Field: you can use it to get and modify name, value, datatype and access modifier of a variable. Method: you can use it to get and modify name, return type, parameter types, access modifier, and exception type of a method. Constructor: you can use it to get and modify name, parameter types and access modifier of a constructor. Modifier: you can use it to get information about a particular access modifier. */ public class Basics { /* You can't just achieve reflection only with the Reflect package that we've mentioned above. The Reflect package can give you information about a field, method or constructor of a class, but first you have to take the field list, method list, and constructor list. This is possible with the java.lang.Class class and its static forName() method. When you pass the name of any class to the forName() method, it returns a Class object that includes information about this class. */ public static void main(String[] args) { javaLangClass(); Class integerClass = Integer.class; } public static void javaLangClass() { try { Class<?> student = Class.forName("javacore.internals.reflection.Student"); Class<?> superclass = student.getSuperclass(); System.out.println("Super Class "); // each of these methods returns an array of objects from java.lang.reflect classes. // getConstructors(), getFields() and getMethods() return only public constructors, fields and methods from the class represented by the Class object. These methods also return inherited public fields and methods from superclasses. // getDeclaredConstructors(), getDeclaredFields(), getDeclaredMethods() return all the constructors, fields and methods from the class represented by the Class object. These methods don't return inherited fields and methods from superclasses. Constructor<?>[] declaredConstructors = student.getDeclaredConstructors(); Constructor<?>[] constructors = student.getConstructors(); for (Constructor dc : declaredConstructors) { System.out.println("Declared Constructor " + dc.getName()); } for (Constructor dc : constructors) { System.out.println("Constructor " + dc.getName()); } Field[] declaredFields = student.getDeclaredFields(); Field[] fields = student.getFields(); for (Field df : declaredFields) { System.out.println("Declared Field " + df.getName()); } for (Field f : fields) { System.out.println("Field " + f.getName()); } Method[] declaredMethods = student.getDeclaredMethods(); Method[] methods = student.getMethods(); for (Method dm : declaredMethods) { System.out.println("Declared Method " + dm.getName()); } for (Method m : methods) { System.out.println("Method " + m.getName()); } int modifiers = student.getModifiers(); System.out.println(modifiers); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } class Student { public String firstName; public String lastName; public int age; protected String phoneNumber; private String accountNumber; Student(){ System.out.println("This is default Constructor"); } public Student(String firstName, String lastName){ this.firstName= firstName; this.lastName= lastName; System.out.println("This is public Constructor"); } private String sanitizeAccountNumber(String accountNumber){ System.out.println("This is a private method to sanitize account number"); //code to sanitize accountNumber goes here. return accountNumber; } public void setAccountNumber(String accountNumber){ accountNumber = sanitizeAccountNumber(accountNumber); this.accountNumber = accountNumber; } } ################################ 2.2.2. Exercise.java public class Exercise { public static void main(String[] args) { Exercise exercise = new Exercise(); System.out.println(exercise.getObjectClassName(exercise)); // javacore.internals.reflection.Exercise } public int getNumberOfFieldsClassDeclares(Class<?> clazz) { // Add implementation here return clazz.getDeclaredFields().length; } public String getObjectClassName(Object object) { // Add implementation here return object.getClass().getName(); } } class BankAccount { protected String number; protected Long balance; public BankAccount(String number, Long balance) { this.number = number; this.balance = balance; } } class CheckingAccount extends BankAccount { public double fee; public CheckingAccount(String number, Long balance, double fee) { super(number, balance); this.fee = fee; } } class SavingsAccount extends BankAccount { public double interestRate; public SavingsAccount(String number, Long balance, double interestRate) { super(number, balance); this.interestRate = interestRate; } } ################################### 2.2.3. RetrievingClassInstances.java public class RetrievingClassInstances { public static void main(String[] args) { // The .class syntax Class stringClass = String.class; System.out.println(stringClass); Class intClass = int.class; System.out.println(intClass); Class voidClass = void.class; System.out.println(voidClass); // Retrieve Class from an object instance Class instanceClass = "abc".getClass(); // Retrieve Class with a given name try { Class forName = Class.forName("java.lang.String"); // The variable floatArrayClass will contain the Class corresponding to a one-dimensional array of primitive type float (the same as float[].class) Class floatArrayClass = Class.forName("[F"); System.out.println(floatArrayClass); // The variable objectArrayClass in its turn will contain the Class corresponding to a two-dimensional array of Object // Note, that there should be a semicolon ; after an array of any objects. Class objectArrayClass = Class.forName("[[Ljava.lang.Object;"); System.out.println(objectArrayClass); // This method can also be used to retrieve Class objects for array classes. } catch (ClassNotFoundException e) { e.printStackTrace(); } // Methods that Return Classes String.class.getSuperclass(); String.class.getClasses(); String.class.getDeclaredClasses(); System.out.println(Object.class.getSuperclass()); } }
Editor is loading...
Leave a Comment