Java Basics Flashcards
Reference types
Reference types refers to objects that they refer to.
A reference points to an object by storing the memory address where teh object is located
Can I assign a String refence variable to Integer later?
No, you cannot assign reference variable to different type.
A reference can be assigned to another object of same type.
What is important about local variables?
You cannot use local variables without initializing.
It cannot be assigned to default value. It contains garbage value if not assigned any value.
If you try to use it before assigning, compile time error occurs
public void findAnswer(boolean check) { int answer; int onlyOneBranch; if (check) { onlyOneBranch = 1; answer = 1; } else { answer = 2; } System.out.println(answer); System.out.println(onlyOneBranch); }
Will this compile?
No, it will not compile.
The compiler throws error.
It complains saying that the the field- onlyOneBranch might have not been initialized
Which method when overriden, called by Garbage collector?
finalize()
How many times a finally could be called by GC?
Zero or one
What are the rules for automatic numeric promotion?
If two values have different data types, Java will automatically promote one of the values
to the larger of the two data types.
2. If one of the values is integral and the other is floating-point, Java will automatically
promote the integral value to the floating-point value’s data type.
- Smaller data types, namely byte, short, and char, are first promoted to int any time
they’re used with a Java binary arithmetic operator, even if neither of the operands is
int. - After all promotion has occurred and the operands have the same data type, the resulting
value will have the same data type as its promoted operands
int x = 3;
int y = ++x * 5 / x– + –x;
System.out.println(“x is “ + x);
System.out.println(“y is “ + y);
X=2
y=7
short x = 10;
short y = 3;
short z = x * y;
What is the actual result?
Compilation error.
We have to downcast it like
short z=(short) (x*y)
What is special about compound operator?
Downcasting will be automatically taken care by compound operator
5 == 5.00 -> result?
TRUE
int a=10;
int b = (a=2);
Syso(a );
syso(b); output?
a=2, b=2
int y = 1;
int z = 1;
final int x = y<10 ? y++ : z++;
System.out.println(y+”,”+z); // Output?
2, 1
What should we keep in mind regarding Switch statements?
The value in each case statement must be a compile time contsant. Means it should be final modifier with constant value assigned to it
Output?
int x = 0;
for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) {
System.out.print(x + “ “);
}
Compilation error- cannot redeclare the variable in for loop initialix=zation block
String x=”Hello”;
String y =”Hello”.trim()
x==y?
false.
Because, one is computed at runtime