小谈Java的初始化问题

小谈Intel SGX Intel SGX简介 背景 为什么要Intel SGX? Intel SGX的目标就是为了解决目前日益受关注的“远程计算的安全问题”。 以云环境为例子,云租户会将自己的产品部署在云平台中,但是云平台现在普遍认为是一个不可信的地方,因为可能会有云平台管理者、同一云主机其他租户的恶意攻击,也可能云平台本身存在漏洞,使得黑客轻易的攻击并拿到Ring0权限(就好比我租了房东的一间卧室,我害怕房东、其他租户、陌生人对我房间东张西望,甚至搞破坏。)。这种情况下,云租户就开始担心了。 与此同时,Intel SGX 阅读详情

CSDN乱码了。重新编辑。

同学发给我一个代码如下:


package hello;
public class hello {
	public static void main(String[] args) {
		int i, j;
		int sum;
		for (i = 1; i <= 1000; i++) {
			for (j = 1, sum = 0; j <= i / 2; j++) {
				if (i % j == 0)
					sum += j;
			}
                if (sum == i)
			System.out.println(sum);
}
         }
}


此代码无法通过编译,提示的错误如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The local variable sum may not have been initialized
The local variable sum may not have been initialized
at hello.hello.main(hello.java:12)

通过对sum的追踪发现sum与int sum中的sum是一个变量。通过C++测试发现C++编译通过并得到结果。

修改代码如下:


package hello;
public class hello {
	public static void main(String[] args) {
		int i, j;
		int sum = 0;//*修改
		for (i = 1; i <= 1000; i++) {
			for (j = 1, sum = 0; j <= i / 2; j++) {
				if (i % j == 0)
					sum += j;
			}
			if (sum == i)
				System.out.println(sum);
		}
	}
}


可以得到正确的答案。

思考如下:Java是一门比较注重安全的语言,for循环能否保证一定可以进入呢?

思考以下代码:


package hello;
public class hello {
	public static void main(String[] args) {
		int i, j;
		int sum = 0;
		for (i = 1; i <= -1000; i++) {
			for (j = 1, sum = 0; j <= i / 2; j++) {
				if (i % j == 0)
					sum += j;
			}
			if (sum == i)
				System.out.println(sum);
		}
	}
}


上面的代码并没有报错。可见就算for循环不符合数理,仍然是可以通过编译的。

那么从安全的角度看来,Java就不应该让一个全局变量的初始化发生在for循环中。当然这是我们的猜测而已。

再思考以下代码:


package hello;
public class hello {
	public static void main(String[] args) {
		int sum;
		while(true){
			sum = 1000;
			break;
		}
		System.out.println(sum);
	}
}


以上代码可以通过编译。

而:


package hello;
public class hello {
	public static void main(String[] args) {
		int sum;
		boolean i = true;
		while(i){
			sum = 1000;
			break;
		}
		System.out.println(sum);
	}
}


则无法通过编译。以上两则代码的区别仅仅是在于判断条件所在的位置。在while(true)中,这个循环是绝对可以进入的,但是在while(i)中呢?假设存在多线程的情况,那么这个循环将不一定可以进入。

所以多少可以侧证我们之前的结论:Java为了注重安全性,不会允许初始化的工作放在不确定的循环中。

---------------------------切割线-----------------------------

那Java不是会自动初始化的嘛?

思考以下代码:


package hello;
public class hello {
	private static int age;
	public static void main(String[] args) {
		System.out.println(age);
	}
}


在代码中,age必须是static的,因为调用它的方法(main)是static的,这是题外话了。

上面的代码输出结果是0,表示Java会自动初始化这个成员变量。

那么局部变量呢?


package hello;
public class hello {
//	private static int age;
	public static void main(String[] args) {
		int age;
		System.out.println(age);
	}
}

以上代码得到下面的错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The local variable age may not have been initialized
        at hello.hello.main(hello.java:6)


所以局部变量Java是不会初始化的。

本文结束。


小谈设计模式(17)—状态模式 对设计模式中状态模式进行详细解析 阅读详情

相关推荐

小谈设计模式(10)—原型模式

对设计模式中的原型模式进行了讲解分析

AI+全栈,AI+应用,实操落地,前沿技术 1572

Java错误解决方法合集

