Assignments Flashcards

1
Q

What is a literal?

A

A primitive literal is merely a source code representation of the primitive data
types—in other words, an integer, floating-point number, boolean, or character that
you type in while writing code. The following are examples of primitive literals:
‘b’ //char literal
42 //int literal
false //boolean literal
2546789.343 //double literal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the ways to represent integers in Java?

A

There are 4 ways: decimal (base

10), octal (base 8), hexadecimal (base 16), and as of Java 7, binary (base 2).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the rules for numeric literals with underscores and when was it introduces?

A

It was introduced by Java7 and it can not be used at the beginning of the literal or at the end or just after decimal point. It can be used by any of the numeric types including doubles and floats.
int pre7 = 1000000; // pre Java 7 – we hope it’s a million
int with7 = 1_000_000; // much clearer!
int i1 = _1_000000; // illegal, can’t begin with an “
int i2 = 10_0000_0; // legal, but confusing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do we write binary literals?

A

By putting a 0B or 0b to the beginning:
int b1 = 0B101010;
int b2 = 0b00011;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do we write octal literals?

A
They start with 0. They can have up to 21 digits not including the leading 0.
int six = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do we write hexadecimal literals?

A

They start with 0x or 0X and can have up to 16 digits not including the prefix.
int x = 0X0001;
int y = 0x7fffffff;
int z = 0xDeadCafe;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can binary, octal, decimal, and hexadecimal integer literals can be in other types and how?

A

They can be specified as long by placing a suffix at the end like:
long jo = 110599L;
long so = 0xFFFFl; // Note the lowercase ‘l’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do we define floating point literals?

A

For double no need to put an explicit D or d to the end but for float put F or f because it is a way to tell compiler that you are aware of what you are doing when you assign the number to a less precise container.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do we define boolean literals?

A

Only as true or false. Numbers not accepted as in some languages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do we define char literals?

A

Inside single quotes but can be defined as unicode as well or any number literal that fits 16-bit unsigned range. We can also escape characters.
char a = ‘a’;
char b = ‘@’;

char letterN = ‘\u004E’; // The letter ‘N’

char a = 0x892; //hexadecimal literal
char b = 982; //int literal
char c = (char)70000; // The cast is required; 70000 is out of char range
char d = (char) -98; //Ridiculous,but legal

char e = -29; // Possible loss of precision; needs a cast
char f = 70000; // Possible loss of precision; needs a cast
char c = ‘"’; // A double quote
char d = ‘\n’; // A newline
char tab = ‘\t’; // A tab

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the non-primitive literals?

A

Strings and arrays.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does a reference variable hold values?

A

We don’t know what the format
is. The way in which object references are stored is virtual-machine specific (it’s a
pointer to something, we just don’t know what that something really is). All we can
say for sure is that the variable’s value is not the object, but rather a value representing a specific object on the heap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What happens if you assign different types of literals to each other?

A

byte b = 27;
27 is implicitly an int. But that assignment is valid only because the compiler automatically narrows the literal value to a byte .byte b = (byte) 27; // Explicitly cast the int literal to a byte

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the result of an expression involving anything int -sized or smaller?

A

The result is always an int.In other
words, add two byte s together and you’ll get an int —even if those two byte s are
tiny. Multiply an int and a short and you’ll get an int . Divide a short by a byte
and you’ll get…an int.
byte a = 3; // No problem, 3 fits in a byte
byte b = 8; // No problem, 8 fits in a byte
byte c = a + b; // Should be no problem, sum of the two bytes fits in a byte
Buttt it won’t compile:
TestBytes.java:5: possible loss of precision found: int
required: byte
byte c = a + b;
^
It would have compiled if we’d done the explicit cast:
byte c = (byte) (a + b);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Is this expression legal?

int j, k=1, l, m=k+3;

A

Yes, k is initialized before m uses it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Is this expression legal?

int j, k=m+3, l, m=1;

