Sie sind auf Seite 1von 9

Q. What are Java key words and reserved words? What are the differences?

A:
Key words are reserved words. but not vice versa. See Java Language Keywords for
details.

Q. What are Java key words this?


A:
this is a keyword used in Java/C++ code to refer the current instance object itself.

Q. What is reference in Java? Is is the same as pointer in C/C++?


A: In Java, reference is a typed named memory space which holds addrees of an
Object of that type.
It is called reference in Java, but called pointer in C/C++. The key differences between
C/C++ with Java on pointer/reference are:

• You cannot put your hands on an Object without through its reference in Java. In
C/C++, you can.
• In C/C++, you can do arithmetic on pointers, but you cannot do arithmetic on
references in Java.
• In C/C++, you can dereference a pointer, you cannot dereference a reference in
Java.
• In Java, all object are put on the heap only. In C/C++, you can put an
Objecty/struct onto the stack.
• In C/C++, you can cast pointer to an totally defferent type without compiler
errors. In Java, you cannot, Java is more strong typed language.
• In C/C++, pointer can point to primitive types too. In Java, reference cannot
reference a primitive type, unlees the wrapper class is used.
• In C/C++, pointer can point to another pointer, in Java, reference cannot
reference another reference.

Java is safer, C/C++ is more powerful.

Q. What modifiers should be used for main method? Why could I violate the rule,
and it still works?
A:
The official modifiers and signature for main method is

public static void main(String[] args){}

You should remember it, and use this for your SCJP test.

However, if you miss public or even use private instead, some JVM might let you launch
your Java application without complaining or error messages. Why?

Because some JVMs just make themselves more tolerant then they should be. This kind
of practice is very common in Microsoft world. I guess Sun learned something from there.
Take a look at stock price movements of both co. on 2001, you will probably understand
why.

 What will happen if I omit static modifier for main method? Should I do that?
Q. What will happen if I omit static modifier for main method? Should I do that?
A: The code will compile, but not functional as you wanted (if you want
something normal, of course).
The main() method is supposed to be the entrance of the entire application.
However, if you omit static, it is just another instance method, happen to be called main.
It will not work as you expected. It will make yourself and your coworker confused. also
make yourself confused. It will become maintenance hazard.

Something is legal does not mean it is recommanded!!!!!! Don't trouble troubles until
trouble troubles you!!!!

Q. How does Java compiler resolve the ambiguity to decide which methods to
call?
A:
In the following example, four test() methods, if we pass ambiguous \b{null} to the test,
which one should (will) be called? The 3 on top has super/subclass/sub-subclass
relationship. The most specific one (down hierarchy) will be called. The 4th with String as
a parameter, but it is a sibling of Tester. Ambiguity compile time error results.
class Tester {
void test(Object s) { System.out.println ("Object version"); }
void test(Tester s) { System.out.println ("Tester version"); }
void test(SubTester s) { System.out.println ("SubTester version"); }

// Not compilable any more if you uncomment the line


// since String and Tester are siblings
// void test(String s) { System.out.println ("String version"); }

public static void main (String args[]) {


Tester c = new Tester ();
// Ambiguous, the most specific one which fit will be call
c.test (null); // SubTester version
c.test (new Object()); // Object version
}
}

class SubTester extends Tester{


}
"The informal intuition is that one method declaration is more specific than
another if any invocation handled by the first method could be passed on to the
other one without a compile-time type error."

Q. Where can I put labels in Java?


A: See the example here. The comments and commented code tells you
everything.
public class Test {
// lbla: //compilable Error: identifier expected
public static void main(String[] args) {
// lblb: //compilable Error: A declaration cannot be labeled
Object o = new Object();
int n = 1;

lblc:
if (o instanceof Object) {
while (true) {
n++;
if (n > 5)
break lblc;
System.out.println(n);
}
}

System.out.println("Finished n");

lblx:
for (int i = 3; i < 7; i++){
// skip number 5
if (i==5)
continue lblx;
System.out.println(i);
}

lbly: // legal before another lable


lblz:
{
System.out.println("Watch:");

break lbly;
// compilable Error: statement not reached
//System.out.println("This will never be printed out.");
}
}
}

