现在的应用领域:
最主要的特点:平台无关性,完全的面向对象,多线程
简单性
面向对象技术
分布性
健壮性
安全性
体系结构中立
可移植性
解释执行
高性能
多线程
类型 | JAVA | C++ |
---|---|---|
编译 | Java源码会先经过一次编译,成为中间码,中间码再被解释器解释成机器码。对于Java而言,中间码就是字节码(.class),而解释器在JVM中内置了 | C++源码一次编译,直接在编译的过程中链接了,形成了机器码。 |
执行速度 | Java可以利用JVM跨平台。 | C++比Java执行速度快 |
面向对象特性 | Java是纯面向对象的语言,所有代码(包括函数、变量)都必须在类中定义 | C++中还有面向过程的东西,比如全局变量和全局函数。 |
指针 | Java中没有,但是有引用。 | C++中有指针 |
继承 | Java中类都是单继承的。同时Java中的接口是多继承,类对接口的实现也是多实现。 | C++支持多继承 |
运算符重载 | 不可以 | 可以 |
强制自动转型 | 不支持 | 支持 |
Goto语句 | Java不支持C、C++中的Goto语句,而是通过异常处理语句try、catch、finally等来代替C、C++中Goto来处理遇到错误时跳转的情况,使程序更可读且更结构化 | 支持 |
内存管理 | Java对此自动地进行管理并且进行垃圾回收 | C++中通过运算符new和delete来分配和释放内存 |
数据类型的支持 | 在Java中,对于这些数据类型总是分配固定长度的位数,如对int型,它总占32位,这就保证了Java的平台的无关性。 | 在C、C++中,对于不同的平台,编译器为简单数据类型,如int、float等分别分配不同长度的字节数。导致代码不可移植性 |
头文件 | Java不支持头文件,类成员的类型和访问权限都封装在一个类中,运行时系统对访问进行控制,防止对私有数据成员的操作。 | C++中用头文件声明类的原型及全局变量、库函数等 |
结构和联合 | Java中不包含结构和联合,所有的内容都封装在类中。 | C++中的结构和联合中所有成员均为公有,这就带来了安全性问题 |
预处理 | Java不支持宏,它通过关键字final来声明一个常量,以实现宏定义中广泛使用的常量定义。 | C、C++中用宏定义来实现的代码给程序的可读性和安全性带来了困难 |
JVM :英文名称(Java Virtual Machine),就是我们耳熟能详的 Java 虚拟机。它只认识 xxx.class 这种类型的文件,它能够将 class 文件中的字节码指令进行识别并调用操作系统向上的 API 完成动作。所以说,jvm 是 Java 能够跨平台的核心,具体的下文会详细说明。
JRE :英文名称(Java Runtime Environment),我们叫它:Java 运行时环境。它主要包含两个部分,jvm 的标准实现和 Java 的一些基本类库。它相对于 jvm 来说,多出来的是一部分的 Java 类库。
JDK :英文名称(Java Development Kit),Java 开发工具包。jdk 是整个 Java 开发的核心,它集成了 jre 和一些好用的小工具。例如:javac.exe,java.exe,jar.exe 等。
Java的解释过程是通过Java虚拟机读取Java字节码文件(.java),然后将其转换成和系统硬件相关的本地指令(.class),最终在CPU上执行。
解释器在执行字节码文件的过程分为三步:
PATH
SDK平台提供Java编译器(javac.exe)和Java解释器(Java.exe)等位于Java安装包目录的bin文件夹中,为了能够在任何目录中使用编译器和解释器。
CLASSPATH
SDK的安装目录jre文件夹中包含着Java运行程序运行时所需要的Java类库,这些类库被包含在jre/lib目录下的压缩文件rt.jar中
Java 程序结构
▪ |包
▪ |----文件
▪ |----------类
▪ |---------------成员(成员变量,方法)
▪ |-----------------------语句
▪ |---------------------------------表达式
Java的package类似于C++的namespace的作用
package a;
public class A{
public void out(){
System.out.println("This is A!");
}
}
package b;
import a.A;
public class B{
public static void main(String[] args){
A a = new A();
a.out();
}
}
StringBuffer:线程安全的可变字符序列,类似于String的字符串缓冲区。
字符串时字符组成的序列,分为常量和变量
String s1; // 声明
s1 = new String(); // 初始化
String s1 = new String();// 合并使用
length() //求字符串长度
charAt(int index) //返回第index个字符
indexOf(int ch) //返回字符ch第一次出现的位置,找不到返回-1
indexOf(String str,int index) //第index开始,子串第一次出现的位置,找不到返回-1
subString(int index1,int index2) //返回index1到index2的字串
equals(Object object) // 比较字符串内容和指定对象内容
equalsIgnoreCase(String s) // 比较字符串内容,忽略大小写
表示一组类型相同的有序数据
必须先定义,后使用
动态初始化
int[] a = new int[5];
int a[] = new int[5];
复合类型数组
String sArray[] = new String[3]; //第一步:声明数组,指定数组名和元素的数据类型
sArray[0] = new String("how"); //第二步:初始化赋值
sArray[1] = new String("are");
sArray[2] = new String("you");
length属性是数组类唯一的数据成员变量,new创建数组的时候自动给length赋值
二维数组初始化
//方法1
int a[][];
a = new int[3][4];
//方法2
int a[][] = new int[3][4];
//方法3
int a[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}
//方法4
int b[][] = new int[4][];
b[0] = new int[2];
b[1] = new int[4];
b[2] = new int[6];
b[3] = new int[8];
深拷贝和浅拷贝
要求
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 50; j++) {
if (j == 3)
break search;
System.out.println(i+" "+j);
}
}
}
// 输出为:
// 0 0
// 0 1
// 0 2
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 50; j++) {
if (j == 3)
continue search;
System.out.println(i+" "+j);
}
}
}
// 输出为:
// 0 0
// 0 1
// 0 2
// 1 0
// 1 1
// 1 2
// 2 0
// 2 1
// 2 2
import java.lang.Math;
public static void main(String[] args) {
Person[] pArray = new Person[5]; //创建长度为5的person数组用于装其子类对象
for (int i = 0;i < 5;i++){
int num = (int)(Math.random()*3); //随机生成1-3的整数,创建相对于的对象类型
switch (num){
case 1:pArray[i] = new Student();break;
case 2:pArray[i] = new Faculty();break;
case 3:pArray[i] = new Staff();break;
}
System.out.println(pArray[i].toString());
}
}
//方法一 new Random()
java.util.Random
public static void main(String[] args)
{
Random r = new Random(1);
for(int i=0 ; i<5 ; i++)
{
int ran1 = r.nextInt(100);
System.out.println(ran1);
}
}
//方法二 Math.random()
java.lang.Math
public static void main(String[] args)
{
int ran2 = (int) (Math.random()*100);
System.out.println(ran2);
}
封装
继承
多态
重载
相同函数名,不同参数和实现
覆盖(重写)
相同函数名、参数,不同实现
类的定义
[修饰符] class [类名] [extends 父类名][implements 接口名]{
类体部分
}
修饰符:public、final、abstract、void、static
extends:继承某个父类,默认继承自Object类
implements:实现某几个接口
类的成员变量定义
成员方法定义
抽象类
抽象方法
接口,类似于(纯虚类)
[访问控制符] interface 接口名{
抽象方法声明
成员变量声明
}
equals
getClass
toString
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Class类实现Java的反射特性
Class c = Class.forName("MyClass");
MyClass mc = (MyClass)c.newInstance();
s = num + "";
s = Integer.toString(num);
s = String.valueOf(num);
num = Integer.parseInt(s);
Integer.valueOf(s).intValue();
相同与区别
Vector用法
import java.util.*;
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector();
v.add(1);
v.add(3);
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(3)
System.out.println("Vector contains 3.");
System.out.println("Current capacity: " +
v.capacity());
Enumeration vEnum = v.elements();
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
}
ArrayList用法
import java.util.ArrayList;
public class RunoobTest {
public static void main(String[] args) {
ArrayList<String> sites = new ArrayList<String>();
sites.add("Google");
sites.add("Runoob");
sites.set(0,'Run'); //将第一个元素修改为Run
sites.remove(1); //删除第二个元素
System.out.println(sites);
}
}
// [Run]
异常的定义
指程序运行过程中出现的非正常现象,例如用户输入错误、除数为零、需要处理的文件不存在、数组下标越界等。
优势:
使完成正常功能的程序代码与进行异常处理的程序代码分开。
Java处理异常的两种方法:
异常的分类——Exception(异常)和Error(错误)
运行时异常
运行时异常都是RuntimeException类及其子类异常,如NullPointerException、IndexOutOfBoundsException等,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。
非运行时异常
非运行时异常是RuntimeException以外的异常,类型上都属于Exception类及其子类。如IOException、SQLException等以及用户自定义的Exception异常。对于这种异常,JAVA编译器强制要求我们必需对出现的这些异常进行catch并处理,否则程序就不能编译通过。所以,面对这种异常不管我们是否愿意,只能自己去写一大堆catch块去处理可能的异常。
异常类的常用函数(输出异常的基本信息)
直接捕获
public class CatchDemo{
public static void main(String[] a){
method(1);
method(2);
}
static void method(int i){
try{
if(i == 1){
int b = 3/0 //抛出异常ArithmeticException
}else if(i == 2){
int c[] = new int[3];
c[5] = 3; //抛出异常ArrayIndexOutOfBoundsException
}
}catch(ArithmeticException e){
System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
}
}
函数头抛出
public class CatchDemo{
public static void main(String[] a){
try{
method(1);
method(2);
}catch(ArithmeticException e){
System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
}
static void method(int i) throws ArithmeticException,ArrayIndexOutOfBoundsException{
if(i == 1){
int b = 3/0 //抛出异常ArithmeticException
}else if(i == 2){
int c[] = new int[3];
c[5] = 3; //抛出异常ArrayIndexOutOfBoundsException
}
}
}
class MyException extends Exception{
MyException(String s){
super(s);
}
}
if(age < 0){
throw new MyException("用户年龄不能小于0");
}
文件读写类
File类
构造方法:
File(String pathOrName);
File(String path,String name);
File(File dir,String name);
成员方法:
String getName() getPath() getParent() getAbsolutePath()
boolean renameTo(File newName)
boolean exists() canWrite() canRead()
long length()
使用FileInputStream和FileOutPutStream完成文件拷贝
void copy(String srcFile,String dstFile) throws Exception{
InputSteam input = new FileInputStream(srcFile);
OutputStream output = new FileOutputStream(dstFile);
byte[] buf = new byte[256];
int length = 0;
while((length = input.read(buf)) != -1){
output.write(buf,0,length);
}
output.flush();
input.close();
output.close();
}
FileReader和FileWriter完成文件拷贝
void copy(String srcFile,String dstFile) throws Exception{
FileReader reader = new FileReader(new File(srcFile));
FileWriter writer = new FileWriter(new File(dstFile));
char[] buf = new char[256];
int length = 0;
while((length = reader.read(buf)) != -1){
writer.write(buf,0,length);
}
writer.flush;
reader.close();
writer.close();
}
字节流转化成字符流(这样可以自定义文件的字符集)
void copy(String srcFile,String dstFile) throws Exception{
InputSteam input = new FileInputStream(srcFile);
OutputStream output = new FileOutputStream(dstFile);
Reader reader = new InputStreamReader(input,"GBK");
Writer writer = new OutputStreamWriter(outpu t,"GBK");
char[] buf = new char[256];
int length = 0;
while((length = reader.read(buf) != -1)){
writer.write(buf,0,length);
}
writer.flush;
reader.close();
writer.close();
}
FilterInputStream,FilterOutputStream
缓冲字符流:BufferedReader/BufferedWriter
优势
import java.io.*;
InputStream is = new FileInputStream("..."); //得到文件字节流
Reader r = new InputStreamReader(is,"GBK"); //封装成字符流
BufferedReader br = new BufferedReader(r); //封装成字符过滤流
//三合一
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("in.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("out.txt")));
String line = '';
while((line = br.readLine()) != null){
bw.write(line + "\n");
}
bw.flush();
br.close();
bw.close();
创建状态
Thread t = new Thread()
//处于创建状态的线程对象,只能作启动、终止线程操作(start()、stop())。
可运行状态
Thread t = new Thread();
t.start();
t.yield(); //让步,放弃当前CPU使用权,但马上竞争新的CPU
//start()方法产生线程运行所需要的系统资源,并将线程提交给Java的线程调度器,等待执行。
不可运行状态
Thread t = new Thread();
t.sleep(300) //休眠300ms,到时间后自动启动
t.wait(); //挂起,需要notify来唤醒
t.notify() //唤醒线程
死亡状态
Thread t = new Thread();
t.run(); //run方法结束之后,正常死亡
t.stop(); //非正常死亡
public class MyThread extends Thread{
@Override
public void run(){
//重写run方法
for(int i = 0;i < 10;i++){
System.out.println(i);
}
}
public static void main(String[] args){
//创建线程实例
MyThread myThread = new MyThread();
myThread.start(); //start方法会调用run()方法
}
}
public class MyThread implements Runnable{
@Override
public void run(){
//重写run方法
for(int i = 0;i < 10;i++){
System.out.println(i);
}
}
public static void main(String[] args){
Thread td = new Thread(new MyThread());
td.start();
}
}
class Cbank {
private static int s=1000; //银行存款
//使用synchronized保证资源同步
public synchronized static void sub(int m){
int temp = s;
temp = temp - m; //取钱之后的钱
try{
Thread.sleep((int)(1000*Math.random()));
}catch(InterruptedException e){ }
s= temp;
System.out.println("s = "+s);
}
}
class Customer extends Thread {
public void run(){
for(int i=1; i<=5; i++)
Cbank.sub(100); //取100块钱
}
}
//main class
class Thread {
public static void main(String args[]){
Customer c1 = new Customer();
Customer c2 = new Customer();
c1.start();
c2.start();
}
}
URL是Java提供的网络功能中最高级的一种,通过URL可以直接读写网络上的数据
URL的组成:http://61.135.169.125:80/img/baidu_sylogo1.gif
HTTP默认端口80,FTP默认端口21,HTTPS默认端口43
URL类的构造方法
URL类的构造方法 | 功能说明 |
---|---|
public URL(String str) | 使用URL字符串创建URL对象 |
public URL(String protocol,String host,String file) | 通过指定协议名、主机名、文件名,端口使用默认值,创建URL对象 |
public URL(String protocol,String host,String port,String file) | 通过指定协议名、主机名、文件名和端口号,创建URL对象 |
public URL(URL content,String str) | 通过在已知的URL路径上增加细节的办法创建URL对象 |
URL类的方法
URL 类 | 功能说明 |
---|---|
int getPort() | 获得端口号,如果端口没有设置,返回-1 |
String getProtocol() | 获得协议名,如果协议没有设置,返回null |
String getHost() | 获得主机名,如果主机没有设置,返回null |
String getFile() | 获得文件名,如果文件没有设置,返回null |
Boolean equals(Object obj) | 与指定的URL对象obj 进行比较,如果相同返回true,否则返回false |
Final OpenStream() | 获得一个输入流,若获取失败,则抛出一个java.io.Exception异常 |
String toString() | 将此URL对象转换为字符串的形式 |
使用URL类读取网页数据
URL数据-> InputStreamReader对象 -> BufferedReader对象
import java.net.*;
import java.io.*;
public class Network_1{
public static void main(String[] args) throws Exception{
URL hfut = new URL("http://www.baidu.com");
BufferedReader in = new BufferedReader(new InputStreamReader( hfut.openStream() ) );
String inputLine;
//打印输出HTML
while ( (inputLine = in.readLine() ) != null )
System.out.println(inputLine);
//关闭缓冲区
in.close();
}
}
URL对象-> URLConnection对象 -> InputStreamReader ->BufferedReader
import java.net.*;
import java.io.*;
public class Network_2 {
public static void main(String[] args) throws Exception {
URL hfut = new URL("http://www.baidu.com");
URLConnection uc = hfut.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader( uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
定义:
网络上运行的程序之间双向通信链路的最后终结点。
IP与端口的组合得出的套接字。
原理:
服务器端:Server
客户端:Client
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
// 创建服务器端实例server,设置端口80
try {
ServerSocket server = new ServerSocket(80);
} catch (IOException e) {
System.exit(1);
}
try {
//通过ServerSocket的方法accept自动创建Socket实例
Socket client = server.accept();
//通过PrintWriter实例将信息发送给客户端
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//通过BufferedReader接收客户端信息
BufferedReader in = new BufferedReader(new InputStreamReader
(client.getInputStream()));
} catch (IOException e) {
System.exit(1);
}
while (true) {
String line = in.readLine();
String len = line.length(); // 计算客户端发来信息长度
//告诉客户端发来的信息有多长
out.println("received string's length is: "+ strlen);
if(line.equalsIgnoreCase("Bye"))
break;
}
out.close();
in.close();
client.close();
server.close();
}
}
//client
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
try {
//实例化客户端,设置端口80,和本地IP
Socket client = new Socket("127.0.0.1", 80);
//通过PrintWriter实例将信息发送给服务器端
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//通过BufferedReader实例接收服务端信息
BufferedReader in = new BufferedReader(new InputStreamReader
(client.getInputStream()));
} catch (Exception e) {
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
while (true){
String line = stdIn.readLine();// 读取命令行输入的信息
out.println(line);// 将命令行内容发送给服务器端
if(line.equalsIgnoreCase("Bye"))
break;
}
out.close();
in.close();
stdIn.close();
}
}
定义:容器就是组件放置的地方。其本身可以看成是一个特殊的组件,只不过可以容纳其他的组件或容器。
四者关系:一般就用Frame(窗体)和Panel
布局方式(可以用途serLayout修改布局方式):
Label–文本
Label titleLabel = new Label("服务器设置");
titleLabel.setPreferredSize(new Dimension(380,30));
Button–按钮
Button sayButton = new Button("Say");
TextField–输入框
TextField portText = new TextField(); //输入框
startButton.addActionListener((e)->{
server = new Server(Integer.parseInt(portText.getText()),textArea);
});
TextArea–文本框
TextArea textArea = new TextArea();
textArea.setPreferredSize(new Dimension(380,100));
Choice–下拉框
//下拉选择框
Choice choice1 = new Choice();
choice1.add("下拉框1");
choice1.add("下拉框2");
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e){
// 按钮事件所进行的具体工作
}
}
事件类型 | 典型触发动作 |
---|---|
ActionEvent | 按钮、列表双击、单击菜单项目 |
KeyEvent | 键盘的输入 |
MouseEvent | 鼠标拖动、移动、单击、按下、释放或者进入、退出组件的事件 |
ComponentEvent | 组件被隐藏、移动、尺寸调整或变为不可见的事件 |
FocusEvent | 组件获得或失去焦点的事件 |
InputEvent | 复选框和列表项单击、控件的选择和可选菜单项的选择事件 |
TextEvent | 文本区域或者文本区域的值的改动 |
WindowEvent | 窗口激活、失去活动窗口、最小化、最小化、打开、关闭或者退出的事件 |
事件类型 | 典型触发动作 |
---|---|
ActionListener | 处理按钮、列表双击、单击菜单项目 |
KeyListener | 处理键盘的输入 |
MouseListener | 处理鼠标拖动、移动、单击、按下、释放或者进入、退出组件的事件 |
ComponentListener | 处理组件被隐藏、移动、尺寸调整或者变为不可见的事件 |
FocusListener | 处理组件获得或失去焦点的事件 |
TextListener | 处理文本区域或者文本区域的值的改动 |
WindowListener | 处理窗口激活、失去活动窗口、最小化、最小化、打开、关闭或者退出的事件 |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
myButtonFrame frm = new myButtonFrame("ActionEventTest");
frm.show(); //显示窗体
}
}
//设计窗口类
class myButtonFrame extends Frame{
JButton btn;
//构造函数
myButtonFrame(String s){
super(s);
this.setSize(200,120);
//创建按钮
btn = new JButton("按钮");
this.add(btn);
btn.addActionListener(new buttonListener());
}
//监听器类
class buttonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e){
System.out.println("你已经按下按钮了");
}
}
}