A

No, m is not initialized before k uses it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Is this expression legal?

int x, y=x+1, z;

A

No, x is not initialized before y uses it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are types of casts?

A

There are two. Can be ımplıcıt or explıcıt.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is an implicit cast?

A

You do not specify anything in code. That happens when you put somethıng smaller to a bigger container. It is a widening conversion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is an explicit cast?

A

When you put a bigger value to a smaller container-narrowing- you get a compile error saying ‘possible loss of precision’. But if you explicitly specify that you re aware of the loss and add type to code, that’s explicit conversion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

double d = 100L; Does that give an error?

A

No double can hold every information long can store. So that’s an implicit conversion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What happens when you cast a floating number to an integer?

A

It looses all the digits after decimal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

class Casting {

public static void main(String [] args) {

long l = 130L;

byte b = (byte)l;

System.out.println(“The byte is “ + b);

}

}

A

%java Casting

The byte is -126

The leftmost bit is 1 so it’s negative.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are he properties of boolean data type?

A

Size in bytes: –
Internal representation: Not precisely defined
Range: true or false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What are he properties of byte data type?

A

Size in bytes: 1
Internal representation: 8-bit two’s complement
Range: −128 to +127

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are he properties of char data type?

A

Size in bytes: 2
Internal representation: Unicode
Range: \u0000 to \uffff

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are he properties of short data type?

A

Size in bytes: 2
Internal representation: 16-bit two’s complement
Range: –32768 to 32767

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are he properties of int data type?

A

Size in bytes: 4
Internal representation: 32-bit two’s complement
Range: −2,147,483,648 to 2,147,483,647

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What are he properties of long data type?

A

Size in bytes: 8
Internal representation: 64-bit two’s complement
Range:-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What are he properties of float data type?

A

Size in bytes: 4
Internal representation: 32-bit IEEE 754
floating point
Range: 3.4e +/- 38 (7 digits)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are he properties of double data type?

A

Size in bytes: 8
Internal representation: 64-bit IEEE 754
floating point
Range: 1.7e +/- 308 (15 digits)

32
Q

What is the result of this assignment?

float f = 32.3;

A

Won’t compile because every floating-point literal is implicitly a double.

33
Q

What is the result of this assignment?

byte a = 128;

A

Won’t compile because compiler knows that the value you true to assign is too big for the container.

34
Q

What is the result?
byte b = 3;
b += 7;

A

No problem - adds 7 to b (result is 10)

+=, -=, *=, and /= will all put in an implicit cast

35
Q

What is the result?
byte b = 3;
b = (byte) (b + 7);

A

Won’t compile without the cast, since b + 7 results in an int

36
Q

What happens when you assign one primitive variable to another?

A

Contents of the variable is copied to the other variable. When you change one of them the other won’t be affected.

37
Q
What happens in this line?
Button b = new Button();
A
  • Makes a reference variable named b, of type Button
  • Creates a new Button object on the heap
  • Assigns the newly created Button object to the reference variable b
38
Q

What does that mean?

Button c = null;

A

It means the variable is not referring to any object.

39
Q
Which statement is valid? Why?
public class Foo {
public void doFooStuff() { }
}
public class Bar extends Foo {
public void doBarStuff() { }
}
class Test {
public static void main (String [] args) {
Foo reallyABar = new Bar(); 
Bar reallyAFoo = new Foo(); 
}
}
A
Foo reallyABar = new Bar(); // Legal because Bar is a
// subclass of Foo
Bar reallyAFoo = new Foo(); // Illegal! Foo is not a
// subclass of Bar

A Bar object is guaranteed to be able to do anything
a Foo can do, so anyone with a Foo reference can invoke Foo methods even though
the object is actually a Bar

40
Q

What are the wrappers?

A

A wrapper object is an object that holds the value of a primitive. Every kind of primitive
has an associated wrapper class: Boolean, Byte, Character, Double, Float, Integer, Long,
and Short.