Q. What is the return type of constructor, if any?


A: General answer is constructor has no return type.

Constructors look a little strange because they have no return type, not even void. This
is because the implicit return type of a class' constructor is the class type itself
It makes sense. Just think of this:
MyObj o = new MyObj();

Q. What are the differences between arguments and parameters?


A:
In method call point of view, they are the same. The two words used alternatively for
historical reasons. The same reason for so many alternatives for method, such as
function, procedure, sub, subroutine, ... If you use those words in different context, then
that is a different question, I need to find my English dictionary first...

Q. Is null the same as void in Java? Can I return null in a void return type
method?
A: No! Another No!
void means return nothing. null in Java means it is a reference type, but refers nothing.
null and void are very different things. For further interest, read here.
Q. What is the difference of null in Java and NULL in C++?

Q. Can we put a continue in a switch-case statement?


A: Answer is a hesitated YES, since it can happen in a special case.
// Guess the print out, then run it.
// A good IQ test
public class A {
public static void main(String args[]) {
int x = 0;
while (x < 10) {
System.out.print(" " + x);
switch (x) {
case 5: x += 2;
continue;
case 2: break;
case 7: break;
default: x++;
};
x++;
}
}
}
Q. How to compile 2 Java files simultaneously? The two inter-dependent files
are sitting on 2 different hard drives.
A:
If you are a beginner of Java, please give yourself a break by not doing this. If you're
experienced Java programmer, I don't think your boss will ask you to do this.

But if you insist, figure it out! I guess it can be done, and here is something which
might help:
Q. How to create my own package, how to call my class in another package?
Q. What are the rules to name a Java file without public class defined in it?
A:
Everyone knows one Java file only can contain one public class, and the file must be
named as the name of the public class name. But how about Java file with no public
class?

No restrictions on name of Java file without public class defined. If you have a class with
a main, you'd better name the file with that class name for your own convenience.
However, this is not required. Test this out!
// D.java
class A {}
class B {}
class C {}
class E {
public static void main(String[] args) {
System.out.println("Strange thing in E.");
}
}
class F {
public static void main(String[] args) {
System.out.println("Strange thing in F.");
}
}
It is called D.java. You can run it in 2 ways:
java E //output: Strange thing in E.
java F //output: Strange thing in F.

If you think carefully, there are good reasons for this. Testing is one of them.

Q. Why cannot I use private access modifier in my interface definition?


A: See original discussion here.
Everything declared in interface are implicit or explicit public. If you don't put anything
there, they are public (not default). No access modifiers other than public allowed.

Q. How to redirect System.out?


A: Use System.setOut()

Sample code:
import java.io.*;
class Redirection {
public static void main(String args[]) throws IOException {
PrintStream pos = new PrintStream(new FileOutputStream("applic.log"));
PrintStream oldstream=System.out;
System.out.println("Message 1 appears on console");
System.setOut(pos);
System.out.println("Message 2 appears on file");
System.out.println("Message 3 appears on file");
System.out.println("Message 4 appears on file");
System.setOut(oldstream);
System.out.println("Message 5 appears on console");
System.out.println("Message 6 appears on console");
}
}

Primitive Types in Java and Type Casting


Q. What is void? Is void a Java type?
A: void means nothing. You mark a method void means the method returns
nothing.
It is the same in Java/C++/C/C#. void is not a type in any of the languages.

Q. What is the difference of signed and unsigned integer?


A:
It is the interpretation of the first bit of the integer number been represented. If it is
signed, the first bit is 0 means it is a positive number, 1 means it is negative. If it is
unsigned, the first bit is just another bit, either to add (1) or not to add (0) 2n to the
value of the number. n is the bit location, 0 based counted from right to left.

Here is a binary representation of two bytes:


1111 1111 1111 0100
Signed : -12
unsigned: 65524

0000 0000 0000 1100


