Which of the following are valid java identifiers?
A. _ B. _helloWorld$ C. true D. java.lang E. Public F. 1980_s G. _Q2_
B, E, G
What is an instance initializer?
A code block that is inside a class but outside a method.
What is the output?
public class Egg {
public Egg() {
number = 5;
}
public static void main(String[] args) {
Egg egg = new Egg();
System.out.println(egg.number);
}
private int number = 3;
{ number = 4; }
}The output is 5.
Fields and instance initializers are run in the order in which they appear in the file.
The constructor runs after all fields and instance initializer blocks have run.
Java has 8 built in data types. Which are they?
boolean, byte, short, int, long, float, double, char
What is the size of the primitive type ‘boolean’?
1 bit
What is the size of the primitive type ‘byte’?
8 bits / 1 byte
What is the size of the primitive type ‘short’?
16 bits / 2 bytes
What is the size of the primitive type ‘int’?
32 bits / 4 bytes
What is the size of the primitive type ‘long’?
64 bits / 8 bytes
What is the size of the primitive type ‘float’?
32 bit / 4 bytes
What is the size of the primitive type ‘double’?
64 bits / 8 bytes
What is the size of the primitive type ‘char’?
16 bits / 2 bytes
True or false
A float does not require the letter ‘f’ following the number in Java.
False.
The letter ‘f’ is required so Java knows its a float.
A byte can hold a value from … to …
-128 to 127
What is the difference between a short and a char?
Short and char are closely related, as both as stored as integral types with 16 bit length. The difference is that short is signed (which means it can hold positive and negative numbers) and char is unsigned (which means it can only hold positive numbers, including 0).
When writing a numeric literal, what data type does java assume you are writing?
An int. This is why we need to specify an ‘L’ after the number if it should be a long.
Java allows other formats other than the decimal system to write numbers. Name the following formats:
Explain why the following does or does not compile:
Which if these can compile?
String value = null compiles fine.
A primitive data type cannot be assigned null.
Does this code compile or not? Why?
String reference = “Hello”;
int len = reference.length();
int len2 = len.length();
Reference types can be used to call methods but primitives to not have methods declared on them. Thus len.length() is not valid.
An identifier is the name of a variable, method, class, interface, or package. There are 4 rules for legal identifiers. What are they?
Whcih of these identifiers are legal?
1 and 3.
@ is not allowed and an identifier cannot start with a number.
Which of the following are legal/illegal declarations? why?
What is a local variable?
A variable defined in a constructor, method or initializer block.