Java基础(更新ing...)

Java语法

1.标识符定义规范
字母/下划线/$开头,字母数字下划线$组成,不能包含特殊字符(包括空格),不能以数字开头;

不能是java关键字和保留字,但可以包含;
严格区分大小写;
命名有意义.

2.数据类型

基本数据类型
(1) 整型 byte、int、long、short
(2) 浮点型 float、double
(3) 布尔型 boolean
(4) 字符型 char
引用类型-数组对象
引用数据类型

数组
接口

3.类型转换
强制类型转换、隐式转换
float f = 10.1;  

int i = (int)f;

4.变量、常量输出
 %c, ascii码对应字符(单个字符)
 %n, 换行(\n)
 %d, 十进制整数
 %u, 无符号十进制数
 %f 十进制浮点数
 %s  字符串
 %%  输出百分号
   if(cin.hasNextInt()){
int x=cin.nextInt();
            System.out.printf(%#o\n”,x);//八进制数 
System.out.printf(%#x\n”,x);//十六进制数
}else{
	System.out.println(“error”);
}

(1).整型常量: 八进制整数:用0开头,如076, -0123;
十六进制整数:用0x或0X开头,如0x123,-0X12。
(2).浮点型常量
(3).字符型常量: 用单引号括起来的转义字符如’\t’,’\n’,’\u000A’
用单引号括起来的一个字符:如’A’,’b’。

(4).字符串常量(引用类型)
(5).符号常量: 可以为任何类型,定义符号常量声明时必须要进行初始化,且程序行过程中不能再改变。例如:final PI=3.1415926;
注:希冀平台 中文输入:Scanner cin=new Scanner(System.in.”UTF-8”);
中文输出:PrintStream ps=new PrintStream(System.out,true,”UTF-8”);
Ps.println();
不要出现魔法值(即未经预先定义的常量)直接出现在代码中
int id = 01;
String key = “tom_" +id ;

5.自增
		i++ 先将值给表达式 再自增
		++i 先将值自增再给表达式

浮点型存在误差,不建议直接比较 例如:3.0 - 2.1 == 0.9 //false

6.运算符短路现象

if(A||B) A为真不执行B;
if(A&&B)A为假不执行B;

int a =1,b=1;
if(++a>=2 && b-->2)
    b++;        //a=2  b=0
if(a--< 3 || ++b<0)
b--;        //a=1   b=-1
int a =1,b=1;
if(a--< 3 || ++b<0)
b--;        //a=0   b=0
7.循环结构

int i =1;
for(;i++<5;); //6
int i =1;
for(;++i<5;);//5

8.Switch分支
有无break区别

switch ( expression ) {
case value1:
语句序列1;
[break;]
case valueN:
语句序列n;
[break;]
default: 语句序列n+1;
}

9.break与continue
 break跳出本层循环
 continue跳出本次循环,进入下一次循环

OOP

1.类和对象
(1).定义类:class 类名{
数据类型 变量名;//成员变量 类里面方法之外(存放于堆,待整个程序结束自动被回收)
返回值类型 方法名(参数){//局部变量
数据类型 变量名;//局部变量 方法里面以及方法的参数(存放于栈,方法结束自动清空)
}//到此释放空间
}
//方法与局部变量存放栈内存;对象与成员变量存放堆内存;未使用类存放硬盘
成员变量可以不赋初值
默认值:
int———0
float ——0.0
double——0.0
boolean——false
引用类型(包括String)——null
构造方法:会在new对象实例化时进行;
类名(参数1,参数2){

}
补充:如果构造方法有参数,实例化对象也一定对应传入参数;
若类没有定义任何的构造方法,java会自动补全一个无参数无内容的构造方法,
基本会在构造方法里进行数据的初始化.

	(2)对象实例化: 类名 对象名 = new 类名();
 对象空间里的内容会一直存在直到程序崩溃

对象数组——很多个相同类别对象
类名 [ ] 对象数组名=new 类名[n];//保存多个对象
对象数组[i]=new 类名();//第i对象实例化

(3)类和对象方法重载
方法重载条件:
方法名相同;
参数不同:参数个数不同、参数数据类型不同、不同数据类型的参数顺序不同;
注:方法重载与方法的返回值类型、参数名都无关
eg: public A(int a){}
public A(int b){}//不是重载,编译器无法识别通过
public B(String m,int n){}
public B(int n,String m){}//重载,不同数据类型的参数顺序不同

2.this关键字
this 关键字指代当前对象

3.静态static关键字 静态修饰符
static 数据类型 变量名;//静态成员变量
所有对象共享同一个静态成员变量
对象名.变量名
类名.变量名(static)

修饰成员变量
修饰成员方法/成员类
static 修饰普通方法
不能修饰构造方法
静态方法只能使用静态成员变量

static静态代码块 :只执行一次
static{
}
static 代码块在类里,优先于构造方法执行;
static 代码块和main函数在公共类中,static优先于main函数执行
public class ex1{
public static void main(String[] args){
pets p1 = new pets();
pets p2= new pets();
System.out.println(pets.count2+p2.count1);//2+1=3
}
}
class pets{
int count1;
static int count2;
public pets() {
count1++;count2++;
}
}

extends
注:1’类的声明没有使用extends关键字,默认父类为java的根类Object类。(例如数组、String等等);
2’单继承机制:一个子类只能继承一个父类
3’子类 extends 父类{ }
子类可以继承父类所有的成员变量 所有的成员方法
3.变量的隐藏、方法的覆盖
成员变量隐藏:子类定义与父类相同名的变量(数据类型、变量名完全相同),父类成员变量被隐藏;想要使用父类的成员变量,可以使用super.父类成员变量的方式使用
子类的内容先从子类找,子类找不到去父类找,父类找不到代码报错;
class Animal{
char b=102;
void printInfo1(){
System.out.println(this.b);
}
}
class Dog extends Animal{
char a=69;
void printInfo(){
System.out.println(this.b);
}
}
mian(){
Dog d=new Dog();
d.printInfo();//
子类调用
this.b 子类没有成员变量b去
父类找b=102 ascci码 f
}
方法覆盖(重写):子类定义与父类完全相同的方法(方法名,返回类型与返回值完全一致),父类方法被覆盖

5.super关键字
(1).子类继承父类,实例化子类对象,先隐式调用父类无参构造方法,再去调用自身子类的构造方法(看清楚有参还是无参,一一对应)
注意: print和println;
char类型输出ASCII码
(2).若父类只有有参数的构造方法(没有无参构造方法),同时子类不做另外的操作,编译无法通过;
解决方法:
在父类添加无参数构造方法,子类会隐式调用;
在子类构造方法第一行添加super语句;
在子类构造方法第一行添加this语句,调用子类自身其他构造方法
(3).子类中调用父类有参数构造方法
super(参数);
且super();只能放在子类构造方法的第一行
注:super关键字只能在子类中使用,应用场景针对子类成员变量隐藏和方法覆盖时想要使用父类被屏蔽的成员变量、成员方法,使用super关键字。super.**
使用父类中有参数的构造方法,必须在子类的构造方法中第一行使用super();
(1)若主函数实例化BMW bmw = new BMW()
(2)若主函数实例化BMW bmw1 = new BMW(2)
(1)(2)运行结果是(用分号隔开两个答案) 01;02
class Car{
int a = 0;
int b = 0;
public Car() {System.out.print(a);}
public Car(int a) {System.out.print(this.a);}
void runing() {}
}
class BMW extends Car{
int a = 1;
public BMW(){System.out.print(a);}
public BMW(int a) {
super(a);System.out.print(this.a);
}
}

6.final关键字
final修饰成员变量、构造方法、成员方法
final 修饰局部变量-方法的作用范围要使用就必须赋值,作用范围在方法内且只能赋值一次
final 修饰成员变量(直接赋值)或在在静态代码块或者构造方法赋值一次(任何位置都不能修改)
成员变量—未赋值的叫做空白final变量,需要在构造方法(普通成员变量)或静态代码块赋值(静态成员变量)
静态成员变量只能在静态代码块赋值
普通成员变量只能在构造方法赋值
final修饰的方法无法被覆盖,一定要满足方法覆盖
class Animal{
final int a;//编译错误
final int b=1;//正常运行
}
class Animal{
final int a;
static {a=1;}//编译错误

   final static int b;
   static {b=1;}//正常运行

}
class Animal{
final int a=1;
Animal(){a=1;}//编译错误

final int b;
Animal(){b=1;}//正常运行

   final int c;
   void Animal(){c=1;}//编译错误

}

final修饰的类不能作为父类被继承,但可以作为子类继承别的类
有时出于设计安全目的,不想让自己编写的类被别人继承,这时可以使用final关键字修饰类;final修饰的方法不能被子类覆盖
为了设计安全的目的,如果父类的方法不想被子类覆盖,可以使用final关键字修饰父类方法
final class Animal{}
class Dog extends Animal{}//编译错误

final class Animal extends Dog{}
class Dog{}//正常运行

7.多态 向上转型 向下转型
多态发生的三个前提条件:
继承,多态发生在子类和父类之间;
覆盖,子类覆盖父类的方法;
声明的变量类型是父类类型,实例指向子类类型
class Person{
Void eat(){}
}
class Student extends Person{
Public Student(){}
void eat(){}//方法覆盖
}
main(){
Student s1=new Student();
Person s2=new Student();//多态
}
向上转型(隐式转换)—子类引用型变量转换为父类
向下转型(强制转换)—父类引用类型变量转换为子类

abstract关键字-修饰抽象类与抽象方法
抽象类:具有抽象方法的类
抽象方法:父类不能具体实现的方法,要求子类实现;
一个抽象类可以有0n个抽象方法,以及0n个具体方法
父类作为抽象类,子类必须实现父类的所有抽象方法,依旧为方法覆盖。
abstract class figure{//一个方法被声明为抽象的,那么这个类必须声明为抽象的;
double area;//成员变量,可以不赋值
abstract void area();//抽象方法只有方法的声明,没有方法的实现
void c(){}
//errorvoid a();
}
class triangle extends figure{
void area(){}
}
抽象类不能被实例化,只有具体类才能被实例化
figure f=new triangle();//指向子类实例,发生多态 向上转型

接口:
接口可以有成员变量,也可以没有成员变量
无构造方法,static代码块
interface Figure{
int a=0;//省略 static final接口中所有成员变量都是静态成员常量,必须赋值
abstract void f1();
void f2();//省略 public abstract
//error void f(){}//所有的方法都是抽象方法,不包含普通的成员方法;
}
接口实现:
接口与抽象类一样都不能被实例化;
接口中不能有实例成员变量,所有声明的成员变量都是静态常量。抽象类与普通类一样,各种形式成员变量都可以声明;
接口中没有包含也不需要构造方法。抽象类需要构造方法,即使程序没实现也会有默认构造方法.
interface B{
void f3();
}
class A{ }
class circle extends A implements Figure,B{ //java单继承,多实现
public void f1(){}
public void f2(){}
public void f3(){}//实现接口时,必须实现接口的所有抽象方法
}
如果一个类使用了某个接口,那么这个类必须实现该接口的 所有方法

异常处理

java中所有异常均当作对象处理
1.异常类型识别
(1).RuntimeException(运行时异常)
ArithmeticException: 数学运算异常 例:int b=3/0;
NullPointerException: 空指针异常,在要求使用对象的地方使用了null
Dog []d=new Dog[2];
d[0]=new Dog();
d[1].leg=3;//NullPointerException
d[2].leg=3;//ArrayIndexOutOfBoundsException
NegativeArraySizeException:数组大小为负值异常
int n=cin.nextInt();
Int []a=new int[n];//输入n为负数
ArrayIndexOutOfBoundsException:数组下标越界异常
NumberFormatException:数字格式异常
String n=cin.next();
Int a=Integer.valueOf(n);
//例12.54、dddko
InputMismatchException:读取类型与期望类型不匹配

(2).IOException(受检查异常)

(3)…

        Error:程序无法处理的错误,交由系统处理

2.异常处理基本内容
若try代码块中有很多语句会发生异常,且异常种类不止一种,try后面可以跟多个catch代码块.多个catch代码块
Try(声明或初始化资源语句,可以有多条语句,语句直接用;分隔){
}catch(Throwable e){
}catch(Throwable e){
}finally{
//释放资源,无论try正常结束还是catch异常结束,finally代码块都会被执行
}
(1).当一个catch代码块捕获一个异常时,其他catch代码块不在进行匹配
(2).当catch代码块存在父类和子类异常,一定是先捕获子类异常,再捕获父类异常
(3).try{
try{}catch(Throwable e){}
}catch(Throwable e){}
try-catch进行嵌套时,如果内层发生异常,先从内层catch进行捕获,如果捕获不到,则由外层catch捕获

2.抛出异常 受检查异常
throws—方法后声明抛出异常
throw—人工引发的异常

常用API类

1.Math  基本所有Math 返回double类型
		  sqrt:
          Math.sqrt(-90);//NaN
abs:
Math.abs(-6.32);//6.32
static  double  ceil(double a):
    Math.ceil(3.2);//4.0
static  double  floor(double a):
      Math.floor(3.2);//3.0
static  double  round(double a):四舍五入
Math.round(3.4);//3
Math.round(3.6);//4
Mah.sin((Math.PI/2));//1.0
Math.E;//2.71828...
Math.log(Math.E);//1.0
Math.log10(10);//1.0
2.String
	indexOf:
String m=”helloworld”;
String z=”llowor”;
int pos=m.indexOf(z);//2
compareTo:
      String s1=”hello”;
      String s2=”hi”;
      String s3=”he”;
      String s4=Hello;
      int a=s1.compareTo(s2);//e-i=-4   s1-s2 ASCII 
      int b=s1.compareTo(s3);//3   llo的长度
      int c=s1.compareTo(s4);//h-H=32
         c=s1.compareToIgnoreCase(s4);//0 忽略大小写      
startWith:
boolean d=s1.startsWith(“he”);//true
endWith:
			boolean e=s1.endsWith(Lo);//false

replace
       String s1=”hello world!;
       s1=s1.replace(‘l’,L);//heLLo worLd!
       String s2=”hellohelloworldhellohelloworldhellohelloworld”;
       s2=s2.replace(“ll”,” ”);//he ohe oworldhe ohe oworldhe ohe oworld
String.format
int num = Integer.parseInt(str);
Integer. valueOf()可以将基本类型int转换为包装类型Integer,或者将String转换成IntegerString如果为Null或“”都会报错

lastIndexOf() 方法:
public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1;
public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1;
public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1;
public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1.

集合

Java中任何集合中存放的都是对象,即引用数据类型,基本数据类型不能放到集合中。
所有的方法都是抽象方法,只做声明 不能被实例化

java.util包  
  父接口                      子接口      实现类
                
 Set<E>          new HashSet
集合 无序不重复      
 Collection<E>              Queue<E>
List<E>  LinkedList  插入、删除效率高 占用内存空间比较大
有序可重复 
         ArrayList  查找效率高,访问元素速度快
 Map<K,V>                          new HashMap

List:
List a=new ArrayList( );
a.add(54);
a.add(‘l’);
a.add(‘s’);
a.add(“hello”);
a.add(new Dog());//输出Dog类存储在JVM/内存中的地址
try{
a.add(7,’k’);
System.out.println(a);
}catch(IndexOutOfBoundsException e){
		System.out.println(“error”);
}

System.out.println(a.get(3));//获取指定位置的元素
System.out.println(a.indexOf(‘o’));//元素不存在返回-1
 	 a.remove(2);//删除某个位置的元素
a.remove(‘p’);//转ASCII查找删除,可能越界
a.remove(“hello”);//若存在多个相同字符串,删除第一个
for(int i=0;i<a.size;i++){
System.out.print(a.get(i)+” ”);
}//普通遍历
Iterator it =a.iterator( );
While(it.hasNext( )){  //判断迭代器是否有元素
System.out.print(it.next()+” ”);//获取List元素
}//迭代器遍历


Set:
   Set s = new HashSet();
s.add(‘o’);//位置随机
s.add(“hello”);
s.add(3);//无法重复添加元素
System.out.println(s);
System.out.println(s.contains(‘o’));//true or false
s.remove();
s.clear();
Iterator it =s.itreator();
While(it.hasNext()){
   System.out.println(it.next());
}

Map(key,value):  key—Set集合   value—Collection集合
Map m =new HashMap( );
m.put(“CN”,”中国”);
m.put(“cn”,”中国”);
m.put(“us”,”美国”);
 System.out.println(m);
 System.out.println(m.get(“CN”));//只能根据Key查找
 System.out.println(m.get(“中国”));//null
   m.remove(“CN”);//只能根据Key,删除一对键值
 System.out.println(m.containsKey(“CN”));
 System.out.println(m.containsValue(“中国”));
//遍历
 System.out.println(m.keySet());
 System.out.println(m.values());
Set s=m.KeySet();
Iterator it =s.itreator();
While(it.hasNext()){
Object o=it.next();
System.out.print(o+” “);
System.out.println(m.get(o));
}

IO

//File类属性
     File f1 = new File(“a.txt”); 
     File f2 = new File(“b.txt”);
System.out.println(f1.getName());//获取文件名函数System.out.println(f1.getPath());//获取文件相对路径的函数System.out.println(f1.getAbsolutePath());//获取文件绝对路径的函数System.out.println(f1.length());//获取文件长度System.out.println(f1.exists());//判断文件是否存在的函数System.out.println(f1.canWrite());//判断文件是否可写的函数System.out.println(f1.isFile());//判断文件是否是文件的函数System.out.println(f1.isDirectory());//判断文件是否是目录的函数System.out.println(f1.isHidden());//判断文件是否隐藏函数

1.文件赋值
编写一个程序,实现文件的复制。程序的任务是将当前目录下filecopy.in文件复制成	filecopy.out。
输入文件为当前目录下的filecopy.in。其内容由任意文本构成;
输出文件为当前目录下的filecopy.out
public class copy{
  public static void main(String[] args){
    byte[ ] data =new data[1000];
    File f=new File(“filecopy.in”);//读取 
    InputStream in = new FileInputStream(f);
    int n=in.read(data,0,1000);
    in.close();
    String s=new String(data,0,n,”UTF-8);
    byte []data =s.getBytes(“UTF-8);
    File w=new File(“filecopy.out”);//写入
    OutputStream os =new FileOutputStream(w);
    os.write(data);
    os.close();
}
}2.子串逆置
输入两行字符串s和t(s和t最长含50个字符,可以含有空格),将s串中首次与t匹配的子串逆置,并将结果输出。输入文件为invertsub.in,含有两行字符串s和t,分别以#作为串结束符;输出文件invertsub.out只有一行,包含一个串,是要求的输出结果。在行末也要有一个回车符。
helloworld#
llowor#
【输出样例】
Herowollld
public class Main {
	public static void main(String[] args) throws IOException {
		String filename = "invertsub.in";
		List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);
		// lines.forEach(System.out::println);
		String[] str = lines.toArray(new String[lines.size()]);
//	    for(String s : str) {  
//	         System.out.println(s);  
//	    }  	
	String a = str[0].toString();
		String b = str[1].toString();
		a = a.substring(0, a.length() - 1);
		b = b.substring(0, b.length() - 1);
		int pos = a.indexOf(b);
		a = reverseSub(a, pos, b.length() + pos - 1);
		//System.out.println(a);		
		a = a + System.getProperty("line.separator");
		byte[] date = a.getBytes("UTF-8");
		File W = new File("invertsub.out");
		OutputStream os = new FileOutputStream(W);
		os.write(date);
		os.close();
	}
	static String reverseSub(String str, int start, int end) {
		String b = "";
		char[] c = str.toCharArray();
		int i = start, j = end;
		while (i <= (start + end) / 2) {
			char ch = c[i];
			c[i] = c[j];
			c[j] = ch;
			i++;
			j--;
		}
		for (int k = 0; k <= c.length - 1; k++) {
			b = b + c[k];
		}
return b;
	}
}

GUI界面

1.布局管理器
BorderLayout默认把容器分为:东、西、南、北、中,每个区域只能放置一个组件;
FlowLayout 摆放组件规律:从上到下,从左到右;
GriderLayout 网格形式对组件进行摆放,容器被分为大小相等的矩形,一个矩形中放置一个组件.

2.组件
文本框 JTextField 文本域 JTextArea 按钮 JButton
单选按钮JRadioButton 复选框 JCheckBox 标签 JLabel
密码框 JPasswordField

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值