你需要知道的Java基础知识(一)

Java 源程序与编译型运行区别

image

拆箱 & 装箱

将一个char类型的参数传递给需要一个Character类型参数的方法时,编译器会自动地将char类型参数转换为Character对象。 这种特征称为装箱,反过来称为拆箱

String & StringBuffer & StringBuilder

  • String 创建就不能修改
  • StringBuffer 创建后可以修改,线程安全
  • StringBuilder 创建后可以修改,不是线程安全的,有速度优势,多数情况下建议使用

访问控制修饰符

修饰符当前类同一包内子孙类其他包
publicYYYY
protectedYYYN
defaultYYNN
privateYNNN

数组

  • 创建&使用
double[] double_arr = { 0.0, 0.1, 0.2 };

double double_arr_sum = 0.0;
//数组索引是[0, length)
for(int i=0; i<double_arr.length; i++){
	double_arr_sum += double_arr[i];
}

System.out.println(double_arr_sum);

for(double element : double_arr){
	System.out.println(element);
}
  • 多维数组
    第二维的长度可以不一样
String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");

System.out.println(s[1][2]);

  • java.util.Arrays一个专门处理数据的工具类
    具有以下功能:
  1. fill
  2. sort
  3. equals
  4. binarySearch二分查找
java.util.Arrays.sort(double_arr);

//二分查找的前提是已经排序好了
int index = java.util.Arrays.binarySearch(double_arr, 0.1);
System.out.println(index);

System.out.println(java.util.Arrays.toString(double_arr));
private static int binarySearch0(double[] a, int fromIndex, int toIndex, double key){
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        double midVal = a[mid];

        if (midVal < key)
            low = mid + 1;  // Neither val is NaN, thisVal is smaller
        else if (midVal > key)
            high = mid - 1; // Neither val is NaN, thisVal is larger
        else {
            long midBits = Double.doubleToLongBits(midVal);
            long keyBits = Double.doubleToLongBits(key);
            if (midBits == keyBits)     // Values are equal
                return mid;             // Key found
            else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
                low = mid + 1;
            else                        // (0.0, -0.0) or (NaN, !NaN)
                high = mid - 1;
        }
    }
    return -(low + 1);  // key not found.
}

/**
 * Returns a string representation of the contents of the specified array.
 * The string representation consists of a list of the array's elements,
 * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
 * separated by the characters <tt>", "</tt> (a comma followed by a
 * space).  Elements are converted to strings as by
 * <tt>String.valueOf(double)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
 * is <tt>null</tt>.
 *
 * @param a the array whose string representation to return
 * @return a string representation of <tt>a</tt>
 * @since 1.5
 */
public static String toString(double[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

时间

  • Date 获得时间
Date date = new Date();
System.out.println(date.toString());
  • 时间格式化
  1. SimpleDateFormat
Date date = new Date();
System.out.println(date.toString());

SimpleDateFormat ft = new SimpleDateFormat("F E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println(ft.format(date));

字母	日期或时间元素	表示	示例
G	Era 标志符	Text	AD
y	年	Year	1996; 96
M	年中的月份	Month	July; Jul; 07
w	年中的周数	Number	27
W	月份中的周数	Number	2
D	年中的天数	Number	189
d	月份中的天数	Number	10
F	月份中的星期	Number	2
E	星期中的天数	Text	Tuesday; Tue
a	Am/pm 标记	Text	PM
H	一天中的小时数(0-23)	Number	0
k	一天中的小时数(1-24)	Number	24
K	am/pm 中的小时数(0-11)	Number	0
h	am/pm 中的小时数(1-12)	Number	12
m	小时中的分钟数	Number	30
s	分钟中的秒数	Number	55
S	毫秒数	Number	978
z	时区	General time zone	Pacific Standard Time; PST; GMT-08:00
Z	时区	RFC 822 time zone	-0800
  1. printf %t开头表示日期格式化
System.out.printf("全部日期和时间信息:%tc%n",date);          
System.out.printf("年-月-日格式:%tF%n",date);  
System.out.printf("月/日/年格式:%tD%n",date);  
System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);  
System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);  
System.out.printf("HH:MM格式(24时制):%tR",date);  
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);


全部日期和时间信息:星期一 五月 08 14:20:24 CST 2017
年-月-日格式:2017-05-08
月/日/年格式:05/08/17
HH:MM:SS PM格式(12时制):02:20:24 下午
HH:MM:SS格式(24时制):14:20:24
HH:MM格式(24时制):14:20
c   包括全部日期和时间信息  星期六 十月 27 14:21:20 CST 2007
F   "年-月-日"格式  2007-10-27
D   "月/日/年"格式  10/27/07
r   "HH:MM:SS PM"格式(12时制) 02:25:51 下午
T   "HH:MM:SS"格式(24时制)    14:28:16
R   "HH:MM"格式(24时制)   14:28
  • Calendar, 日期管理的抽象类,主要针对年月日各个字段增加处理补充方法
  1. add(int field, int amount)
  2. get(int field)
  3. set(int year, int month, int date …)
  4. roll(int field, boolean up_or_down)
