Java入门学习笔记

时间:2023-03-09 20:58:41
Java入门学习笔记

Hello.java

 public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
文件名必须和程序的类名完全一致。扩展名是.java,编译文件为.class  
一个project对应一个目录,源码存放在src目录, 编译输出存放在bin目录, bin目录在eclipse中自动隐藏。
计算机最小存储单元是字节,一个字节8个二进制数00000000~11111111(1B=8b).
变量分为两种:基本类型和引用类型。
基本类型(持有某个数值):
  • 整数类型:byte(1B),short(2B),int(4B),long(8B)
  • 浮点类型:float(4B),double(8B)
  • 字符类型:char(2B)
  • 布尔类型:boolean
         final double PI = 3.1415;
byte b = 127; // -128 ~ +127
short s = 32767; // -32768 ~ +32767
int i = 2147483647;
int i2 = -2147483648;
int i3 = 2_000_000_000; // 加下划线更容易识别
int i4 = 0xff0000; // 表示16进制的数
int i5 = 0b100000;// 表示二进制数
long l = 90000000000L; // 结尾加L
float f = 3.14e4f;
double f2 = 3.14e4; System.out.println(Integer.toHexString(11)); // 输出16进制表示的整形
System.out.println(Integer.toBinaryString(10)); // 输出二进制表示的整形
  • 与运算特点:把某些位保留下来,其余位全部置0
  • 或运算特点:把某些位保留下来,其余位全部置1
  • ^异或运算:相同为0不同为1
         double a=0.0/0; // NaN(Not a number)
double a1=1.0/0; // Infinity
double a2=-1.0/0; // -Infinity

java使用Unicode表示字符

字符串类型是引用类型(变量指向某个对象,而不是持有某个对象)

         char c1='A';
char c2='中';
int n1=c1; //
int n2=c2; //
char c3='\u0041'; // \ u加4位的16进制数也可表示字符
String s="中文123"; // 五个字符
String s1="12\n"; // 三个字符
String s2=null; // 输出null
String s3=""; // 和null不一样

数组是引用类型的变量

         int[] ns1 = new int[5];
int[] ns2 = new int[] { 1, 2, 3, 4, 5 };
int[] ns3 = { 1, 2, 3, 4, 5 };
int[] ns4=ns3;
ns3[3]=999; // ns[4]=999,它们指向同一个数组
System.out.printf("%1$s %3$s %2$s %1$s", "A", "B", "C"); // A C B A $可以调整参数位置
         int[] ns = {1, 2, 3};
System.out.println(Arrays.toString(ns));
int[][] ns1= {{1}, {1, 2}, {1, 2, 3}};
System.out.println(Arrays.deepToString(ns1));

命令行参数是String[], 由用户输入并传递给main方法,如何解析命令行参数由程序自己实现。

this作用:

  1. 表示类中的属性
  2. 可以使用this调用本类的构造方法
  3. this表示当前对象,如下
 public boolean compare(Person per) {
Person per1 = this; //表示当前调用方法的对象,为per1
Person per2 = per;
if(per1 == per2)
return true;
if(per1.name.equals(per2.name) && per1.age==per2.age) {
return true;
}else {
return false;
}
}

Java中主要存在4块内存空间:

  1. 栈内存空间:保存所有对象的名称(准确说保存了引用的堆内存地址)
  2. 堆内存空间:保存了每个对象的具体属性内容
  3. 全局数据区:保存static类型的属性
  4. 全局代码区:保存所有的方法定义

非static声明的方法可以去调用static声明的属性或方法, 但是static声明的方法是不能调用非static类型声明的属性或方法

抽象类就是比普通类多了一个抽象方法, 除了不能直接进行对象的实例化操作之外并没有任何的不同。

接口:一种特殊的类,明确由全局常量和公共的抽象方法组成,可简写。

 public interface A {
public static final String NAME = "XiaoMing";// 全局变量,等价于Stirng NAME = "XiaoMing"
public abstract void print(); // 定义抽象方法 , 等价于void print();
public abstract String getInfo(); // 定义抽象方法,等价于String getInfo();
// 接口方法默认public, 不是default。
}

若一个子类既要实现接口又要继承抽象类,如下

 class 子类 extends 抽象类 implements 接口A, 接口B,...{
}

允许一个抽象类实现多个接口, 但一个接口不允许继承抽象类, 但是允许一个接口继承多个接口,如下

 interface 子接口 extends 父接口A,父接口B,...{
}

除了在抽象类中定义接口及在接口中定义抽象类外, 对于抽象类来说也可以在内部定义多个抽象类, 而一个接口也可以在内部定义多个接口。

对象在向下转型先前用instanceof判断是否是某的类的实例, true后在转型。

object可接收一切引用类型,包括数组和接口类型。

 int x = 30;
Integer i = new Integer(x)
= Integer i = 30;//自动装箱 int temp = i.intValue;
= int temp=i;//自动拆箱
 // Integer类(字符串转int型)
public static int parseInt(String s) throws NumberFormatException
// Float类(字符串转float型)
public static float parseFloat(String s) throws NumberFormatException(异常属于RuntimeException可以不使用Try...catch处理,有异常交给JVM处理)
以上两种操作,字符串必须由数字组成。(Integer.parseInt,Float.parseFloat这样调用)