41
Q
WHat are the types of variables in that block?
class Layout { // class
    static int s = 343; // static variable
    int x; // instance variable
    { x = 7; int x2 = 5; } // initialization block  
    Layout() { x += 8; int x3 = 6;} // constructor
    void doStuff() { // method
        int y = 0; // local variable
        for(int z = 0; z < 4; z++) { // 'for' code block
            y += z + x;
        }
    }
}
A
  • s is a static variable.
  • x is an instance variable.
  • y is a local variable (sometimes called a “method local” variable).
  • z is a block variable.
  • x2 is an init block variable, a flavor of local variable.
  • x3 is a constructor variable, a flavor of local variable.
42
Q

What are the scope of variables?

A
* Static variables have the longest scope; they are created when the class is
loaded, and they survive as long as the class stays loaded in the Java Virtual
Machine (JVM).
* Instance variables are the next most long-lived; they are created when a new
instance is created, and they live until the instance is removed.
* Local variables are next; they live as long as their method remains on the stack.
As we'll soon see, however, local variables can be alive and still be "out of scope."
* Block variables live only as long as the code block is executing.
43
Q

Are instance variables initialised and how?

A

Instance variables are initialised to a default value
each time a new instance is created, although they may be given an explicit value
after the object’s superconstructors have completed.

44
Q

What are the default values for instance variables?

A
Object reference -> null (not referencing any object)
byte, short, int, long -> 0
float, double -> 0.0
boolean -> false
char -> '\u0000'
45
Q
What is the output for that code?
public class Book {
	private String title; // instance reference variable
		public String getTitle() {
			return title;
		}
		public static void main(String [] args) {
			Book b = new Book();
			System.out.println("The title is " + b.getTitle());
	}
}
A

The title is null

46
Q
What is the output for that exception?
public class Book {
	private String title; 
	public String getTitle() {
		return title;
	}
	public static void main(String [] args) {
		Book b = new Book();
		String s = b.getTitle(); 
		String t = s.toLowerCase(); 
	}
}
A

Exception in thread “main” java.lang.NullPointerException
at Book.main(Book.java:9)
We get this error because the reference variable title does not point (refer) to an
object.

47
Q

What is the default value for an array object that is defined but not explicitly initialised?

A

An array is an object; thus, an array instance variable that’s declared but not
explicitly initialised will have a value of null, just as any other object reference
instance variable.

48
Q

What are the default values for members of an array that is initialised?

A

All array elements are given their default values—the same
default values that elements of that type get when they’re instance variables.

  • When an array of objects is instantiated, objects within the array are not instantiated automatically, but all the references get the default value of null.
  • When an array of primitives is instantiated, elements get default values.
49
Q

What are the default values for loccal variables?

A

They are not initialised. They should always be assigned a value. Otherwise we get compile error when we try to use it.

50
Q
What is the output for that?
public class TestLocal {
	public static void main(String [] args) {
		int x;
		if (args[0] != null) { // assume you know this is true
			x = 7; // compiler can't tell that this
			// statement will run
		}
		int y = x; // the compiler will choke here
	}
}
A

The compiler knows that the
initialisation might not happen and produces an error:

TestLocal.java:9: variable x might not have been initialised

51
Q
What is the result for that code block?
import java.util.Date;
public class TimeTravel {
    public static void main(String [] args) {
    Date date;
    if (date == null)
        System.out.println("date is null");
    }
}
A

Locally declared references can’t get away with checking for null before use, unless you explicitly initialise the local variable to null.
Local references are not given a default value; in other words, they aren’t null.

%javac TimeTravel.java
TimeTravel.java:5: Variable date may not have been initialized.
if (date == null)
1 error

52
Q

Do arrays defined as local or instance variables get default values?

A

