之前学习一直都是自己做笔记 没有在网上发表任何内容 这次把自己以前学习碰到的值得收藏的内容拿出来与大家一起分享~
1、
求奇数 i%2 ==1 X
i%2 == 0
3、
浮点数相加减
2.2-1.1=0.9 X
双精度浮点小数不是一个确定值
可以使用bogdecimal("2.2").sub......
如果只用于输出 也可以使用pringtf("%.2f",2.2-1.1);
3、
长整形计算
float a=24*60*60*1000*1000;
float b=24*60*60*1000;
a/b=1000? X
在java中进行运算的 时候默认是int 型,溢出后再强转 数值已经变了
正确写法:
float a=24L*60*60*1000*1000;
4、
互换内容
int a=1000;
int b=2000;
y=(x^=(y^=x))^y;
5、
字符串和字符
"h"+"a" = "ha"
'h'+'a' = 201
6、
字符数组
直接打印 就是数组里面的内容 print()默认参数是 char[]
而进行字符串的拼接时 print( ) 参数则为 String
7、
转义字符
\u0022 是双引号的Unicode转义字符
System.out.println("a\u0022.length()
+\u0022b".length());
System.out.println("a".length()
+"b".length());
2
2
8、
打印输出类名
System.out.println(
MyClass.class.getName().
replaceAll(".","/")
+
".class");
}
//////////.class
System.out.println(
MyClass.class.getName().
replaceAll(".","/")
+
".class");
}
no8/MyClass.class
9、
随机数的问题
StringBufferword=null;
switch(rnd.nextInt(3))
{
case1: word=newStringBuffer("P");break;
case2: word=newStringBuffer("G");break;
default:word=newStringBuffer("M");
}
word.append('a');
word.append('i');
word.append('n');
System.out.println(word);
注意点:rnd.next(n); 是0-n 但是不取到n
switch 每次case 要break
stringBuffer 里面的参数和传入的值有关 int/string ...
10、
优柔寡断的返回值
publicstaticvoidmain(String[]args)
{
System.out.println(decision());
}
publicstaticbooleandecision()
{
try{
returntrue;
}finally{
returnfalse;
}
}
返回值:false 尽量避免在try catch 里面有返回
11、
无情的增量操作
intj=
0;
for(inti=
0;i< 100;i++){
j=j++;
//j++ j=++j
}
System.out.println(j);
结果:0 j=j++; j=j ++ 只有自增 没有再次赋值
12、
整数的边界问题
publicstaticfinalintEND=
Integer.MAX_VALUE;
publicstaticfinalintSTART=END-
100;
publicstaticvoidmain(String[]args)
{
intcount=
0;
for(inti=START;i<END;i++)
count++;
System.out.println(count);
}
无限循环 整数有边界 但是类似于一个环 上届和下届“差1”
13、
计数器问题
intminutes=
0;
for(intms=
0;ms< 60*60*1000;ms++)
if(ms%(60*1000)
== 0) //加括号 运算符优先级
minutes++;
System.out.println(minutes);
14、
你好 再见
try{
System.out.println("Hello
world");
System.exit(0);
}finally{
System.out.println("Goodbye
world");
}
finally 不一定会执行 程序中断之后 则不会执行
15、
到底关闭了么?
InputStreamin=null;
OutputStreamout=null;
try{
in=newFileInputStream(src);
out=newFileOutputStream(dest);
byte[]buf=newbyte[1024];
intn;
while((n=in.read(buf))
> 0)
out.write(buf,
0,
n);
}finally{
if(in!=null)in.close();
//in.close 也可能抛异常 也要try
if(out!=null)out.close();
}