赞
踩
跨平台、适合于分布式计算环境的纯面向对象语言,Java是一种编程语言, 又是一种平台和规范
语言特点:(JAVA是一种“简单、面向对象、分布式、解释型、健壮、安全、体系结构中立、可移植、高性能和动态”的编程语言)
1)简单(完全面向对象的,它是最容易学习的面向对象的编程语言之一,同时它还提供了大量可重用的类库,Java的简单性是以增加系统的复杂性为代价的)
2)面向对象(支持封装、继承、多态)
3)分布式(数据分布支持(通过Java的URL类可以访问网上的各类信息资源,访问方式完全类似于本地文件系统)、操作分布支持(通过在web页面中的小应用程序(Applet)等将计算从服务器分布至客户机,避免网络拥挤,提高系统效率))
4)半编译、半解释(Java源程序经编译器编译后产生字节码(bytecode),Java解释器解释执行字节码,优点: 兼具编译执行的效率优势和解释执行的灵活性; 提高了应用程序的可移植性:源程序、中间代码)
5)平台无关性/可移植性(程序不经过修改而在不同的硬件或软件平台上运行的特性,Java可移植性源于两方面: Java的半编译、半解释的特征; Java采用标准的独立于硬件平台的数据类型)
6)安全性(Java的内存分配和引用模型对于程序员透明,完全由底层的运行系统控制。在语言和运行环境中引入了多级安全措施:内存布局与C、 C++不同,不是由编译器决定,而是运行系统根据所在的硬件平台的特性决定; 取消了C、C++的指针,JAVA编译器通过符号指针来引用内存,由JAVA运行系统在运行时将符号指针具体解释为实际的内存地址。字节码验证:运行系统引入字节码验证器,其中包含简单的规则验证程序,以确保遵循规则)
7)多线程
8)健壮(Java致力于检查程序在编译和运行时的错误。 运行错误的处理机制 内存的垃圾收集机制 不使用指针操作)
开发与运行Java程序需要经过的三个主要步骤为:编辑源程序、编译生成字节码、解释运行字节码
• It translates a Java program into byte-code.(Byte-code is the machine language for a hypothetical computer (or interpreter) called the Java Virtual Machine, a byte-code program is easy to translate into machine language for any particular computer.)
• A program called an interpreter translates each byte-code instruction, executing the resulting machine-language instructions on the particular computer before translating the next byte-code instruction.
• Most Java programs today are executed using a Just-In-Time or JIT compiler in which byte-code is compiled as needed and stored for later reuse without needing to be re-compiled.
• Use the compiler to translate the Java program into bytecode (done using the javac command)
· the byte-code can be used on any computer with a byte-code interpreter and without a need to recompile, so it can be sent over the Internet and use anywhere in the world. So this makes Java suitable for Internet applications.
运行环境的种类: JAVA Application (JAVA解释器)、 JAVA Applet(JAVA兼容的Web浏览器)
JDK工具:
appletviewer: Applets是被嵌入在网页里的Java程序,可以用Web浏览器运行appletsappletviewer 可运行applets而不必运行 Web浏览器。 用法: appletviewer < .HTML文件的URL>
javap反汇编程序: javap反汇编程序可以从字节码文件恢复 java 源代码。 用法: javap <.class文件列表> 文件名由空格分隔
• JavaFX is a set of packages that allow Java programmers to create graphics and media applications
JavaFX是最新的图形化工具包,程序员可以创建富图形化和富媒体应用程序
在Java的基本数据类型中,char型采用Unicode编码方案,每个Unicode码占用 2
字节内存空间。
不是关键字:sizeof,字面常量:true、false、null
标识符:
若想对比两个对象的实际内容是否相同,使用方法equals(),但不适用于自己创建的类!
若为String,则使用s1.compareTo(s2)
Float类型的数据其最后一个字符之后需加入“F”或“f”,如果数据其最后一个字符之后没有“F”或“f”,则默认为double类型的数值。
reference 类型:数组Array ,类 classe,接口interface。reference 类型的变量可简单认为是所引用对象的内存地址。
String不是基本数据!
创建字符串变量:
- S=new String(“abc”);
- S=“abc”;
- String tomName=String(“tom”);
- String(char a[]);//通过数组创建字符串对象
- String(char a[],int startIndex,int count);//截取数组元素的一部分来创建字符串对象
- s1.length();//获取字符串的长度
- charAt(int index);//获得字符串指定位置的字符
- //比较
- String s1=“abc”,s2=“abc”,s3=“Abc”;
- s1.equals(s2); //true
- s1.equals(s3); //false
- s1==s2; //false,引用
- //equalsIgnoreCase(String s),比较时忽略大小写
- String s1=“abc”,s2=“Abc” ;
- s1. equalsIgnoreCase(s2); //true
- //public boolean startsWith(String s):判断当前字符串的前缀是否含有字符串s
- String s1=“220123456”,s2=”210654321”;
- s1. startsWith(“220”); //true
- s2. startsWith(“220”); //false
- //public boolean endsWith(String s):判断当前字符串的后缀是否含有字符串s
- s1. endsWith(“456”); //true
- //public int compareTo(String s):按字典顺序比较当前字符串和s
- //public int compareToIgnoreCase(String s):比较时忽略大小写
- s1.compareTo(s2);
- //public int indexOf(String s)返回第一次找到时的下标,如果没有找到,则返回-1
- //public int indexOf(String s, int strartPoint)从指定的下标开始找子串,返回第一次找到时的下标,找不到则返回-1
- String s=“I am a good student”;
- S.indexOf(“a”); //=2
- S.indexOf(“a”,3); //=5
- S.indexOf(“k”,2); //=-1
- //字符串的截取(求子串)
- "unhappy".substring(2);// returns "happy"
- "Harbison".substring(3);// returns "bison“
- "emptiness".substring(9);// returns "" (an empty string)
- "hamburger".substring(4, 8);// returns "urge"
- "smiles".substring(1, 5);// returns "mile"
- //拼接两个字符串,并返回一个新字符串,源字符串不会被修改
- String s1 = "ABC";
- String s2 = "XYZ";
- s1 = s1.concat(s2); // s1 = s1 + s2;
- //替换public String replace(char oldChar, char newChar)
- String s1 = "mesquite in your cellar";
- s1.replace('e', 'o');// returns "mosquito in your collar"
- //public String replaceAll(String regex, String replacement)
- String s1 = "opq@#$";
- s1.replaceAll(“[a-z]”,”123”);// returns “123123123@#$”
- //返回前后没有空格的字符串public String trim()
- "Java ".trim();//"Java"
- //字符串与相应数值的相互转化public static int parseInt(String s)
- int i=Integer.parseInt(“123”);
- public static float Float.parseFloat(String s)
- public static double Double.parseDouble(String s)
- //通过String类的静态(static)成员方法valueOf(…)转为String类型
- public String valueOf(byte n)
- public String valueOf(int n)
- public String valueOf(long n)
- public String valueOf(float n)
- public String valueOf(double n)
- String str=String.valueOf(12313.9876);
- Float x=123.987f;
- String s=String.valueOf(x);
- //对象还可以通过方法toString转化成字符串
- Date date=new Date();
- System.out.println(date.toString());//Sat Oct 04 21:10:48 CST 2007

