源代码经过编译器编译后会生成一个字节码文件,字节码文件是一种二进制的类文件,它的内容是JVM的指令,而不是像C、C++经由编译器直接生成机器码,因此字节码文件不能被系统直接执行,而是需要虚拟机解释执行。
每个应用程序只有一个main()
函数,Java虚拟机启动执行时调用main()
,main()
是应用程序的起点。
.jar文件,manifest指定了哪个文件中有main()
方法。
public class HelloWorld {
public static void main(String[] args){
int x = 3;
double d = Math.random();
String name = "Nicholas";
System.out.println("x:"+x);
System.out.println("d:"+d);
System.out.println("name:"+name);
System.out.println("--------------------");
String[] words = {"hello","world"};
System.out.println("words.length:"+words.length);
System.out.println("words[0]:"+words[0]);
System.out.println("words[1]:"+words[1]);
System.out.println("--------------------");
double a = 12.3;
int b = (int) a;
System.out.println("a:"+a);
System.out.println("b:"+b);
double i = 56.7;
int j = (int) i;
System.out.println("i:"+i);
System.out.println("j:"+j);
}
}
数据类型 | 说明 | 对应的包装类 |
---|---|---|
boolean |
true 或false |
Boolean |
char |
16位(0 ~ 216-1,即 0 ~ 65535) | Character |
byte |
8位( -27 ~ 27-1,即-128 ~ 127) | Byte |
short |
16位(-215 ~ 215-1,即-32768 ~ 32767) | Short |
int |
32位(-231 ~ 231-1) | Integer |
long |
64位(-很大 ~ +很大) | Long |
float |
32位 | Float |
double |
64位 | Double |
public class Test {
public static void main(String[] args){
int x = 28;
Integer wrapper = new Integer(x);
int unWrapper = wrapper.intValue();
}
}
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
System.out.println(list.get(0));
System.out.println(list.get(1));
}
}
Integer.parseInt()
Double.parseDouble()
new Boolean("false").booleanValue()
Integer.toString()
Double.toString()
public class Test {
public static void main(String[] args){
String s = "42";
int i = Integer.parseInt(s);
String s2 = Integer.toString(i);
String str = "3.14";
double d = Double.parseDouble(str);
String str2 = Double.toString(d);
String string = "true";
boolean b = new Boolean(string).booleanValue();
}
}
String.format(格式,数值)
第一个参数是格式化串,第二个参数是需要被格式化的数值。
String.format("%,d",100000000)
%,d
这种格式将数值100000000
格式化。%
代表需要被格式化的数值,,d
意思是用逗号分隔这个数值,所以String.format("%,d",100000000)
的结果是100,000,000
。String.format("I have %.2f bugs to fix",1234.5678)
%.2f
将数值1234.5678
格式化。%
代表需要被格式化的数值,.2f
意思是小数点后保留两位,所以String.format("I have %.2f bugs to fix",1234.5678)
的结果是I have 1234.57 bugs to fix
。String.format("I have %,.2f bugs to fix",1234.5678)
%,.2f
将数值1234.5678
格式化。%
代表需要被格式化的数值,,.2f
意思是整数部分用逗号分隔,小数点后保留两位,所以String.format("I have %,.2f bugs to fix",1234.5678)
的结果是I have 1,234.57 bugs to fix
。格式化指令 | 说明 |
---|---|
%d |
被格式化的值的类型必须与int 兼容 |
%f |
被格式化的值的类型必须是float /double 中任一种 |
%x |
被格式化的值的类型必须是byte /short /int /long /BigInteger 中任一种 |
%c |
被格式化的值的类型必须是byte /short /int /long 中任一种 |
public class Test {
public static void main(String[] args){
System.out.println(String.format("%,.1f",42.000));
System.out.println(String.format("0042.0"));
System.out.println(String.format("%,6.1f",42.000));
}
}
public class Test {
public static void main(String[] args){
int i = 20456654;
double j = 100567890.248907;
System.out.println(String.format("The rank of %,d out of %,.2f",i,j));
}
}
格式化指令 | 说明 |
---|---|
%tc |
完整的日期和时间 |
%tr |
时间 |
%tA |
周 |
%tB |
月 |
%td |
日 |
import java.util.Date;
public class Test {
public static void main(String[] args){
Date d = new Date();
System.out.println(d);
System.out.println(String.format("%tc",d));
System.out.println(String.format("%tr",d));
System.out.println(String.format("%tA",d));
System.out.println(String.format("%tB",d));
System.out.println(String.format("%td",d));
System.out.println(String.format("%tA,%tB,%td",d,d,d));
System.out.println(String.format("%tA,%,d));
}
}
对象,有自己的实例变量和方法。
创建的对象会保存在堆中。当某个对象被Java虚拟机察觉到不再被使用,该对象会被标识为可回收。内存不足时垃圾收集器会启动以清理垃圾、回收空间。
引用变量,可以理解成 指向对象的指针。
对于任何一台Java虚拟机而言,所有引用变量的大小都是一样的,不论它实际引用的对象大小如何。
数组也是一个对象。
public class Helloworld {
public static void main(String[] args){
int[] nums = new int[3];
nums[0] = 10;
nums[1] = 20;
nums[2] = 30;
for(int i=0;i<nums.length;i++){
System.out.println(nums[i]);
}
}
}
public class Dog{
public void bark(){
Hippo hippo = new Hippo();
System.out.println("dog didn't know hippo");
}
}
public class Hippo{
}
public class Test {
public static void main(String[] args){
Dog dog = new Dog();
dog.bark();
}
}
bark()
方法一调用完,局部变量hippo
就会被销毁。
public class Dog{
public void bark(){
Hippo hippo = new Hippo();
hippo = new Hippo();
System.out.println("dog didn't know hippo");
}
}
第一个创建的Hippo
对象会在hippo
被重新赋值时销毁。
null
public class Dog{
public void bark(){
Hippo hippo = new Hippo();
hippo = null;
System.out.println("dog didn't know hippo");
}
}
hippo
被置为null
时,第一个创建的Hippo
对象会被销毁。
==
可以用来比较两个主数据类型的值是否相等、两个对象引用是否引用的是堆上的同一个对象。
所有的对象都在堆上。
对象有自己的实例变量和方法,所以,实例变量存在于对象所属的堆上。
如果实例变量是主数据类型,Java会根据主数据类型的大小在堆上为该实例变量分配空间。比如,int
需要32位,long
需要64位。
如果实例变量是另一个的对象引用,就要分两种情况,
第一种,只是声明了引用变量,但并没有赋值,那么只会在堆上为该引用变量分配空间;
第二种,引用变量被赋值了一个对象,则还需要在堆上为该对象分配空间。
方法调用和局部变量保存在栈上。
当一个方法被调用,该方法会被放在调用栈的栈顶。
将实例变量标记为private
,将Setters和Getters标记为public
。
public class DogTestDrive {
public static void main(String[] args){
Dog one = new Dog();
one.setSize(80);
System.out.println(one.getSize());
one.bark();
Dog two = new Dog();
two.setSize(30);
System.out.println(two.getSize());
two.bark();
Dog three = new Dog();
three.setSize(8);
System.out.println(three.getSize());
three.bark();
}
}
public class Dog {
private int size;
public void setSize(int s){
size = s;
}
public int getSize(){
return size;
}
public void bark(){
if(size>60){
System.out.println("Wooof!Wooof!");
}else if(size>14){
System.out.println("Ruff!Ruff!");
}else{
System.out.println("Yip!Yip!");
}
}
}
public class Dog {
private int size;
private String name;
public int getSize(){
return size;
}
public String getName(){
return name;
}
public void bark(){
}
}
public class DogTestDrive {
public static void main(String[] args){
Dog d = new Dog();
System.out.println(d.getSize());
System.out.println(d.getName());
}
}
数据类型 | 默认值 |
---|---|
boolean |
false |
char |
0 |
byte |
0 |
short |
0 |
int |
0 |
long |
0 |
float |
0.0 |
double |
0.0 |
对象引用 | null |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameHelper {
public String getUserInput(String prompt){
String inputLine = null;
System.out.print(prompt+": ");
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
inputLine = reader.readLine();
}catch(IOException e){
System.out.println("IOException: " + e);
}
return inputLine;
}
}
public class Game {
private int[] locationCells;
private int numOfHits = 0;
public void setLocationCells(int[] locs){
locationCells = locs;
}
public String check(String stringGuess){
String result = "miss";
int guess = Integer.parseInt(stringGuess);
for(int cell:locationCells){
if(guess == cell){
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length){
result = "kill";
}
System.out.println(result);
return result;
}
}
public class GameTestDrive {
public static void main(String[] args){
int numOfGuesses = 0;
Game game = new Game();
int randomNum = (int) (Math.random()*5);
int[] locationCells = {randomNum,randomNum+1,randomNum+2};
game.setLocationCells(locationCells);
GameHelper helper = new GameHelper();
boolean isActive = true;
while(isActive){
String guess = helper.getUserInput("enter a number");
numOfGuesses++;
if(game.check(guess) == "kill"){
isActive = false;
System.out.println("You took " + numOfGuesses +" guesses");
}
}
}
}
Integer.parseInt()
String
转换成int
int randomNum = (int) (Math.random()*5)
for(int cell:locationCells){}
ArrayList
isEmpty()
size()
contains()
indexOf()
get()
add()
remove()
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
ArrayList<String> list = new ArrayList<String>();
list.add("Hello");
list.add("World");
System.out.println(list.isEmpty()); // false
System.out.println(list.size()); // 2
System.out.println(list.contains("Hello")); // true
System.out.println(list.contains("World")); // true
System.out.println(list.indexOf("Hello")); // 0
System.out.println(list.indexOf("World")); // 1
System.out.println(list.get(0)); // Hello
System.out.println(list.get(1)); // World
list.remove(0);
System.out.println(list.contains("Hello")); // false
list.remove("World");
System.out.println(list.contains("World")); // false
System.out.println(list.isEmpty()); // true
System.out.println(list.size()); // 0
}
}
前面我们提到了一个bug,连续输入2
,也能结束游戏。
现在来修复这个bug,解决方法是,localtionCells
不用数组,用ArrayList。
import java.util.ArrayList;
public class Game {
private ArrayList<String> locationCells = new ArrayList<String>();
private int numOfHits = 0;
public void setLocationCells(ArrayList<String> locs){
locationCells = locs;
}
public String check(String stringGuess){
String result = "miss";
int index = locationCells.indexOf(stringGuess);
if(index >= 0){
locationCells.remove(index);
if(locationCells.isEmpty()){
result = "kill";
}else{
result = "hit";
}
}
System.out.println(result);
return result;
}
}
import java.util.ArrayList;
public class GameTestDrive {
public static void main(String[] args){
int numOfGuesses = 0;
Game game = new Game();
int randomNum = (int) (Math.random()*5);
ArrayList<String> locs = new ArrayList<String>();
locs.add(String.valueOf(randomNum));
locs.add(String.valueOf(randomNum+1));
locs.add(String.valueOf(randomNum+2));
game.setLocationCells(locs);
GameHelper helper = new GameHelper();
boolean isActive = true;
while(isActive){
String guess = helper.getUserInput("enter a number");
numOfGuesses++;
if(game.check(guess) == "kill"){
isActive = false;
System.out.println("You took " + numOfGuesses +" guesses");
}
}
}
}
java.util.ArrayList
ArrayList
的完整名称是java.util.ArrayList
,所以import java.util.ArrayList
。String
的全称是java.lang.String
;System
的全称是java.lang.System
;Math
的全称是java.lang.Math
,import java.lang.String
、import java.lang.System
、import java.lang.Math
,java.lang
是经常用到的基础包,所以Java会预先将java.lang
这个包引用进来。构造函数与类同名,且没有返回值。
构造函数用来初始化对象。
最好有一个无参的构造函数。
public class Animal {
public Animal(){
System.out.println("Making an Animal");
}
}
public class Hippo extends Animal {
public Hippo(){
System.out.println("Making a Hippo");
}
}
public class Test {
public static void main(String[] args){
Hippo hippo = new Hippo();
}
}
Math.random()
0.0
~1.0
之间的双精度浮点数。Math.abs()
Math.round()
Math.max()
Math.min()
new Date()
getTime()
import java.util.Date;
public class Test {
public static void main(String[] args){
Date date = new Date();
System.out.println(date);
System.out.println(date.getTime());
}
}
Calendar.getInstance()
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test {
public static void main(String[] args){
System.out.println(new GregorianCalendar() instanceof Calendar);
}
}
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
System.out.println(calendar instanceof GregorianCalendar);
}
}
set(int year,int month,int date,int hourOfDay,int minute)
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2020,10,16,21,25);
System.out.println(calendar.getTime());
}
}
getTimeInMillis()
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2020,10,16,21,25);
System.out.println(calendar.getTime());
System.out.println(calendar.getTimeInMillis());
}
}
setTimeInMills(long millis)
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2020,10,16,21,25);
System.out.println(calendar.getTime());
System.out.println(calendar.get(calendar.HOUR_OF_DAY));
System.out.println(calendar.get(Calendar.HOUR));
long newDay = calendar.getTimeInMillis()+3600*1000;
calendar.setTimeInMillis(newDay);
System.out.println(calendar.get(calendar.HOUR_OF_DAY));
System.out.println(calendar.get(calendar.HOUR));
}
}
get(int field)
calendar.YEAR
calendar.MONTH
0
开始,0
就代表1
月calendar.DATE
calendar.HOUR_OF_DATE
calendar.MINUTE
calendar.SECOND
calendar.MILLISECOND
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2020,10,16,21,25);
System.out.println(calendar.getTime());
System.out.print(calendar.YEAR);
System.out.print(" ");
System.out.println(calendar.get(calendar.YEAR));
System.out.print(calendar.MONTH);
System.out.print(" ");
System.out.println(calendar.get(calendar.MONTH));
System.out.print(calendar.DATE);
System.out.print(" ");
System.out.println(calendar.get(calendar.DATE));
System.out.print(calendar.HOUR_OF_DAY);
System.out.print(" ");
System.out.println(calendar.get(calendar.HOUR_OF_DAY));
System.out.print(calendar.MINUTE);
System.out.print(" ");
System.out.println(calendar.get(calendar.MINUTE));
System.out.print(calendar.SECOND);
System.out.print(" ");
System.out.println(calendar.get(calendar.SECOND));
System.out.print(calendar.MILLISECOND);
System.out.print(" ");
System.out.println(calendar.get(calendar.MILLISECOND));
System.out.println(calendar.getTimeInMillis());
}
}
add(int field,int amount)
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.add(calendar.DATE,3);
System.out.println(calendar.getTime());
}
}
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.add(calendar.DATE,14);
System.out.println(calendar.getTime());
}
}
roll(int filed,int amount)
add(int field,int amount)
的区别是,roll(int filed,int amount)
不进位。import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.roll(calendar.DATE,14);
System.out.println(calendar.getTime());
}
}
getTimeZone()
import java.util.Calendar;
public class Test {
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar.set(2020,10,16,21,25);
System.out.println(calendar.getTime());
System.out.println(calendar.getTimeZone().getDisplayName());
System.out.println(calendar.getTimeZone().getID());
System.out.println(calendar.getTimeZone().getRawOffset()/(3600*1000));
}
}