您的位置:首页 > 编程语言 > Java开发

Java 基础

2015-11-11 17:35 399 查看
windows上运行java,首先百度“jdk”下载最新的jdk,然后设置环境变量jdk****下的bin目录,然后在cmd里就可以执行java或者javac,java就是java虚拟机jvm,然后用javac *.java来编译java文件,生成了*.class文件,然后java * 来执行文件。

public class Hello {
public static void main(String args[]) {
System.out.println("Hello!");
}
}

其中main函数为程序的入口函数。一个java文件中只能有一个public class

public class Hello {
public static void main(String args[]) {
int a = 10;
int b = 20;
int result = a+b;
System.out.println("Result is " + result);
}
}


java中的比C多一个byte数据类型,-128~127,原有的char类型为两个字节,能存放汉字。然后 布尔类型是 boolean。

java虚拟机有内存回收机制,就算new的空间也会在没有对象指向的时候且内存空间不足的时候被释放。而C++则不会。

public class Hello {
public static void main(String args[]) {
Child ch1 = new Child();
Child ch2 = new Child();
ch1.add(12, "哈哈");
ch2.add(22, "嘿嘿");
System.out.println("总数是" + ch2.total);//直接引用输出
}
}

class Child {
int age;
String name;
static int total = 0;//静态变量所有的对象共同使用的同一个内存单元
public void add ( int age, String name ) {
this.age = age;
this.name = name;
this.total ++;
}
}
静态变量 static ,并且在类外能直接引用

public class Hello {
static int i = 1;
static {
i ++;
}
public static void main(String args[]) {
System.out.println(i);
}
}
静态变量和静态区域块,在进入主函数之前会提前放入内存块中。静态区域块中的函数只会执行一次,再次创造的对象不会再执行,只会执行构造函数了。

public class Hello {
public static void main(String args[]) {
Stu stu1 = new Stu(10, "小明", 500);
Stu stu2 = new Stu(11, "小红", 520);
System.out.println(Stu.getTotalFee());
}
}

class Stu {
int age;
String name;
static int totalFee = 0;
public Stu ( int age, String name, int Fee ) {
this.age = age;
this.name = name;
totalFee += Fee;
}

public static int getTotalFee () {
return totalFee;
}
}

类方法,又称静态方法,所有的对象共同可以调用,包括类名本身。同时,在静态方法里面无法访问非静态变量。非静态方法可以同时访问非静态变量和静态变量。这里跟C++类似。

四大类型(多种类型):

抽象:讲数据抽象成具体事物,比如 1 代表开始标志,2 代表结束标志 那么就定义1为“开始”,2为“结束”。

封装:我们把抽象出来的数据和对数据操作的操作封装在一起,数据保护在其内部。



继承:根据访问控制修饰符,允许使用或者不允许使用父类中的成员变量或成员函数。一个子类只能继承一个父类。以下是不同包通过 protected 子类继承父类

package firstproj;
import secondproj.*;

public class student1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Pupil a1 = new Pupil();
a1.pay(100);
a1.printfee();
}
}

class Pupil extends student3 {
public void pay(int fee1) {
this.job = fee1;
}
public void printfee () {
this.showfee1();
}
}
package secondproj;

public class student3 {
protected int job;
protected void showfee1() {
System.out.println(job + "\n");
}
}


重载:函数的名称相同,只要在传入的参数有任何地方不一样,都能形成重载,如果传入的参数一模一样(个数,类型顺序),就不能形成重载,重载和函数的返回类型无关。

覆盖(重写):子类中存在与其继承父类中相同名称的函数,则子类对象默认引用子类中的成员函数。1、其中子类成员函数的返回类型、参数、方法名称要和父类的一模一样;2、子类方法不能缩小父类方法的访问权限。

多态:一个公共引用可以通过一个方法实现多种状态的输出结果。

package demo1;

public class Demo1_1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Animal an = new Cat();
an.cry();
an = new Dog();
an.cry();
}

}

class Animal {
void cry () {
System.out.println("不知道怎么叫");
}
}

class Cat extends Animal {
void cry () {
System.out.println("猫叫");
}
}

class Dog extends Animal {
void cry () {
System.out.println("狗叫");
}
}


抽象类:1、抽象类可以没有抽象方法,有抽象方法必须要在抽象类里面;2、抽象类不能实例化(new一个对象);3、抽象方法不能在自己的抽象类中实现;4、子类继承抽象类时,若抽象类中有抽象方法,那么子类中一定要实现父类中所有的抽象方法。(还有很多细节)