求String类对象长度:s.length()//这里有()!!
在android系统下,默认是UTF8编码,一个中文字符通常相当于3个字节,而gb2312下一个中文相当于2字节。把JVM内存中unicode形式的String按encoding指定的编码,转成字节流。这种情况下可采取以下办法:
- byte[] byBuffer = new byte[200];
- String strInput="我是字符串";
- byBuffer= strInput.getBytes("gb2312");
JVM内部的String,Char都是用unicode存储(没有任何特殊编码)
- buf1 = new StringBuffer();//创建空的StringBuffer对象容量为16字符
- buf2 = new StringBuffer( capacity );//创建空的StringBuffer对象指定容量大小
- buf3 = new StringBuffer( myString );//创建含有相应字符序列的StringBuffer对象容量为myString.length() + 16
- //实例
- StringBuffer b = new StringBuffer("hello");
- import java.util.Scanner;
- //Scanner Scanner_Object_Name = new Scanner(System.in);
- Scanner Keyboard = new Scanner(System.in);
-
- int n1 = keyboard.nextInt();//读入int
- String s1 = keyboard.next();//读入String
- String sentence = keyboard.nextLine();//读入一行
基本概念:事物的属性或特性可以用变量来表示,行为或功能用方法来反应。
类是同种对象的集合与抽象:在面向对象的程序设计中,定义类的概念来表述同种对象的公共属性和特点。 类是一种抽象的数据类型,它是具有一定共性的对象的抽象,而属于类的某一对象则被称为是类的一个实例,是类的一次实例化的结果。
面向对象的程序设计方法就是将客观事物抽象成为“类”,并通过类的“继承”实现软件的可扩充性和可重用性。
声明对象:声明对象的名字和类型,用类名来说明对象的类型。 格式:type name
说明: 声明对象的规则与变量声明规则相同,但对象变量是引用类型; 在java里类和接口都可以作为数据类型来使用; 对象声明通知编译器name将用来引用type类型的变量 对象声明并不创建新的对象。操作符new通过为新对象分配存储空间来实例化类
System.gc( ); // 申请立即回收垃圾
static关键字/类成员与实例成员:在类中声明一个变量或方法时,可指定它为实力成员或类成员。用static修饰的是类成员(类变量oe类方法)
类变量与实例变量的区别:1)运行时系统在首次遇到类变量时就为类变量分配存储空间;而当创建类的实例对象时才为实例变量分配存储空间。2)不管有多少类的实例,类变量只有一份拷贝,即所有实例共享相同的类变量;而每个实例对象都有自己的实例变量。3)实例变量只能通过对象来访问,而类变量既可以通过类名来访问,也可以通过实例对象来访问。
在该类所有实例之间是共享的。在加载该类时,只分配 一次空间,并初始化。可用来在实例之间进行通信或跟踪该类实例的数目。(e.g.用count++来计数)
类方法与实例方法的区别:1)实例方法既能访问当前对象的实例变量也能访问类变量;类方法只能访问类变量而不能访问实例变量。2)实例方法只能由实例对象来调用而类方法既可以由实例对象调用也可以由类名直接调用。
Java总是会在尝试使用自动类型转换之前使用重载。如果Java可以找到一个能够匹配引元类型的方法定义,就会使用这个定义。Java尝试寻找参数类型与方法调用中的引元精确匹配的方法名定义,直至尝试失败之后才会尝试方法引元的自动类型转换。(先找是否有重载函数再取进行自动类型转换)
default(缺省访问,包范围的): 如果没有给定修饰符,那就是default或friendly(友元)的(它不是java的关键字)。拥有缺省修饰符的类、变量或方法对同一个包里的所有类来说都是可访问的。
获取数组长度:c.length(注意没有()),c.length是final变量,不能对它 再次赋值
每个数组元素是对象的引用,还需要继续创建对象才可以使用。
数组的初始化语句创建数组 int[ ] n = { 10, 20, 30, 40, 50 };
·对基本数据类型:
- int[] nums;
- nums = new int[3];
- nums[0] = 1;
- nums[1] = 2;
- nums[2] = 3;
·对非基本数据类型:
- MyDate[] dates;
- dates = new MyDate[ 3];
- dates[ 0] = new MyDate( 22, 7, 1964);
- dates[ 1] = new MyDate( 1, 1, 2000);
- dates[ 2] = new MyDate( 22, 12, 1964);
- MyDate[] dates = {
- new MyDate( 22, 7, 1964),
- new MyDate( 1, 1, 2000),
- new MyDate( 22, 12, 1964) };
当指定数组参数时,只需要给出数组的基类型,但不需要指定数组的长度。
- double[] a = new double[10]
- double[] b = new double[30]
- SampleClass.incrementArrayBy2(a);
- SampleClass.incrementArrayBy2(b);
多维数组定义方式:
- int [][] intArray;
- int[][][] a2;
分配内存空间:
- int[][] a = new int[2][3];//直接为每一维分配空间
- int twoDim [][] = new int [][ 4]; //error
- //分别为每一维分配空间
- int[][] a = new int[2][ ];
- a[0] = new int[3];
- a[1] = new int[3];
- //可以为每行设置为空间大小不同的数组
- a[0] = new int[3];
- a[1] = new int[5];
初始化:
- int a[][] = {{2,3}, {1,5}, {3,4}};
- double[ ][ ] c =
- {
- {1.0, 2.0, 3.0, 4.0},
- {0.0, 1.0, 0.0, 0.0},
- {0.0, 0.0, 1.0, 0.0}
- };
数组数据的复制,通过拷贝数组的函数
- System.arrayCopy(Object source, int srcIndex, Object dest, int destIndex, int length)
- public class ArrayCopyDemo {
- public static void main(String[] args) {
- char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n',
- 'a', 't', 'e', 'd' };
- char[] copyTo = new char[7];
-
- System.arraycopy(copyFrom, 2, copyTo, 0, 7);
- System.out.println(new String(copyTo));
- }
- }
类java.lang.Object处于类层次树的根部,其他所有的类都直接或间接地为它的子类
抽象类中不一定要包含abstract方法,但是,一旦某个类中包含了abstract方法,则这个类必须声明为abstract类。
使用多态进行程序设计的核心技术之一是使用上转型对象,即将abstract类声明对象作为其子类的上转型对象,那么这个上转型对象就可以调用子类重写的方法。 所谓面向抽象编程,是指当设计某种重要的类时,不让该类面向具体的类,而是面向抽象类,即所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。
- //Geometry.java
- public abstract class Geometry { //如果使用接口需用interface来定义Geometry。
- public abstract double getArea();
- }
- Circle.java
- public class Circle extends Geometry {
- double r;
- Circle(double r) {
- this.r=r;
- }
- public double getArea() {
- return(3.14*r*r);
- }
- }
-
- //Rectangle.java
- public class Rectangle extends Geometry {
- double a,b;
- Rectangle(double a,double b) {
- this.a=a; this.b=b;
- }
- public double getArea() {
- return a*b;
- }
- }
-
- //Pillar.java
- public class Pillar {
- Geometry bottom; //bottom是抽象类Geometry声明的变量
- double height;
- Pillar (Geometry bottom,double height) {
- this.bottom=bottom; this.height=height;
- }
- public double getVolume() {
- return bottom.getArea()*height; //bottom可以调用子类重写的getArea方法
- }
- }
-
- //Application.java
- public class Application{
- public static void main(String args[]){
- Pillar pillar;
- Geometry bottom;
- bottom=new Rectangle(12,22);
- pillar =new Pillar (bottom,58); //pillar是具有矩形底的柱体
- System.out.println("矩形底的柱体的体积"+pillar.getVolume());
- bottom=new Circle(10);
- pillar =new Pillar (bottom,58); //pillar是具有圆形底的柱体
- System.out.println("圆形底的柱体的体积"+pillar.getVolume());
- }
- }

