###### tags: `JAVA` # Java Beginner Part-1 ## Data Type ```java=1 int age = 3123456789; // syntax error , the value is too large long age = 3123456789L; // long type need to add L after the value float price = 10.99F; // need to add F convert double to float char letter = 'A'; boolean isEligible = false; String message = "Hello World" + "!!"; ``` ### String `String` are reference type & class String aren't value types since they can be huge, and need to be stored on the heap. So the first vocabulary of String needs to be capitalizing And it has many method can be used String are immutable, we cannot change them if you want to edit strings, java will create a new string object for you the below are the method of String ```java=1 message.endsWith("!!") message.length() message.indexOf("w") // find the index of the character message.replace("!","*") // replace ! with * message.toLowerCase() message.toUpperCase() message.trim() // ignore the beginning and ending space String special = "Hello\"WALL\""; // use `\` can print the `"` in string String path = "c:\\Windows\\..."; // get the correct path ``` ### Array **Single Dimension** `Arrays.toString(arrayName)` ```java=1 int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; System.out.println(numbers); // print random value that we can't understand System.out.println(Arrays.toString(numbers)); // correct print ``` **Multi-dimension** `Arrays.deepToString(arrayName)` ```java=1 int[][] two_dim = new int[2][3]; // 2 rows 3 columns two_dim[0][0] = 1; // set a value System.out.println(Arrays.toString(two_dim)); // got random value because this is multi-dimension System.out.println(Arrays.deepToString(two_dim)); // deepToString can separate the multi-dimension array ``` **Array Initialize Value** ```java=1 int[] nums = {2,3,5,1,4}; int[][] two_dim_val = {{1,2,3},{4,5,6}}; ``` **Array Methods** ```java=1 int[] nums = {2,3,5,1,4}; // initialize array Arrays.sort(nums); // sort the array System.out.println(nums.length); // array size ``` **Array Sort** ```java=1 int[] x = {-1,5,3,9,11,10,2}; Arrays.sort(x,1,5); // sort index 1 to index 4 for(int i:x){ System.out.println(i); } ``` ### Constant `final` in variable means it cannot be changed ```java=1 final float PI = 3.14F; ``` ## Type casting Assign a value of one primitive data type to another **If the data types are compatible, then it will convert automatically** * widening casting (automatically) From smaller data type to larger data type size For example: byte -> short -> char -> int -> long -> float ->double **If not compatible then those type need to be converted explicitly** * narrowing casting (manually) From larger data type to smaller data type size For example: reverse the above example <font color="#f00">Why we need to convert data type manually?</font> Because if convert the data type automatically will make data lossing **For example:** double -> int ==> 12.3 -> 12 the value which. behind the decimal point will disappear automatically and we didn't know. **Implicit casting** ```java=1 short w = 1; // two bytes int u = w + 2; // four bytes System.out.println(u); ``` **Explicit casting** ```java=1 double a = 1.1; int b = a + 2; // casting error, we need to manually casting this two data types String s = "1"; // int y = int(s) + 2; // this will get error , because string and integer are not compatible int y = Integer.parseInt(s) + 2; ``` ## Math class In the Math class the methods all use static keywords, it means we don't need to care about Instance, we can use those method by Math class **For example:** ```java=1 int i = Math.round(1.1F); // 四捨五入 rounding int j = (int)Math.ceil(1.1F); // 2 (無條件進入) // Math.ceil output type is double, so we need to convert data type ``` **How to make a random number using Math class?** ```java=1 double rand = Math.random(); // between 0 and 1 int randi = (int)Math.round(Math.random() * 100); // make random number from 0 to 100 ``` **<font color="#f00">notice: use both random method and roud method together the type will change to long, so we need to do a type casting</font>** ## Format number ```java=1 NumberFormat currency = NumberFormat.getCurrencyInstance(); // currency 貨幣 String format = currency.format(1234567.891); // $1,234,567.89 NumberFormat percent = NumberFormat.getPercentInstance(); // percentage 百分比 String percent_format = percent.format(0.1); // 10% ``` ## Primitive Type & Reference Type * primitive type * don't need to allocate memory * don't have any method * store simple value * store on the stack * reference type * need to allocate memory * have many methods * store complex object * store on the heap **For example:** ```java=1 // primitive type byte x = 1; byte y = x; x = 2; System.out.println(y); // 1 // reference type Point point1 = new Point(1,1); // point(1,1) store in addr:100 // x points to addr:100 and store a value called 100 Point point2 = point1; // point2 point to point1's object address // so the value of point2 will as same as point1, and they store the address, not point(1,1) // this is the property of reference type point1.x = 2; System.out.println(point2); // java.awt.Point[x=2,y=1] ``` ## Parameter & Argument **Parameter** Default function parameters , if no value or undefined is passed. 建立函式時,預設帶入的變數 example: **Argument** an actual value pass to function 呼叫函式時,傳給該函式參數的值 **For example:** `.replace(target,replacement)` ```java=1 str.replace("!","*"); ``` parameter : target , replacement argument : ! , * ## Print 輸出 ```java=1 System.out.println("Hello"); // print and change new line ``` ## Scanner 輸入 Scanner are class(類別) `next()` if you input over one token, means your input contain space, it will only show the first token ```java=1 Scanner scanner = new Scanner(System.in); // creat a object byte a = scanner.nextByte(); // this method can only parse byte value String b = scanner.next() // only can read a token String c = scanner.nextLine().trim(); // read a line and ignore the beginning and ending space ``` ## final & static keywords * static * 靜態 擁有唯一值,不管 new 多少 object 值都會一樣(在同一個記憶體位址) * 可以透過類別直接去存取該變數,不需要 new object * static method : cannot be used in Instance because it is class method (don't care about instance) * general method : it only can be used with instance (no instance no used this method) * final * 可以用來宣告類別、函數、變數 * 類別:當宣告在類別上時,該類別就無法被繼承 * 函數:繼承他的子類別無法覆寫(override) * 變數:是一個常數,無法被修改 ## Operators **Comparison Operator** ```java=1 int x = 1; int y = 1; System.out.println(x == y); // true ``` **Logic** ```java=1 int temperature = 25; boolean isWarm = temperature > 20 && temperature < 30; System.out.println(isWarm); // true boolean hasHighIncome = true; boolean hasGoodCredit = true; boolean hasCriminalRecord = false; boolean isEligible = (hasGoodCredit || hasHighIncome) && !hasCriminalRecord; System.out.println(isEligible); // true ``` ## Arithmetic Expression ```java=1 double result = (double)10 / (double)3; int x = 1; x++; // ++x has the same result // 2 System.out.println(x); // 2 int p = 1; int q = p++; // first do q = p then do p+1 System.out.println(p); // 2 System.out.println(q); // 1 int p1 = 1; int q1 = ++p1; // first do p1+1 then do q1 = p1 System.out.println(p1); // 2 System.out.println(q1); // 2 ```