package demo1;

public class Demo1_1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Animal an = new Cat();
an.cry();
an = new Dog();
an.cry();
}

}

abstract class Animal {
abstract void cry ();
}

class Cat extends Animal {
void cry () {
System.out.println("猫叫");
}
}

class Dog extends Animal {
void cry () {
System.out.println("狗叫");
}
}


接口:更加抽象的抽象类(首先,他是一个类,是一个跟抽象类有一点不同的类),一个子类可以继承多个接口,接口中不能有任何实现的方法以及成员变量。(还有很多细节)

package demo1;

public class Demo1_1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Animal an = new Cat();
an.cry();
}

}

interface Animal {
public void cry ();
}

class Cat implements Animal {
public void cry () {
System.out.println("猫叫");
}
}


final 关键字:相当于 c 中的 const 。

集合类:ArrayList。在定义的时候使用泛型可避免不必要的运行错误(编译却没错误)ArrayList<Clerk> al = new ArrayList<Clerk>();

package gather;

import java.util.*;/*集合类的包基本都在这里面*/

public class gather {

public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList al = new ArrayList();
System.out.println("al大小:"+al.size());
Clerk clerk1 = new Clerk("员工1",25, 1000);
Clerk clerk2 = new Clerk("员工2",31, 2000);
Clerk clerk3 = new Clerk("员工3",40, 3000);
al.add(clerk1);
al.add(clerk2);
al.add(clerk3);
System.out.println("al大小:"+al.size());
for ( int i = 0; i < al.size(); i ++ ) {
Clerk temp = (Clerk)al.get(i);
System.out.println("名字:"+temp.getName());
}
System.out.println("==删除员工2==");
al.remove(1);
for ( int i = 0; i < al.size(); i ++ ) {
Clerk temp = (Clerk)al.get(i);
System.out.println("名字:"+temp.getName());
}
System.out.println("==将员工2加回到序列1的位置==");
al.add(1, clerk2);
for ( int i = 0; i < al.size(); i ++ ) {
Clerk temp = (Clerk)al.get(i);
System.out.println("名字:"+temp.getName());
}
}

}

class Clerk {
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public float getSal() {
return sal;
}

public void setSal(float sal) {
this.sal = sal;
}

private String name;
private int age;
private float sal;

public Clerk ( String name, int age, float sal ) {
this.name = name;
this.age = age;
this.sal = sal;
}
}

ArrayList和Vector的区别:

Vector是同步的,线程安全的,ArrayList是异步的。

ArrayList与Vector都有一个初始的容量大小,当存储进它们里面的元素的个数超过了容量时,就需要增加ArrayList与Vector的存储空间,每次要增加存储空间时,不是只增加一个存储单元,而是增加多个存储单元,每次增加的存储单元的个数在内存空间利用与程序效率之间要取得一定的平衡。Vector默认增长为原来两倍,而ArrayList的增长策略在文档中没有明确规定(从源代码看到的是增长为原来的1.5倍)。ArrayList与Vector都可以设置初始的空间大小,Vector还可以设置增长的空间大小,而ArrayList没有提供设置增长空间的方法。

HashMap:用了上面的员工类

package gather;

import java.util.*;

public class hashMap {

public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap hm = new HashMap();
Clerk clerk1 = new Clerk("员工1",25, 1000);
Clerk clerk2 = new Clerk("员工2",31, 2000);
Clerk clerk3 = new Clerk("员工3",40, 3000);
hm.put("员工1", clerk1);
hm.put("员工2", clerk2);
hm.put("员工3", clerk3);/*放入一个同样的键值,之前的键值value就会被覆盖*/

if ( hm.containsKey("员工2")) {
System.out.println("有该员工。");
Clerk temp = (Clerk)hm.get("员工2");
System.out.println("年龄:"+temp.getAge());
}
else {
System.out.println("没有该员工。");
}
/*HashMap遍历*/
Iterator it = hm.keySet().iterator();
while ( it.hasNext() ) {/*理论上内容是无序排列的,但是貌似像栈一样是先进后出*/
String key = it.next().toString();
Clerk temp = (Clerk)hm.get(key);
System.out.println("工资:"+temp.getSal());
}
}

}