必须实现接口中定义的所有方法。 如果一个类声明实现一个接口,但没有实现接口中的所有方法,那么这个类必须是abstract类.
接口可以作为一种引用类型来使用,所以可以象其它类型的一样使用。把接口作为一种数据类型可以不需要了解对象所对应的具体的类,而着重于它的交互接口 使用者关注的是对象所实现(或暴露)的接口(能力)而不是目标对象本身。
- interface ShowInfo{
- void showBrand(String s);
- }
- class TV implements ShowInfo{
- public void showBrand(String s){
- System.out.printf(s);
- }
- }
- class PC implements ShowInfo{
- public void showBrand(String s){
- System.out.printf(s);
- }
- }
- public class Exam{
- public static void main(String args[]){
- ShowInfo si;
- si = new TV();
- si.showBrand(“索尼牌电视机”); //接口回调
- si = new PC();
- si. showBrand(“DELL PC”); //接口回调
- }
- }

在接口类中,对象只能调用接口中的方法,不能使用继承类的方法,若要使用,则需要进行强制类型转换。
什么是异常(Exception)(在其他书中,也称例外)? 异常(Exception)是正常程序流程所不能处理或没有处理的异常情况或异常事件。
格式:
在try语句块中包含可能会产生异常的语句
紧接着若干个catch语句块,进行异常处理
catch语句块与finally语句块至少存在一个
- try
- {
- // code that may throw exceptions
- }
- catch (ExceptionType ref)
- {
- //exception handling code
- }
- finally
- {
- // …
- }
常见异常:内存耗尽、数组下标越界、除数为0、非法的参数(方法的参数)
- public class ExceptionMethods {
- public static void main(String[] args) {
- try {
- throw new Exception("Here's my Exception");
- } catch(Exception e) {
- System.out.println("Caught Exception");
- System.out.println("e.getMessage(): " + e.getMessage());
- System.out.println("e.toString(): " + e.toString());
- System.out.println("e.printStackTrace():");
- e.printStackTrace();
- }
- }
- }
用户也可自定义异常类来处理异常; 自定义异常类是Exception类的子类,可包含普通类的内容。
当程序运行中发生异常时,异常处理机制将按以下步骤处理: 1、产生异常对象并中断当前正在执行的代码,抛出异常对象。 2、自动按程序中的catch的编写顺序查找“最接近的”异常匹配。一旦找到就认为异常已经得到控制,不再进行进一步查找。这个匹配不需要非常精确,子类对象可以与父类的catch相匹配。 3、若有匹配则执行相应的处理代码,然后继续执行本try块之外的其他程序。否则这个没有被程序捕获的异常将由缺省处理程序处理,缺省处理程序将显示异常的字符串、异常发生位置等信息,终止整个程序的执行并退出。
catch进入过一次后面的都会忽略掉
try、catch中有return时,也会执行finally。return时,要注意返回值的类型,是否受到finally中代码的影响。
finally中有return时,会直接在finally中退出,导致try、catch中的return失效。在执行完finally的return之后,就不会再返回try中的return值。
- public class Demo8 {
- //引用数据类型
- //最终返回结果是finally的结果,方法在处理返回值的时候finally块执行
- public static void main(String[] args) {
- Person p = ha();
- System.out.println(p.age);
-
- }
- public static Person ha() {
- Person p = new Person();
- try {
- p.age = 18;
- return p;
- } catch (Exception e) {
- return null;
-
- } finally {
- p.age = 28;
- }
-
- }
- static class Person{
- int age;
- }
- }//28