错误和解决方法都是亲自验证过的,解决方法可以用!不断更新中。 文章目录一、错误提示:Unexpected exception encountered during query.二、错误提示:MYSQL插入中文显示乱码。三、错误提示:windows中没有mysql服务。四、错误提示:Client does not support authentication五、错误提示:Unknown init...

spark2010的博客 7520

手把手教你用89C52单片机驱动0.96寸OLED(IIC接口,附完整代码)

本文详细介绍了如何使用89C52单片机通过I2C接口驱动0.96寸OLED显示屏,包括硬件连接、I2C通信原理、SSD1306驱动芯片的初始化及显存管理技巧,并提供了完整的代码示例和常见问题排查方法,帮助电子爱好者快速掌握OLED显示技术。

weixin_30781433的博客 376

在学习java程序初始化时碰到的问题及解决

因为:给类变量赋值的引用出现以下情况会报错:1.引用是类变量的初始化或是在类的静态初始化程序(静态代码块)里。局部变量的作用域是声明了这个变量到block的最后。a的作用域是整个testStatic,所以声明前也能用,和在函数定义前调用函数是一个道理。起因:代码里a=2前不加int,声明在后面,不懂为啥。参见8.3.3章节的文档。

m0_54174553的博客 509

C语言—for循环打印矩形,正三角形,倒三角形,九九乘法,等腰三角形,倒着的等腰三角形(简易版代码)(重点考察for循环嵌套)

本章节教大家如何利用for循环打印正三角形,倒三角形,九九乘法表及等腰三角形(简易版代码)说明:1、循环语句的循环体内又包含另一个完整的循环结构,称为循环结构的嵌套。内嵌的循环语句中还可以再嵌套循环结构,这样就形成多重循环结构的嵌套。2、for 语句、while 语句和 do-while 语句都允许嵌套。三种循环语句可以相互嵌套。3、内层的循环语句必须完全被包含在外层的循环体中,不能发生交叉。

m0_63501145的博客 1704

告别手动干预:深入浅出LPDDR5的Background ZQ校准与DVFSQ切换避坑指南

本文深入解析LPDDR5的Background ZQ校准与DVFSQ切换技术,帮助工程师实现DRAM阻抗校准的自动化管理。通过详细配置指南和实战案例,揭示如何避免动态电压调节下的模式切换陷阱,提升信号完整性和系统能效。特别适合嵌入式系统和移动终端开发者参考。

weixin_30329623的博客 462

java 未初始化_Java 代码中的可能未初始化变量问题

