Android java基础知识

一.Android java基础知识

第一个java程序Hello Worid:

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

运行结果:

root@ubuntu:/home/topeet/guyilian# javac Hello.java
root@ubuntu:/home/topeet/guyilian# java Hello
Hello, world!

循环打印的例子:

public class Hello {
	public static void main(String args[]) {
		int i = 0;
		for (i = 0; i < 3; i++) {
			System.out.println("Hello, world!");
		}
	}
}

运行结果: 

root@ubuntu:/home/topeet/guyilian# javac Hello.java 
root@ubuntu:/home/topeet/guyilian# java Hello
Hello, world!
Hello, world!
Hello, world!

java与C语言的数据类型对比,java中无指针类型的数据:


public class Var {
	public static void main(String args[]) {
		int   a = 3;
		float f = (float)3.14;
		float f2 = 3.14f;

		int i = 4;
		short s = 4;
		short s2 = (short)40000;

		//s = i;
		s = (short)(s + 1);  
		s = (short)(s + s2);

		/* Java has no pointer */
		//int* p = malloc(10*sizeof(int));
		int p[] = new int[10];
		int p2[] = {1,2,4}; /* static alloc */
		
		//char str[100];
		char str[] = new char[100];

		//char str2[] = "abc";

		String str2 = "abc";

		p = null;
		p2 = null;
		str = null;
		str2 = null;
	}
}


与C语言相比,Java的函数可以进行重载的操作,对函数的个数以及函数参数的类型也能够进行重载


public class Hello {
	public static void main(String args[]) {
		System.out.println(add(1,2));
		System.out.println(add(1,2, 3));
		System.out.println(add(1.0f, 2.0f));
	}

	public static int add (int x, int y) {
		return x + y;	
	}
	
	public static int add (int x, int y, int z) {
		return x + y + z;	
	}

	public static float add (float x, float y) {
		return x + y;	
	}

}

运行结果:

root@ubuntu:/home/topeet/guyilian# javac Hello.java 
root@ubuntu:/home/topeet/guyilian# java Hello
3
6
3.0

函数传递参数,如果要修改传递的参数要使用指针,但是在java里面用的是数组的地址。

public class Hello {
	public static void main(String args[]) {
		int x = 1;
		fun (x);

		int p[] = new int[1];
		p[0] = 123;

		System.out.println("Before fun2: "+p[0]);
		fun2(p);
		System.out.println("After fun2: "+p[0]);
		
		System.out.println(x);
	}

	public static void fun(int x) {
		x = 100;
	}		

	public static void fun2(int[] p) {
		p[0] = 200;
	}		

}

运行结果:

root@ubuntu:/home/topeet/guyilian# java Hello
Before fun2: 123
After fun2: 200
1

你可能感兴趣的:(Android,android,java,开发语言)