- public int catch1() {
- int i = 1;
- try{
- i++;
- int x = i / 0 ;
- }catch (Exception e) {
- i++;
- return i;
- }finally {
- i++;
- }
- return i;
- }//catch中会先执行return前的代码,然后暂时保存需要return的信息,再执行finally中的代码,最后再通过return返回之前保存的信息。所以,这里方法返回的值是try、catch中累积计算后的3,而非finally中计算后的4。
- public int catch1() {
- int i = 1;
- try{
- i++;
- return i;
- }catch (Exception e) {
- i++;
- }finally {
- i++;
- return i;
- }
- }//3
- static void createException() {
- throw new ArrayIndexOutOfBoundsException();
- }
-
- static void method() {
- try {
- createException();
- System.out.print('a');
- } catch (ArithmeticException e) {
- System.out.print('b');
- } finally {
- System.out.print('c');
- }
- System.out.print('d');
- }
- }//cmn

- class TestException {
- public static void main(String[] args) {
- try {
- method();
- } catch (Exception e) {
- System.out.print('m');
- }
- System.out.println('n');
- }
-
- static void createException() {
- throw new ArrayIndexOutOfBoundsException();
- }
-
- static void method() {
- try {
- createException();
- System.out.print('a');
- } catch (ArrayIndexOutOfBoundsException e) {
-
- System.out.print('b');
- } finally {
- System.out.print('c');
- }
- System.out.print('d');
- }
- }//bcdn