出现的错误:import java.util.Scanner;public class tickets {public static void main(String[] args) {Scanner stdin=new Scanner(System.in);System.out.println("Please enter the for family or not ( Y or N ): ");...

weixin_39652810的博客 670

西门子Simotion运动控制

SIMOTION

rjimhcd的博客 3029

“The local variable XXX may not have been initialized”

“The local variable XXX may not have been initialized” 翻译一下就是:局部变量XXX可能尚未初始化 在文件中的操作是: double d = 0.00; String str = "100"; try{ d = Double.parseDouble(str); }catch(Exception e){ } /*

饭糕的博客 4万+

秃鹰搜索优化算法(BES)详解:从自然捕食到全局优化

秃鹰搜索优化算法(Bald Eagle Search Optimization Algorithm,BES)是由马来西亚学者Alsattar等人于2020年提出的一种新型元启发式优化算法。该算法灵感来源于秃鹰在自然界中高超的捕食行为,特别是其独特的狩猎策略和卓越的视觉搜索能力,模拟了秃鹰捕食鲑鱼等猎物的完整过程。

qq_42212808的博客 1358

道威棱镜的设计参考

道威棱镜的设计参考

weixin_72050316的博客 384

小谈Java中类加载以及对象初始化的过程

探讨Java中类加载到完成一个对象创建的过程 Java作为面向对象的一门语言,在程序中最重要的也是最基础的就是通过类创建对象,在本文中我简单聊一聊对于这个过程我个人的理解。有不足之处还请多多指正。 一个Java类中有什么? 那么当我们创建一个对象时执行了哪些操作呢? 类加载以及对象创建及其初始化 类加载:发生在类第一次被虚拟机调用,类会被虚拟机加载一次,一般来说,也只被加载一...

Viaxiz 881

YOLO26 FP16/INT8混合量化实战:精度无损+速度拉满,边缘设备部署最优解

这是混合量化的灵魂,告诉量化器:哪些层不准动,保留FP16。"""判断是否为量化敏感层 → 是则豁免为FP16返回 True=敏感层(FP16),False=可量化(INT8)"""# 1. 检测头回归分支# 2. 小通道1×1卷积# 3. SiLU 激活# 4. 残差ShortcutYOLO26想要在Jetson、RK3588、昇腾、嵌入式NPU上真正落地,FP16/INT8混合量化是唯一最优解。它的核心逻辑不是玄学,而是工程上的精准取舍能量化的层,全部INT8榨性能;

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 753

小谈Java构造器

java构造器的原理相似于c++中的构造函数,是一个特殊的成员函数,是用于创建类实例的一个重要方法。如果一个类要进行对一系列属性的初始化,那么构造函数可以根据函数需要进行编写完成所有变量的初始化,不必一一去初始化。 对其做简单的总结,它的基本特点是: 构造方法的方法名必须与类名相同。构造方法没有返回类型,也不能定义为void,在方法名前面不声明方法类型。构造方法的主要作用是完成对象

Runing and flying 1524

R语言使用survminer包的ggcompetingrisks函数可视化竞争风险的累积事件曲线、使用可视化对象的mapping属性自定义修改、配置颜色分组及线条类型

R语言使用survminer包的ggcompetingrisks函数可视化竞争风险的累积事件曲线、使用可视化对象的mapping属性自定义修改、配置颜色分组及线条类型

data+scenario+science+insight 1383

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

小谈Java中的静态块与非静态块

原文地址:点击打开链接 java中经常有一些静态块,这是用来在生成类之前进行的初始化,无论java还C++语言中的static,都是最先初始化好的。结构如下: static { 静态语句代码块 } { 非静态语句代码块 } 异同点 相同点:都是在JVM加载类时且在构造方法执行之前执行,在类中都可以定义多个,一般在代码块中对一些...

aobi6343的博客 115

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

java 静态块 非静态块_小谈Java中的静态块与非静态块

java中经常有一些静态块,这是用来在生成类之前进行的初始化,无论java还C++语言中的static,都是最先初始化好的。结构如下:static {静态语句代码块}{非静态语句代码块}异同点相同点:都是在JVM加载类时且在构造方法执行之前执行,在类中都可以定义多个,一般在代码块中对一些static变量进行赋 值。不同点:静态代码块在非静态代码块之前执行(静态代码块--》非静态代码块--》构...

weixin_42099815的博客 175

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

小谈单例模式 | 单例模式的八种写法?

看了这篇文章,你能和面试官畅谈单例模式一、前言二、单例模式最通俗的解释来一个简单的例子三、实现单例模式的8种写法1.饿汉式(静态常量)(可用)2.饿汉式(静态代码块)(可用)3.懒汉式(线程不安全)(不可用)4.懒汉式(线程安全)(不推荐)5.懒汉式(线程不安全)(不可用)6.懒汉式(双重检查)(推荐面试使用)7.懒汉(静态内部类方式)(可用)8.枚举 推荐在项目中使用四、常见面试问题五、关于几种...

qq_35764460的博客 1691

小谈ResultSet用法

结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同时还具有操纵数据的功能,可能完成对数据的更新等.   结果集读取数据的方法主要是getXXX(),他的参数可以使整型表示第几列(是从1开始的),还可以是列名.返回的是对应的XXX类型的值. 如果对应那列时空值,XXX是对象的话返回XXX型的空值,如果X...

abo38416的博客 139

小谈队列

小谈队列   虽然数组是存储和访问速度最快的数据结构,但是却受创建时其长度、存储的类型就固定限制这一特性所限制。为此我们引入动态存储数据的数据结构——队列。说到队列,现实生活中还真有不少:食堂打菜的学生、超市等待结账的客户、影院排队购票的观影者,现实生活中总是存在排队现象。当我们把队列搬到计算机、搬到JAVA程序中,我们需要找寻队列的特性。 每次排队,人们总会自觉从后面加入队列,当然也有那...

u014442623的博客 166
上一篇: 有用的知识技能书签
下一篇: IBM技术论坛:单元测试利器 JUnit 4
louis9212
博客等级 码龄14年 8粉丝 49原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址