Array elements are given
their default values (0, false, null, ‘\u0000’, and so on) regardless of whether the
array is declared as an instance or local variable. The array object itself, however,
will not be initialized if it’s declared locally. In other words, you must explicitly
initialize an array reference if it’s declared and used within a method, but at the
moment you construct an array object, all of its elements are assigned their default
values.

53
Q
What's the output of this code block?
class StringTest {
    public static void main(String [] args) {
        String x = "Java"; // Assign a value to x
        String y = x; // Now y and x refer to the same
                            // String object
        System.out.println("y string = " + y);
        x = x + " Bean"; // Now modify the object using
                                  // the x reference
        System.out.println("y string = " + y);
 }
}
A

%java StringTest
y string = Java
y string = Java

Any time we make any changes at all to a String, the VM will update the reference
variable to refer to a different object. The different object might be a new object, or it
might not be, but it will definitely be a different object. The reason we can’t say for
sure whether a new object is created is because of the String constant pool.

54
Q

What happens when you use a String reference variable to modify a string?

A
  • A new string is created (or a matching String is found in the String pool),
    leaving the original String object untouched.
  • The reference used to modify the String (or rather, make a new String
    by modifying a copy of the original) is then assigned the brand new String
    object.
55
Q

What happens when you pass a reference variable to a method?

A

That means you are passing the object reference not the actual object itself(a reference variable holds bits that represent to the underlying VM a way to get to a specific object in memory). But it still points to the same object on the heap.

56
Q

Is Java pass-by-value or pass-by-reference?

A

Java is actually pass-by-value for all variables running within a single VM. (Why mentioned VM??)

57
Q
What is the result?
class ReferenceTest {
	public static void main (String [] args) {
		int a = 1;
		ReferenceTest rt = new ReferenceTest();
		System.out.println("Before modify() a = " + a);
		rt.modify(a);
		System.out.println("After modify() a = " + a);
	}
	void modify(int number) {
		number = number + 1;
		System.out.println("number = " + number);
	}
}
A
Before modify() a = 1
number = 2
After modify() a = 1
58
Q

What is shadowing?

A

Reusing a variable name that’s already been declared somewhere else. The effect of shadowing is to hide the previously declared variable in such a way that it
may look as though you’re using the hidden variable, but you’re actually using the shadowing variable.

59
Q
What is the result?
class Foo {
	static int size = 7;
	static void changeIt(int size) {
		size = size + 200;
		System.out.println("size in changeIt is " + size);
	}
	public static void main (String [] args) {
		Foo f = new Foo();
		System.out.println("size = " + size);
		changeIt(size);
		System.out.println("size after changeIt is " + size);
	}
}
A

%java Foo
size = 7
size in changeIt is 207
size after changeIt is 7

60
Q
What is the result?
class Bar {
	int barNum = 28;
}
class Foo {
	Bar myBar = new Bar();
	void changeIt(Bar myBar) {
		myBar.barNum = 99;
		System.out.println("myBar.barNum in changeIt is " + myBar.barNum);
		myBar = new Bar();
		myBar.barNum = 420;
		System.out.println("myBar.barNum in changeIt is now " + myBar.barNum);
	}
	public static void main (String [] args) {
		Foo f = new Foo();
		System.out.println("f.myBar.barNum is " + f.myBar.barNum);
		f.changeIt(f.myBar);
		System.out.println("f.myBar.barNum after changeIt is "
		\+ f.myBar.barNum);
	}
}
A

f.myBar.barNum is 28
myBar.barNum in changeIt is 99
myBar.barNum in changeIt is now 420
f.myBar.barNum after changeIt is 99

61
Q

What are the elements created in memory?

A

A heap, a stack, constant pools, method areas.

62
Q

What is a heap?

A

The heap is that part of memory where Java objects live, and it’s the one and only part of memory that is in any way involved in the garbage collection process. All of garbage collection revolves around making sure that the heap has as much free space as possible

63
Q

When does the garbage collector run?

A