如果一个程序导入多个包中有同名类, 调用时“包.类名称”。

Thread类中提供了public Thread(Runnable target)和public Thread(Runnable target, String name)两个构造方法,可以接受Runnable接口的子类实例对象,可以以此启动多线程,

Thread和Runnable的子类都同时实现了Runnable的接口,之后将Runnable的子类放到Thread类之中,类似代理设计。

Runnable接口可以资源共享:

 public class Mythread extends Thread{

     private int ticket = 5;
public void run() {
for(int i=0;i<100;i++) {
if(ticket>0) {
System.out.println("买票:ticket="+ticket--);
}
}
}
}
public class Main { public static void main(String args[]) {
Mythread my1 = new Mythread();
Mythread my2 = new Mythread();
Mythread my3 = new Mythread();
my1.start();
my2.start();
my3.start();
}
}

终断线程:

 public class Mythread implements Runnable{

     public void run() {
System.out.println("进入run方法");
try {
Thread.sleep(5000);
System.out.println("休眠结束");
}catch(Exception e) {
System.out.println("休眠被终止");
return;
}
System.out.println("休眠正常结束");
}
}
public class Main { public static void main(String[] args) { Thread t = new Thread(new Mythread());
t.start();
try {
Thread.sleep(2000);
}catch(Exception e) {};
t.interrupt();
}
}

线程礼让:

 public class Mythread implements Runnable{
@Override
public void run() { for(int i=1; i<=5; i++) {
System.out.println(Thread.currentThread().getName()+"运行"+i);
if(i==3)
{
System.out.println("线程礼让");
Thread.currentThread().yield();
}
}
}
public class Main { public static void main(String[] args) { Mythread my = new Mythread();
Thread t1 = new Thread(my, "线程A");
Thread t2 = new Thread(my, "线程B");
t1.start();
t2.start();
} }

线程操作实例:生产者与消费者(生产者一直生产,消费者不断取走)

存在两个问题:

  1. 在线程中生产者没有添加完信息,消费者就取走,信息联系错乱。( 解决:同步方法synchronized )
  2. 线程中生产者放了多次消费者不取或消费者取了多次已取过的信息。 ( 解决: 加flag标记,同时利用object类中的等待wait()与唤醒notify() )

代码:

 public class Main {

     public static void main(String[] args) {

         Info info = new Info();
Producer p = new Producer(info);
Consumer c = new Consumer(info);
new Thread(p).start();
new Thread(c).start();
}
}
public class Info { private boolean flag = false;
private String name = "LiXinghua";
private String concent = "Java"; public synchronized void set(String name, String concent) {
if (!flag) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.concent = concent;
flag = false;
super.notify();
} public synchronized void get() {
if (flag) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + " " + this.concent);
flag=true;
super.notify(); }
}
public class Producer implements Runnable { boolean flag = false;
private Info info = null; public Producer(Info info) {
this.info = info;
} @Override
public void run() {
for (int i = 0; i < 10; i++) { if (flag) {
this.info.set("LiXinghua", "Java");
System.out.println("修了几次");
flag = false;
} else {
this.info.set("mldn", "JavaMldn");
System.out.println("修了几次");
flag = true;
}
}
}
}
public class Consumer implements Runnable{ private Info info = null;
public Consumer(Info info) {
this.info = info;
}
@Override
public void run() { for(int i=0; i<10; i++) {
this.info.get();
} }

停止进程常用方法:在Mythread中调用stop()将flag设置为false这样run()方法就停止运行

代码:

 public class Mythread implements Runnable {

     private boolean flag = true;

     @Override
public void run() { int i = 0;
while (this.flag) {
while (true) {
System.out.println(i++);
}
}
}
public void stop() {
this.flag = false;
}
public class Main { public static void main(String[] args) { Mythread my = new Mythread();
Thread t = new Thread(my, "线程啊");
t.start();
my.stop();
} }

返回值类型 方法名称(Object...args)表示方法可以接收任意多个参数

 public class Main {

     public static void main(String args[]) {

         String str[] = fun("lasd", "asd", "111");
for(String t:str) {
System.out.print(t+"、");
}
}
public static <T> T[] fun(T... args) {
return args;
}
}

finalize()可以让一个对象被回收前执行操作:

     @Override
public String toString() {
return "姓名:" + this.name + ", " + "年龄:" + this.age;
}
public void finalize() throws Throwable{
System.out.println(this);
}

格式化日期操作:

public SimpleDateFormat(String pattern) 构造类型 ,通过一个指定的模板构造对象

public Date parse(String sourse) throws ParseException 普通类型,将一个包含日期的字符串变为Date类型

public final String format(Date date) 普通类型, 将一个Date类型按照指定格式变为String类型

 import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Main { public static void main(String args[]) { Date d = null;
String strDate = "2018-8-26 17:11:30.214";
String pat1 = "yyyy-MM-dd hh:mm:ss.SSS";
String pat2 = "yyyy年MM月dd日, hh时mm分ss秒SSS毫秒啦!"; SimpleDateFormat sdf1 = new SimpleDateFormat(pat1);
SimpleDateFormat sdf2 = new SimpleDateFormat(pat2);
try {
d = sdf1.parse(strDate);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sdf2.format(d));
}
}