- class TestException {
- public static void main(String[] args) {
- try {
- method();
- } catch (Exception e) {
- System.out.print('m');
- }
- System.out.println('n');
- }
-
- static void createException() {
- throw new ArrayIndexOutOfBoundsException();
- }
-
- static void method() {
- try {
- createException();
- System.out.print('a');
- } catch (ArithmeticException e) {
-
- System.out.print('b');
- } finally {
- System.out.print('c');
- }
- System.out.print('d');
- }
- }//cmn

FileOutputStream 在写文件内容时,若目标文件已存在,没有警告信息
File的实例对象可以判断出文件是否存在 提供警告信息,或改变打开文件方式
- //文件流的建立
- FileInputStream in=new FileInputStream(fp);
- FileOutputStream out=new FileOutputStream(fp);
- //文件拷贝 file1->file2
- import java.io.*;
- public class filestream{
- public static void main(String args[]){
- try{
- File inFile=new File("file1.txt");
- File outFile=new File("file2.txt");
- FileInputStream fis=new FileInputStream(inFile);
- FileOutputStream fos=new FileOutputStream(outFile);
- int c;
- while((c=fis.read())!=-1) fos.write(c); //核心代码
- fis.close(); fos.close();
- }
- catch(FileNotFoundException e) {
- System.out.println("FileStreamsTest: "+e);
- }
- catch(IOException e) {
- System.err.println("FileStreamsTest: "+e);
- }
- }
- }

- //拷贝文件
- import java.io.*;
- public class Copy {
- public static void main(String[] args) throws IOException {
- File inputFile = new File("farrago.txt");
- File outputFile = new File("outagain.txt");
- FileReader in = new FileReader(inputFile);
- FileWriter out = new FileWriter(outputFile);
- int c;
- while ((c = in.read()) != -1)
- out.write(c);
- in.close();
- out.close();
- }
- }
- //创建File类
- myFile = new File("myfile.txt");
- File myDir = new File("MyDocs");
- myFile = new File( myDir, "myfile.txt");
- File f2 = new File("/etc", "passwd");
- //如果要读入类的话要implemtnts Serializable
- public class Species implements Serializable{}
-
- public class ClassObjectIODemo
- {
- public static void main(String[] args)
- {
- ObjectOutputStream outputStream = null;
- ObjectInputStream inputStream = null;
- String filename = "species.records";
-
- try
- {
- outputStream = new ObjectOutputStream(new FileOutStream(filename));
- outputStream.writeObject(Species s);
- readOne = (Species)inputStream.readObject();//注意强制转换
- }catch(IOException e){
- System.out.println("Errpr````");
- }
- }
- }

可提高程序代码的复用性
减少数据的类型转换,以提高代码的运行效率 --在编译时强制使用正确的数据类型
通过给类或接口增加类型参数实现
ArrayList:采用可变大小的数组实现List接口,并提供了访问数组大小的方法。ArrayList对象会随着元素的增加其容器自动扩大。该类是非线程同步的,3种List效率最高也最常用。
- import java.util.Scanner;
-
- public class ArrayListDemo
- {
- public static void main(String[] args){
- ArrayList<String> toDoList = new ArrayList<Atring>();
- System.out.println("Enter items for the list, when prompted.");
- bool done = false;
- Scanner keyboard = new Scanner(Syatem.in);
- while(!done)
- {
- System.out.print("Type an entry:");
- String entry = keyboard.nextLine();
- toDoList.add(entry);
- System.out.print("More item for the list?");
- String ans = keyboard.nextLine();
- if(!ans.equalsIgnoreCase("yes")) done = true;
- }
- System.out.println("The list contains:");
- int listSize = toDoList.size();
- for(int position = 0; position<listSize; position++) System.out.println(toDoList.get(position));
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。