field :
Calendar.YEAR	年份
Calendar.MONTH	月份
Calendar.DATE	日期
Calendar.DAY_OF_MONTH	日期,和上面的字段意义完全相同
Calendar.HOUR	12小时制的小时
Calendar.HOUR_OF_DAY	24小时制的小时
Calendar.MINUTE	分钟
Calendar.SECOND	秒
Calendar.DAY_OF_WEEK	星期几
Calendar calendar = Calendar.getInstance();

System.out.println(calendar.getTime());
System.out.println(calendar.getWeekYear());
System.out.println(Calendar.YEAR);

calendar.set(2017, 2, 14);
System.out.println(calendar.getTime());
calendar.set(Calendar.YEAR, 2018);
System.out.println(calendar.getTime());

calendar.roll(Calendar.DATE, true);
System.out.println(calendar.getTime());

正则表达式

  • Pattern、Matcher、PatternSyntaxException
    Pattern处理正则表达式
    Matcher判断INPUT、处理INPUT
String input = "I missing " + "someone.";
String regex = ".*I.*";

boolean isMatch = Pattern.matches(regex, input);
System.out.println("方法一。字符串中是否包含了 'I' 子字符串? " + isMatch);

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
System.out.println("方法二,字符串中是否包含了 'I' 子字符串? " + matcher.matches());
  • group查找
// 按指定模式在字符串查找
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";

// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);

// 现在创建 matcher 对象
Matcher m = r.matcher(line);
if (m.find( )) {
    System.out.println("Found value: " + m.group(0) );
    System.out.println("Found value: " + m.group(1) );
    System.out.println("Found value: " + m.group(2) );
    System.out.println("Found value: " + m.group(3) ); 
} else {
    System.out.println("NO MATCH");
}


// output
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?

方法

  • 可变参数

typeName… parameterName
(…)一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明

public static void main(String[] args) {
	// 调用可变参数的方法
	printMax(34, 3, 3, 2, 56.5);
	printMax(new double[] { 1, 2, 3 });
}

public static void printMax(double... numbers) {
	if (numbers.length == 0) {
		System.out.println("No argument passed");
		return;
	}

	double result = numbers[0];

	for (int i = 1; i < numbers.length; i++)
		if (numbers[i] > result)
			result = numbers[i];
	System.out.println("The max value is " + result);
}
  • finalize
    对象销毁之前,会执行的方法
protected void finalize() {
   // code...
}

数据流

  • system.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
	str = br.readLine();
	System.out.println(str);
} while (!str.equals("end"));
  • InputStream 和 OutputStream
File test_file = new File("/tmp/test.txt");
FileOutputStream file_output = new FileOutputStream(test_file);
// 构建FileOutputStream对象,文件不存在会自动新建
OutputStreamWriter writer = new OutputStreamWriter(file_output, "UTF-8");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
	str = br.readLine();
	System.out.println(str);
	writer.append(str);
	writer.append("\n");
} while (!str.equals("end"));

writer.close();
file_output.close();

FileInputStream file_input = new FileInputStream(test_file);
InputStreamReader reader = new InputStreamReader(file_input, "UTF-8");
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
	sb.append((char) reader.read());
}
System.out.println(sb.toString());

reader.close();
file_input.close();

image

  • Scanner 单独为了接受、处理input stream而生成的工具类
Scanner scanner = new Scanner(System.in);
System.out.println("come on, write some double numble");

double sum = 0;
int m = 0;

while (scanner.hasNextDouble()) {
	double x = scanner.nextDouble();
	m = m + 1;
	sum = sum + x;
}

System.out.println(m + "个数的和为" + sum);
System.out.println(m + "个数的平均值是" + (sum / m));

重载&重写&多态性&虚函数&纯虚函数

  • 重写(Override)
    子类重新实现父类的允许访问方法, 返回值和形参都不能改变,结构不变
    final的方法不能被重写
    static方法不能被重写,但是能够被再次声明
    没有继承,就没有重写
  • 重载(Overload)
    同一个类里,方法名相同,参数不同。返回类型可相同或者不同
    喝继承没有任何关系
  • 多态
    重写(Overriding)和重载(Overloading)是多态性的不同表现
    重写是父类与子类之间多态性的表现
    重载是同一个类中多态性的表现
    多态是同一个行为具有多个不同表现形式或形态的能力
  • 虚函数
    所有可以被重写,重载的函数
  • 纯虚函数
    没有具体实现,一定要被继承后重写的函数,也就是抽象函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值