HashMap和HashTable的区别:
Hashtable的方法是同步的,而HashMap的方法不是。这就意味着,虽然你可以不用采取任何特殊的行为就可以在一个多线程的应用程序中用一个Hashtable,但你必须同样地为一个HashMap提供外同步。一个方便的方法就是利用Collections类的静态的synchronizedMap()方法,它创建一个线程安全的Map对象,并把它作为一个封装的对象来返回。这个对象的方法可以让你同步访问潜在的HashMap。这么做的结果就是当你不需要同步时,你不能切断Hashtable中的同步(比如在一个单线程的应用程序中),而且同步增加了很多处理费用。

泛型

java 异常及异常处理

package exception;

import java.io.*;

public class exception {

public static void main(String[] args) {
// TODO Auto-generated method stub
//FileReader fr = new FileReader("d:\\aa.txt");//提示文件没找到的异常,这种属于检查类异常
//int a = 4/0;//运行异常
try {
FileReader fr = new FileReader("d:\\aa.txt");//提示文件没找到的异常,这种属于检查类异常
} catch (Exception e) {//捕获异常
// TODO: handle exception
e.printStackTrace();
} finally {//一般情况下,抛出异常之后还会执行的代码段
}
}
}


java 多线程处理 继承Thread类

package busy.thread;

public class Test_thread {

public static void main(String[] args) {
// TODO Auto-generated method stub
Cat cat = new Cat();
cat.start();//启动一个线程,会导致run函数的运行
}
}

class Cat extends Thread {
//重写run函数
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello!");
}
}
}


java 多线程处理 继承Runnable接口(处理java的单继承情况)

package busy.thread;

public class Test_thread {

public static void main(String[] args) {
// TODO Auto-generated method stub
Cat cat = new Cat();
Thread t = new Thread(cat);//这样没有继承Thread类就没有start方法
t.start();
}
}

class Cat implements Runnable {
//重写run函数
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello!");
}
}
}


java 线程同步(对象同步锁)

package busy.thread;

public class Test_thread {

public static void main(String[] args) {
// TODO Auto-generated method stub
TicketWindow tw1 = new TicketWindow();
Thread t1 = new Thread(tw1);
Thread t2 = new Thread(tw1);
Thread t3 = new Thread(tw1);
t1.start();
t2.start();
t3.start();
}
}

class TicketWindow implements Runnable {

private int nums = 2000;
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized(this) {//对象锁synchronized(Object)里面放其他的对象也可以,只是用这个对象做一个标志位
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(nums > 0) {
System.out.println(Thread.currentThread().getName() + "正在售出 " + nums + "票");
nums --;
}else {
break;
}
}
}
}

}


java IO文件操作

package busy.filestream;

import java.io.*;

public class Filestream {

public static void main(String[] args) {
// TODO Auto-generated method stub
File fs = new File("E:\\1java-temp\\test.txt");
System.out.println("文件路径:" + fs.getPath());//文件路径
System.out.println("文件大小:" + fs.length());//文件大小(字节)

File fs1 = new File("E:\\1java-temp\\test2.txt");//创建文件
if (!fs1.exists()) {
try {
fs1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
System.out.println("文件存在,无法创建!");
}

File fs2 = new File("E:/1java-temp/newFile");//创建文件夹
if (fs2.isDirectory()) {
System.out.println("文件夹存在");
}else {
fs2.mkdir();
}

File fs3 = new File("E:\\");
if( fs3.isDirectory()) {
File lists[] = fs3.listFiles();
for(int i = 0; i < lists.length; i ++) {
System.out.println("文件名:"+lists[i].getName());
}
}

File fs4 = new File("E:\\1java-temp\\test.txt");//读文件(这是字节流,还有字符流和字符串流)
FileInputStream fsm = null;                 //FileReader(字符流),BufferReader(字符串流)
try {
fsm = new FileInputStream(fs4);
byte []bytes = new byte[1024];
int n = 0;//实际读取到的字节数
while((n = fsm.read(bytes)) != -1) {
String str = new String(bytes, 0, n);
System.out.println(str);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fsm.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

File fs5 = new File("E:\\1java-temp\\test3.txt");//写文件
FileOutputStream fsom = null;
try {
fsom = new FileOutputStream(fs5);
String str = "一二三四五";
fsom.write(str.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fsom.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

File fs6 = new File("E:\\1java-temp\\img.jpg");//图片拷贝
File fs7 = new File("E:\\1java-temp\\img1.jpg");
FileInputStream fsm1 = null;
FileOutputStream fsom1 = null;
try {
fsm1 = new FileInputStream(fs6);
fsom1 = new FileOutputStream(fs7);
byte buf[] = new byte[1024];
int n = 0;
while( (n = fsm1.read(buf)) != -1) {
fsom1.write(buf);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fsm1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fsom1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: