Java学习记录(基础)

一、Java基本语法
对象:类的一个实例,有状态(变量)和动作(函数)
类:描述一类对象的状态和动作
方法:
实例变量:确定对象的状态

1、Java对象和类
1.1
局部变量:在方法、构造方法和语句块中定义的变量。声明和初始化都在方法中,方法结束,变量基于会自动销毁。
成员变量:定义在类中,方法体之外的变量。在创建对象时实例化
类变量::声明为static类型
构造方法:

public class Puppy{
     public Puppy(){
     }
 
     public Puppy(String name){
     }
}

1.2 创建对象
使用new创建一个对象:
① 声明:包括对象名称和对象类型;
② 实例化:new
③ 初始化:调用构造方法初始化对象;

Puppy mypuppy = new Puppy("Lili");

2、基本数据类型
byte:1字节(有符号)
short:2字节(有符号)
int:4字节
long:8字节
float:4字节
double:8字节

boolean:true/false
char:2字节(C++中占1字节)

Byte/Short/Integer/Long/Float/Double.SIZE;
Byte/Short/Integer/Long/Float/Double.MAX_VALUE;
Byte/Short/Integer/Long/Float/Double.MIN_VALUE;

使用final来修饰常量
八进制:前缀0;
十六进制:前缀0x
ASCII码:a : 97; A:65

3、变量
Java支持的变量
类变量:方法之外定义的变量,用static修饰;
实例变量:方法之外定义的变量,不用static修饰;
局部变量:方法内定义的变量,在栈上分配,在方法执行时创建,退出时销毁,声明后必须初始化