The garbage collector is under the control of the JVM; JVM decides when to run the arbage collector. From within your Java program you can ask the JVM to run the garbage collector, but there are no guarantees, under any circumstances, that the JVM will comply. Left to its own devices, the JVM will typically run the garbage collector when it senses that memory is running low.

64
Q

When does an object become eligible for garbage collection?

A

An object is eligible for garbage collection when no live thread can access it. - String object garbage collection is a different topic.

65
Q

What does garbage collector do when it sees an object eligible for collection?

A

It will consider that object as eligible for deletion, and it might even delete it at some point. It also might never delete it.

66
Q

Can a Java program run out of memory?

A

Yes. The garbage collection system attempts to remove objects from memory when they are not used. However, if you maintain too many live objects (objects referenced from other live objects), the system can run out of memory.

67
Q

What are the ways to make objects eligible for garbage collection?

A

Nulling a reference, reassigning a reference variable, isolating a reference.

68
Q

Give an example to reassigning a reference variable.

A
class GarbageTruck {
	public static void main(String [] args) {
		StringBuffer s1 = new StringBuffer("hello");
		StringBuffer s2 = new StringBuffer("goodbye");
		System.out.println(s1); // At this point the StringBuffer "hello" is not eligible
		s1 = s2; // Redirects s1 to refer to the "goodbye" object
		// Now the StringBuffer "hello" is eligible for collection
	}
}
69
Q

What is the eligibility for garbage collection of objects defined in a method?

A

When a method is invoked, any local variables created exist only for the duration of the method. Once the method has returned, the objects created in the method are eligible for garbage collection. There is an obvious exception, however. If an object is returned
from the method, its reference might be assigned to a reference variable in the method that called it; hence, it will not be eligible for collection.

70
Q

How does isolating a reference case occurs? (islands of isolation)

A
A simple example is a class that has an instance variable that is a reference variable to another instance of the same class. Now imagine that two such instances
exist and that they refer to each other. If all other references to these two objects are removed, then even though each object still has a valid reference, there will be no way for any live thread to access either object. When the garbage collector runs, it can usually discover any such islands of objects and remove them. 
public class Island {
	Island i;
	public static void main(String [] args) {
		Island i2 = new Island();
		Island i3 = new Island();
		Island i4 = new Island();
		i2.i = i3; // i2 refers to i3
		i3.i = i4; // i3 refers to i4
		i4.i = i2; // i4 refers to i2
		i2 = null;
		i3 = null;
		i4 = null;
		// do complicated, memory intensive stuff
	}
}
71
Q

Can garbage collection be forced?

A

No, we can just request a GC from JVM. But the garbage collector has evolved to such an advanced state that it’s recommended that you never invoke System.gc() in your code—leave it to the JVM.

72
Q

Does garbage collector remove all the unused objects when it collects?

A

Even if GC is run, it may not remove all the unused objects.

73
Q

How can you explicitly call GC?

A

The garbage collection routines that Java provides are members of the Runtime class. The Runtime class is a special class that has a single object (a Singleton) for
each main program. The Runtime object provides a mechanism for communicating directly with the virtual machine. To get the Runtime instance, you can use the
method Runtime.getRuntime(), which returns the Singleton. Once you have the Singleton, you can invoke the garbage collector using the gc() method. Alternatively, you can call the same method on the System class, which has static methods that can do the work of obtaining the Singleton for you. The simplest
way to ask for garbage collection (remember—just a request) is
System.gc();

!!But JVM may not have implemented this routine; the language specification allows this routine to do nothing at all.

74
Q

What is finalize method for?

A

It is called just before GC deletes the object. Bu since there is no guarantee that GC will delete the object it is not recommended to override this method. Also this method can again make the object ineligible for GC. And when this object becomes eligible again, GC will not call it since it was called before.

75
Q

Where do the variables live?

A

Local variables live on the stack and instance variables live with their objects on the heap.