分析Java代码块的实例。
作者:归人云淡风轻
时间:2023-05-09
来源:互联网
浏览:0
1.普通代码块普通代码块就是指直接在方法或是语句中定义的代码块publicclassCodeDemo{publicstaticvoidmain(String[]args){//普通代码块{intx=10;//局部变量System.out.println("普通代码块---》"+x);//10}intx=100;System.out.println("代码块之外---》"+x);//100}}2.构造代码块publicclassCodeBlock{{System.out.println("构造代码块");}
1.普通代码块
普通代码块就是指直接在方法或是语句中定义的代码块
public class CodeDemo {
public static void main(String[] args) {
// 普通代码块
{
int x = 10; // 局部变量
System.out.println("普通代码块---》"+x); //10
}
int x = 100;
System.out.println("代码块之外---》"+x); //100
}
}2.构造代码块
public class CodeBlock
{
{
System.out.println("构造代码块");
}
CodeBlock(){
System.out.println("构造方法");
}
}
public class Test
{
public static void main(String[] args) {
CodeBlock codeBlock = new CodeBlock();
}
}
//执行结果
//构造代码块
//构造方法3.静态代码块
在类中方法外出现,并加上static修饰,常用于给类进行初始化,在加载的时候就执行,并且静态代码块执行一次。
public class CodeBlock
{
{
System.out.println("静态代码块");
}
{
System.out.println("构造代码块");
}
CodeBlock(){
System.out.println("构造方法");
}
}
public class Test
{
public static void main(String[] args) {
CodeBlock codeBlock = new CodeBlock();
}
}
//执行结果
//静态代码块
//构造代码块
//构造方法4.局部代码块
作用域:存在方法中
public static void main (String[] args){
{
int number = 1;
}
System.out.println(number);//异常
}
作者最新文章
荣耀MagicOS 11发布计划与Agent Harness架构解析
2026-09-08 19:23
AI重构企业业务架构:超聚变“智企”范式核心解析
2026-09-08 18:39
PDF合并工具怎么选?在线合并5步实操指南
2026-09-04 17:05
PDF图片压缩工具推荐与批量处理实操指南
2026-09-03 12:14
照片如何转成PDF格式?三种图片转PDF操作方法
2026-09-03 11:04
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















