2019-06-07 java learning diary

Array to String

 1 public static void main(String[] args) {
 2         int[] arr = {54,542,231,3,21};
 3         System.out.println(array2String(arr));
 4     }
 5     public static String array2String(int[] arr) {
 6         StringBuffer sb = new StringBuffer();
 7         sb.append("[");
 8         for (int i = 0; i < arr.length; i++) {
 9             if (i == arr.length - 1) {
10                 sb.append(arr[i]).append("]");
11             } else {
12                 sb.append(arr[i]).append(", ");
13             }
14         }
15         return sb.toString();
16     }

 

 

Reverse keyboard input string 

 1 import java.util.Scanner;
 2 
 3 public class test5 {
 4 
 5     public static void main(String[] args) {
 6         Scanner sc = new Scanner(System.in);
 7         String line = sc.nextLine();
 8         System.out.println(rev2String(line));
 9     }
10     
11     public static String rev2String(String line) {
12         StringBuffer sb = new StringBuffer(line);
13         sb.reverse();
14         return sb.toString();
15         
16     }
17 }

 

 

The difference between StringBuffer and StringBuilder

StringBuffer is jbk1.0 version is thread-safe, low efficiency

StringBuilder is jdk1.5 version is incomplete thread safe, efficient

 The difference between String and StringBuffer and StringBuilder of

String is an immutable sequence of characters

StringBuffer, StringBuilder is mutable sequence of characters

1    / *     formal parameter problem
 2       * String passed as a parameter
 . 3       * the StringBuffer passed as a parameter
 4       * 
 5       * basic data type value passed with no change in the value of
 6       * reference value delivery data type, can change its value
 7       * 
 8       * Although reference data type is String class, but he is passed as a parameter and is the same basic data types
 . 9       * * / 
10      public  static  void main (String [] args) {
 . 11          String S = "Heima" ;
 12 is          the System.out. the println (S);
 13 is          Change (S);
 14          System.out.println (S);
 15          
16         StringBuffer sb =new StringBuffer();
17         sb.append("heima");
18         System.out.println(sb);
19         Change(sb);
20         System.out.println(sb);
21 
22     }
23 
24     public static void Change(StringBuffer sb) {
25         sb.append("baima");
26         
27     }
28 
29     public static void Change(String s) {
30         s +="itcast";
31         
32     }
such as

 

 

Parameter passing

String passed as a parameter

StringBuffer passed as parameters

Transmitting the basic data types of values, does not change its value

Reference value delivery data type, change its value

Although the String class reference data types, but when he passed as parameters and basic data type is the same

Guess you like

Origin www.cnblogs.com/Sherwin-liao/p/11012078.html