Java基础错题
Blocks and Statements
概念
Block:
{ [*BlockStatements] } //我们所写的`{...}`就是Block陈述
*BlockStatements:
*BlockStatement {BlockStatement}
*BlockStatement:
LocalVariableDeclarationStatement //局部变量声明Declaration陈述
ClassDeclaration //类声明
*Statement //普通Java语句,例如分支选择循环条件...
*Statement:
*StatementWithoutTrailingSubstatement
LabeledStatement //标签语句,例如top:for(){second:for(){}}
IfThenStatement //仅if语句
IfThenElseStatement //if else语句
WhileStatement //while循环语句
ForStatement //for循环语句
StatementNoShortIf:
*StatementWithoutTrailingSubstatement
LabeledStatementNoShortIf
IfThenElseStatementNoShortIf
WhileStatementNoShortIf
ForStatementNoShortIf
*StatementWithoutTrailingSubstatement: //没有Trailing子陈述的陈述(没有类似悬空else问题)
Block
EmptyStatement
ExpressionStatement
AssertStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
//解释一下,为什么Statement和if干起来了(NoShortIf),因为parsing java的时候
//你会遇到,if if else,这个else到底是谁的这样的问题——"dangling else problem",悬空else问题
//Java,C,C++ 将这个问题,通过语法设计 武断(arbitrarily)规定 上面的else子句(clause)属于最近的if
//following grammar就是本文上面的Statements
The Java programming language, like C and C++ and many programming languages before them,
arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong.
This rule is captured by the following grammar
//如果形象一点的说Trailing,就是藤曼相互缠绕的样子,不能分清到底哪个藤条是A的,哪个藤条是B的
//也就是,不能让语法parse器出现不确定性,一条后续语法语句C,要么是前置A的,要么是前置B的
//不能后续语句C(else)即是A(if)的子句(else),又是B(if)的子句(else)。
switch
Switch-case-default-break问题
1.由于swtch-case-break有些常识,这里就略过了。
2.default位置与break的执行情况
psvm(args){
int i = ?;
switch(i){
default:i+=2;
case 1:i+=1;
case 4:i+=8;
case 2:i+=4;
}
sout(i);
}
//Problem1:怎么输出i为15,i=?
//Problem2:如果输入1,4,2,因为没有break,会执行最终缺省选项default吗?
答:switch为顺序执行
for
for语法规则
1.表达式123问题
//1
for(int i = 0 ; ; ){
sout(i);
break;
}
//2
int i = 1;
for( ; ; ){
sout(i);
break;
}
//Problem:这两个for循环哪个可以执行?哪个不能执行?如果可以执行,输出什么?
答:三大皆空
集合框架
Collection
ArrayList
1.remove方法的重载问题
@Test
public void testListRemove() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
updateList(list);
System.out.println(list);// }
}
private static void updateList(List list) {
list.remove(2);
}
//问:执行结果
答:1,2【remove(int)/remove(Object)2是int型,如果强转Integer则删除“2”对象】