类型转换
类型转换的一般原则:
1.不能对boolean类型进行转换
2.不能把对象类型转化为不相关类的对象
3.大容量类型转化为小容量类型需要使用强制类型转换
4.转换过程中可能会发生溢出,示例如下:
public class change_num{
public static void main(String args[])
{
int a=123;
int b=134;
byte c=(byte)a;
byte d=(byte)b;
System.out.println("a is changed to "+c);
System.out.println("d is changed to "+d);
}
}
![](https://img-blog.csdnimg.cn/20190707163517532.png)
5.浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入
修饰符
1.static
静态修饰符在java中的作用与c++不一样,在java中被static修饰的变量或者函数,可以直接通过类名引用,而不需要创建对象,以下是示例:
public class test{
static int value=6;
public static void main(String args[]) {
test.value=12;
System.out.println(value);
}
}
public class test{
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
public static void main(String args[]) {
int[] array= {2,1,3,4};
test.printArray(array);
/*这边的test加不加都不会影响程序的结果但是两种调用方式只是结果相同,性质并不一样*/
System.out.println(reverse(array)[2]);
}
}
2.final
final 表示"最后的、最终的"含义,变量一旦赋值后,不能被重新赋值。被 final 修饰的实例变量必须显式指定初始值。
final 修饰符通常和 static 修饰符一起使用来创建类常量。
public class Test{
final int value = 10;
public void changeValue(){
value = 12; //将输出一个错误
}
}
final 方法
类中的 final 方法可以被子类继承,但是不能被子类修改。
声明 final 方法的主要目的是防止该方法的内容被修改。
如下所示,使用 final 修饰符声明方法。
public class Test{
public final void changeName(){
// 方法体
}
}
final类
final 类不能被继承,没有类能够继承 final 类的任何特性。
3.abstract
抽象类不能用来实例化对象,声明抽象类的唯一目的是为了将来对该类进行扩充。抽象类中包括抽象方法和非抽象方法,包括了抽象方法的类一定是抽象类,抽象方法没有任何实现,只能由子类实现其内容,以下是示例:
public abstract class SuperClass{
abstract void m(); //抽象方法
}
class SubClass extends SuperClass{
//实现抽象方法
void m(){
.........
}
}
循环
- while循环
while( 布尔表达式 ) {
//循环内容
}
布尔为真进入循环
- do while循环
do {
//代码语句
}while(布尔表达式);
同样布尔为真进入循环,不过do while至少执行一次。
- for循环
for(初始化; 布尔表达式; 更新) {
//代码语句
}
更新后满足布尔表达式进入循环
- 增强for循环
增强for循环的作用主要是便于对数组的管理。
示例:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
增强for循环的格式:for(变量类型 变量名:数组名){函数体},功能即遍历数组。
break和continue
- break功能:终止整个循环。
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
// x 等于 30 时跳出循环
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
- continue功能: 立刻跳入下次循环。
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
10
20
40
50