public class Variable{
     static int all = 0; //类变量
     String str = "Hello";  //实例变量
     public void method(){
            int i = 0;  //局部变量
}

实例变量:类中、方法之外;对象被实例化后,实例变量也跟着确定;在对象创建时创建、销毁时销毁;一般设置为private,使用访问修饰符使其对子类可见;直接通过变量名访问,在静态类和其它类中,使用完全限定名

类变量:(静态变量)用static修饰,在方法外;无论类有多少对象,类只拥有一份静态变量的拷贝初始化后不可改变; 存在静态存储区,通常声明为常量;其他类访问则需要类名.变量名

4、修饰符
访问控制修饰符(public、private、protected、defaul):public、protected不能修饰类

**private:**只能被所属类访问,类和接口不能用private修饰;用来隐藏类的实现细节和保护类的数据;外部类访问需要使用getter方法

protected:基类的protected成员在包内可见,对其子类也可见;若子类和基类不在一个包内,那么子类可以访问他继承的protected成员不能访问基类实例的protected方法
clone()只对包java.lang及其子类可见

package p2;
class MyObject2 {
    protected Object clone() throws CloneNotSupportedException{
       return super.clone();
    }
}
 
package p22;
public class Test2 extends MyObject2 {
    public static void main(String args[]) {
       MyObject2 obj = new MyObject2();
       obj.clone(); // Compile Error         ----(1)
                    //不在一个包内
       Test2 tobj = new Test2();
       tobj.clone(); // Complie OK         ----(2)
                     //Test2访问的是其本身实例从基类继承的方法                         
    }
}

访问控制修饰符继承规则:
public:子类中必须为public;
protected:子类中为protected或public,不能为private
private:不能被继承

非访问修饰符:
static:修饰类方法和类变量;
final:修饰类、方法和变量。final修饰的类不能被继承;方法不能被子类重新定义;定义的变量不能修改
abstract:修饰抽象类和抽象方法
synchronized和volatile:用于线程的编程

abstract类:不能实例化对象,为了类的扩充;不能同时被final和static修饰;
abstract方法:该方法是没有实现的方法,具体由子类提供;**不能声明为static和final;**子类必须实现父类所有的抽象方法,除非子类是抽象类;抽象类可以不包含抽象方法;抽象方法声明以;结尾

synchronized修饰符:方法同一时间只能由一个线程访问。

transient修饰符:表示该成员变量不参与序列化过程

**volatile修饰符:**每次被线程访问时,都强制从共享内存中读取改变量的值,当变量值改变时,会强制线程将变化值写回共享内存,这样任何时刻,两个不同的线程看到的成员变量都是一个值。

public class MyRunnable implements Runnable
{
    private volatile boolean active;
    public void run()
    {
        active = true;
        while (active) // 第一行
        {
            // 代码
        }
    }
    public void stop()
    {
        active = false; // 第二行
    }
}

5、运算符
位运算符:
&与运算:两边同为1才为1,其余为0;
|或运算:同时为0时为0,其余为1;
^异或运算:两边值相同则为0,其余为1
~取反:
<<左移运算符:左移且末位补0,得到的值比原有的大
>>右移运算符:右移,得到的值比原有的小
>>>右移补零运算符:右移,得到的值比原有的小

**短路逻辑运算符:**使用与操作符时,如果第一项为false,那么厚一项就不用判断了

**instanceof运算符:**检查对象是否是一个特定类型

switch case语句中如果没有break,则匹配成功后,将输出后面所有的case语句

6、Number 和 Math类
Number类属于java.lang包
toString():以字符串形式返回值;
parseInt():将字符串解析为int类型

**Character类:**对单个字符进行操作
装箱:

Character ch  = 'a' //将字符‘a’装箱到Character对象ch中`
char c = test('x'); //利用test方法将‘x'装箱,然后拆箱得到的值返回给c

Character方法:
isLetter():是否是字母;
isDigit():是否是数字;
isWhitespace():是否是空白字符
isUpperCase():是否是大写字母
isLowCase ():是否是小写字母
toUpperCase():改为大写形式
toLowCase():改为小写形式
toString() : 返回字符的字符串,长度为1

7、String类

String str = "Hello"; //存储在公共池中
String str1 = String new("Hello"); //构造函数创建对象,字符串存储在堆上

通过字符数组初始化字符串

char[] array = {'h', 'e', 'l', 'l', 'o'};
String str = new String(array); // hello

String类是长度不可改变的
源码分析:字符串实际是一个char数组,且是被final修饰的,String中所有修改都是对char数组进行修改;String s = ‘hello’, s只是String对象的引用,并不是本身,s = ’Google‘后原本的’hello‘还存在于内存中;
StringBuffer类:每次都会对StringBuffer对象本身进行操作,而不产生新的对象
√ **StringBuilder类:**不是线程安全的,相较于StringBuffer有速度优势,长度可变 **
单行用加号拼接字符串是没有性能损失的,java 编译器会隐式的替换成 stringbuilder

public class RunoobTest{
    public static void main(String args[]){
        StringBuilder sb = new StringBuilder(10); //创建一个大小为10的字符数组
        sb.append("Runoob.."); //按字符存入内存中
        System.out.println(sb);  //Runoob..
        sb.append("!"); 
        System.out.println(sb); //Runoob..!
        sb.insert(8, "Java"); //在位置8处插入”Java“
        System.out.println(sb); //Runoob..Java!
        sb.delete(5,8); //删除[5,8)之间的字符
        System.out.println(sb); //RunooJava!
    }
}

① StringBuffer类的方法:
append():添加字符串到指定字符序列
**reverse():**反转形式
delete(int start, int end):
insert(int index, int i) : 将i插入到序列中
replace(int start, int end, String str) : 使用str替换从start到end范围的字串

② String类的方法:
capacity():返回当前容量
length():返回字符长度
charAt(int index):返回index位置处的char值
isEmpty():是否为空
**concat(String str):**连接两个字符串
String[] split(String regex) : 按给定正则表达式拆分字符串
indexOf(String str):返回第一次出现str的位置索引
setCharAt(int index, char ch):将指定索引处的字符设置为ch。

8、Java数组
数组是引用传递,

double[] myArray = new double[10];

数组作为函数参数:public static void printarray(int[] array)
数组作为函数返回值:

public static int[] reverse(int[] array)
{
     int[] ret = new int[array.length];
     for(int i = 0, j = ret.length-1; i < ret.length; i++,j--)
     {
           ret[i] = array[j];
      }
      return ret;
}

Array类方法
binarySearch(int[] array, int key): 二分查找key是否在数组中,数组是排好序的
equal(int[] a1, int[] a2):
fill(int[] a, int val): 将指定的val值分配给数组指定范围内的每个元素
sort(int[] a): 升序排列

9、Java日期
包:java.util.Date
Date类:构造函数Date() 和 Date(millisec)
getTime():返回自1970年1月1日以来的毫秒数
toString() : 打印当前日期和时间

10、Java正则表达式
查找字符串中是否包含子串
pattern = Pattern.compile(REGEX);
matcher = pattren.matcher(INPUT);

String content = " from runoob.com";
String pattern = ".*runoob.*";
boolean isMatch = Pattern.matches(pattern, content);

java中\反斜杠表转义

11、函数
可变参数:同一类型参数在参数类型后加省略号…,其它普通参数只能在它之前声明
finalize()方法:在对象被垃圾收集器析构(回收)之前调用,清除回收对象
手动回收内存,Java中由JVM自动回收

protected void finalize(){ }

12、流、文件
java.io包包含所有输入、输出所需的类
输入流表示从一个源读取数据,输出流表示向一个目标写数据

12.1 读取控制台输入:为获取绑定到控制台的字符流,可以将System.in包装到一个BufferedReader对象中创建字符流

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

① read()方法读取字符

import java.io.*;
public class BRRead {
    public static void main(String[] args) throws IOException
    {
    	char c;
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	do {
    		c = (char) br.read();
    		System.out.println(c);
    	}while(c != 'q');
    }
}

② readline()读取字符串

import java.io.*;
public class BRRead {
    public static void main(String[] args) throws IOException
    {
    	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    	String str;
    	do {
    		str = bf.readLine();
    		System.out.println(str);
    	}while(!str.equals("end"));
    }
}

12.2 控制台输出
PrintStream类定义,System.out是该类对象的一个引用。有print()和println()两种方法;
write()方法用来向控制台写操作

12.3 文件流
① FileInputStram:从文件读取数据

InputStream f = new FileInputStream("C:/java/hello");

File f = new File("C:/java/hello");
InputStream in = new FileInputStream(f);

② FileOutFile:创建文件并向文件写入数据

OutputStream f = new FileOutputStream("C:/java/hello");

File f = new File("C:/java/hello");
OutputStream of = new FileOutputStream("C:/java/hello");

eg:

import java.io.*;
public class BRRead {
    public static void main(String[] args)
    {
    	try {
    		byte bWrite[] = {1, 2, 4, 6};
    		OutputStream os = new FileOutputStream("test.txt");
    		for(int i = 0; i < bWrite.length; i++)
    		{
    			os.write(bWrite[i]);
    		}
    		os.close();
    		InputStream in = new FileInputStream("test.txt");
    		int size = in.available();
    		for(int i = 0; i < size; i++)
    		{
    			System.out.print((char) in.read() + ' ');
    		}
            in.close();
    	}catch(IOException e)
    	{
    		System.out.print("Exception");
    	}
    }
}

判断是否是目录
f.isDirectory() 检查是否是目录文件
String s[] = f.list(); 使用list方法检查一个文件夹中的内容
删除目录:deleteFolder(f)
删除文件:f.delete();

13 Scanner类
java.util.Scanner;
获取用户输入
① 用**next方法:**只能输出单个字符串 空格后不会显示

Scanner s = new Scanner(System.in);
import java.util.Scanner;
public class BRRead {
    public static void main(String[] args)
    {
    	Scanner s = new Scanner(System.in);
    	if(s.hasNext())
    	{
    		String str = s.next();
    		System.out.println(str);
    	}
    	s.close();
    }
}

next() 和 nextLine()的区别:
next() : 不能得到有空格的字符串; 读取到有效字符才能结束
nextLine():得到输入回车之前的所有字符,可以获得空白
int型 : s.hasNextInt()
int i = s.nextInt()

14、异常处理
如果一个方法没有捕获到一个检查性异常,必须使用一个throws来声明
多重捕获: try{
}catch{
}catch{
}
finally关键字:在try块后执行的代码块
检查性异常:需要继承Exception类;
运行时异常:需要继承RuntimeException类;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值