Signed : 12
unsigned: 12
If you don't understand how the negative number comes out, Do google search for
"Two's complement". many good articles are out there.

In java, only char is unsigned, others like byte, short, int, long are all signed. In other
languages like c/c++, all other types have a unsigned brother, char too. All are default to
signed except char type is implementation dependent.

Q. Why char range is 0 to 216-1?


A:
0 to 216-1
0 to 65535
0 to 1111 1111 1111 1111
'\u0000' to '\uFFFF'

All of above are equivalent, since char is unsigned 2 byte integer.

For the first one, use your scientific calculator to do a little math. You can use the
following to understand it too.
1111 1111 1111 1111 + 1 = 1 0000 0000 0000 0000 = 216

Q. The size of long is 64bits and that of float is 32 bits. then how it is possible
long to float without type casting it?
eg.
long l=12345678;
float f = l; // ok to compiler
A: Interesting question!!!
The internal representation of integer types (byte, short, char, long) and floating point
number (float, double) are totally different. Converting from long to float is not a
narrowing conversion. Even it may lose some significant digits. See the following table for
details:

Primitive Data Types

default value
# of
type range when it is a class
bits
member

8, 1 bit
Boolean true false false
used

char 16 '\u0000' '\uFFFF' '\u0000'

byte 8 -128 +127 0

short 16 -32,768 +32,767 0

int 32 -2,147,483,648 +2,147,483,647 0

long 64 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 0

float 32 -3.40292347E+38 +3.40292347E+38 0.0

+
double 64 -1.79769313486231570E+308 0.0
1.79769313486231570E+308

Q. Why char c = 3; compiles, but float f = 1.3; error out?


A:
char c = 3; byte b = 300; short s = 300; int i = 30000;

are assignments to integers(signed or unsigned) Compiler will do a range checking to see


if those value are in the range of the variable, if it is, ok; otherwise, error out!

float f = 1.3; float f = 1.3f; double d = 1.3;

are assignments to floating numbers. The difference between 1.3d and 1.3f is the
precision, not the range. 1.3 is default to double precision number, assigning it to a float
will lose precision. It will need a cast!

1.3 is different than 1.30 in physics/science, since different precision implication.

Distance d = 1.3 miles implies d is between 1.25 and 1.35 miles


Distance d = 1.30 miles implies d is between 1.295 and 1.305 miles, which is a lot more
precise measurement.

Of course, not everybody follows the convention.

Q. What are the variable initialization rules in Java?


A: Here we are:

• Member variables (both static and instance) are initialized implicitly by default:
1. Most primitives except boolean are default initialized to zero, not null!
2. boolean variables are default initialized to false, not zero, not null!
3. Only object references are default initialized to null!
4. Final varibles must be initialized explicitly in declaration or constructors
(instance final variable.)
• Local varibles are not initialized
1. They are not default intialized to anything, unless programmer initialize
them explicitly!
2. It is not compilable if you use them before assign them a value!

Q. Why byte to char, or float to long are narrow conversion defined by JLS?
A:
class My{
static long l;
static float f;
static char c;
static byte b;
public static void main(String[] ss) {
b=c; //not compilable
c=b; //not compilable either

l=f; //not compilable


f=l; //OK
}
}
Since char is 2 bytes unsigned integer, assign it to 1 byte signed integer will possible loss
precision. Opposite is true too, since the negative part of byte will be re-interpret to
positive and possible loss precision.

The float to long should be more obvious, since its decimal part will be lost.

Q. How many bits represent a boolean variable?


A:
Since boolean only has 2 states (true, false), one bit is absolutely enough for storing it.
However, in memory, we have no way to represent the address of each bit as a variable
address / reference, then we have to use one byte (8 bits) to make the variable
addressable. In other words, we only use 1 bit, and leave the other 7 bits unused.

To prove this theory, run the following program TestBoolSerialize.java. The output file
Bool.tmp and Byte.tmp will be the same size, but Short.tmp will be double the size. You
may need to run 1 section a time if you run out your memory.

