• 代码块,静态变量,静态代码块,运算符优先级


    1)普通代码块:写在方法或者语句中的代码块

    2)构造块:直接写在类中的代码块

     1 class Demo{
     2         {
     3             System.out.println("1,构造块");
     4         }
     5         public Demo(){
     6             System.out.println("2,,构造方法");
     7         }
     8     }
     9 public class CodeDemo02 {
    10 
    11     public static void main(String[] args) {
    12         new Demo();
    13         new Demo();
    14         new Demo();
    15     }
    16 
    17 }

    输出结果为:

    1,构造块
    2,,构造方法
    1,构造块
    2,,构造方法
    1,构造块
    2,,构造方法

    分析:构造块优于构造方法执行,而且每次实例化对象都会执行构造块中的代码,即会执行多次。

    3)静态代码块

     1 class Demo{
     2     {
     3         System.out.println("1,构造块");
     4     }
     5     static{
     6         System.out.println("0,,静态代码块");
     7     }
     8     public Demo(){
     9         System.out.println("2,,构造方法");
    10     }
    11 }
    12 
    13 public class CodeDemo03 {
    14     static{
    15         System.out.println("在主方法所在类中定义的代码块");
    16     }
    17     public static void main(String[] args) {
    18         new Demo();
    19         new Demo();
    20         new Demo();
    21     }
    22 }

    输出结果为:

    在主方法所在类中定义的代码块
    0,,静态代码块
    1,构造块
    2,,构造方法
    1,构造块
    2,,构造方法
    1,构造块
    2,,构造方法

    分析:静态代码块优于主方法执行,而在类中定义的静态代码块会优于构造方法执行,而且不管有多少个对象产生,静态代码块只执行一次。

    4)

     1 public class Test {
     2     static {
     3         int x = 5;            //x是局部变量,不影响后边的值。
     4         System.out.println(x);
     5     }
     6     static int x,y;            //x和y是全局变量,初始化后x=0,y=0。
     7     public static void main(String[] args) {
     8         x--;
     9         myMethod();
    10         System.out.println(x + y++ +x);
    11     }
    12     public static void myMethod(){
    13         y = x++ + ++x;        
    14         //计算顺序:y = x+(++x);x+1
    15     }
    16 
    17 }

    输出结果为:

    5
    2

  • 相关阅读:
    不要放弃你的梦想
    ResultSet获得总行数的方法
    MS SQL Server数据库事务锁机制分析
    VS2005学习02Visual Studio® 2005 Team System
    获取打印机
    Download Accelerator PlusDAP
    设置打印机
    sqlserver2005里查询当前锁的状态。
    Excel的单位的转换
    PGP的密匙和口令的安全性问题
  • 原文地址:https://www.cnblogs.com/XuGuobao/p/7227535.html
Copyright © 2020-2023  润新知