Don't need to worry too much about internal representation is one beautiful thing of Java.
The programmer don't need to actively allocate/return memory like in c/c++. Don't you
remember the pain of using sizeof() in c/c++, because of the pointer arithmetic, etc?
There is no sizeof() in Java. My above program TestBoolSerialize.java actually does the
trick of sizeof() to reveal the secret of Java for you.

Q. What is type cast, can you give some simple example?


A: *** type cast ***
Cast the type of a variabe from one type to another, of course, it must be legal in
Java/C++ etc. Examples follow:
long l = 300L;
int i = (int)l; // cast a long to an int

class A {}
class B extends A {}

// will compile and run fine


A a = new B();
B b = (B)a; // cast A reference a to a B reference b
// runtime fine since a is actually a B

// will compile fine and ClassCastException will be thrown on runtime


A a = new A();
B b = (B)a; // cast A reference a to a B reference b
// runtime exception will be thrown since a is not really a B

Q. How to cast between objects? How about interfaces?


A:

1. Upper cast from subclass to supercalss, no need to cast, since the ISA
relationship. OakTree is a Tree.
2. Down cast from superclass to subclass, an explicit cast is needed to avoid compile
time error. If you cast Tree to OakTree, it would possibly be right, but not
necessarily, since this particular Tree actually might be an AppleTree. In that
case, a ClassCastException will be thrown out at the run time
3. If you cast between siblings or even irrelevant classes, a compile time error
results, since compiler has the type information of them. for example, if you cast
a OakTree to an AppleTree, or even a Furniture, compile will error out.
4. However, there is a catch, if you cast to an interface, even they are irrelevant,
and compiler might let you go without an error.

See some interesting example and runnable code at TestCast.java

Q. Why this code compiles OK, but throw ClassCastException at runtime?


Base b=new Base();
Sub s=new Sub(); //Sub extends Base
s=(Sub)b;
A:
"Oversea Chinese is a Chinese", but not vise versa.
"Chinese is not necessary an oversea Chinese, but possible."

When you cast super to sub, compiler assume that you know what you were doing, since
it is possible. However, runtime will find out b actually is not a Sub.

Since Cat is an Animal, but Animal is not necessary a Cat, but it is possible a Cat.

That is why downcast is allowed on compile time, since compiler assumes you know what
you are doing. However, Runtime will find out this Animal is actually not a Cat.

ClassCastException! Big time.

Q. What are the differences between char and byte? Why text file can be read
back as byte streams?
A:
1. Everything in computer are represented by 0's and 1's, every eight 0's and 1's
can form a byte, that is why everything can be read in as byte streams.
2. byte is the smallest memory unit addressable.
3. How to interpret those bytes is the job of operation system, software, etc.
4. For Java primitive types, char is 16 bits unsigned integer, byte is 8 bits signed
integer, short is 16 bits signed integer.
5. The difference between char and short is the interpretation of the first bit.

Q. A case study, why 3 is printed out?


class Test {
public static void main(String[] args) {
Test t = new Test();
t.test(1.0, 2L, 3);
}
void test(double a, double b, short c) {
System.out.println("1");
}
void test(float a, byte b, byte c) {
System.out.println("2");
}
void test(double a, double b, double c) {
System.out.println("3");
}
void test(int a, long b, int c) {
System.out.println("4");
}
void test(long a, long b, long c) {
System.out.println("5");
}
void test(float a, long b, int c) {
System.out.println("6");
}
}

// output: 3
// think why?
A:
Remember the following will help:

• 3 (integer type) is always default to int in Java.


• 1.0 (floating point number) is is always default to double in Java.

Explanation correct or wrong:

1. Wrong! Since 3 is int, int to short needs explicit cast.


2. Wrong! Since all three parameters are wrong.
3. Correct! Since numeric promotions are performed on 2nd/3rd parameters.
4. Wrong! Since 1.0 is double, double to int needs explicit cast.
5. Wrong! Since double to long needs explicit cast.
6. Wrong! Since double to float needs explicit cast

Das könnte Ihnen auch gefallen