0% found this document useful (0 votes)
44 views

5.which Algorithm Garbage Collector Uses To Perform Garbage Collection?

The document discusses several topics related to programming languages: 1. The size keyword exists in C and C++ but not in Java. read[] returns 0 at the end of a file. 2. Unicode requires 16 bits, ASCII 7 bits, UTF-8 uses 8, 16, or 18 bits, and UTF-16 uses 16 bits or more. 3. The JVM has five memory areas: heap, method, stack, program counter, and native method stack. 4. The mark-and-sweep algorithm is a garbage collection algorithm that traces reachable objects and reclaims memory from unreachable objects in two phases: marking and sweeping.

Uploaded by

Pragya Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

5.which Algorithm Garbage Collector Uses To Perform Garbage Collection?

The document discusses several topics related to programming languages: 1. The size keyword exists in C and C++ but not in Java. read[] returns 0 at the end of a file. 2. Unicode requires 16 bits, ASCII 7 bits, UTF-8 uses 8, 16, or 18 bits, and UTF-16 uses 16 bits or more. 3. The JVM has five memory areas: heap, method, stack, program counter, and native method stack. 4. The mark-and-sweep algorithm is a garbage collection algorithm that traces reachable objects and reclaims memory from unreachable objects in two phases: marking and sweeping.

Uploaded by

Pragya Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1.

size of is keyword in C and C++ not in java


2.read[] return 0 at the end of file.
3.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character
set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters
using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns
4. How many types of memory areas are allocated by JVM?
The memory areas of the Java Virtual Machine are listed below:-

Heap area:- It is the runtime data area in which objects are allocated.
Method area:- It stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
JVM language stack:- It stores frames.It holds local variables and partial results,
and plays a part in method invocation and return.Each thread has a private JVM
stack, created at the same time as thread.A new frame is created each time a
method is invoked. A frame is destroyed when its method invocation completes.
PC (program counter) register:-. It contains the address of the Java virtual
machine instruction currently being executed.
Native Methods Stack:- Native method stacks is called C stacks.It support native
methods (methods written in a language other than the Java programming
language), typically allocated to each thread when the thread is created.The size of
native method stacks can be either fixed or dynamic.
5.Which algorithm garbage collector uses to perform garbage collection?

Mark-and-Sweep: Garbage Collection Algorithm


Background
All the objects which are created dynamically (using new in C++ and Java) are
allocated memory in the heap. If we go on creating objects we might get Out Of
Memory error, since it is not possible to allocate heap memory to objects. So we
need to clear heap memory by releasing memory for all those objects which are no
longer referenced by the program (or the unreachable objects) so that the space is
made available for subsequent new objects. This memory can be released by the
programmer itself but it seems to be an overhead for the programmer, here garbage
collection comes to our rescue, and it automatically releases the heap memory for
all the unreferenced objects.
There are many garbage collection algorithms which run in the background. One of
them is mark and sweep.
Mark and Sweep Algorithm
Any garbage collection algorithm must perform 2 basic operations. One, it should
be able to detect all the unreachable objects and secondly, it must reclaim the heap
space used by the garbage objects and make the space available again to the
program.
The above operations are performed by Mark and Sweep Algorithm in two phases:
1) Mark phase
2) Sweep phase
Mark Phase
When an object is created, its mark bit is set to 0(false). In the Mark phase, we set
the marked bit for all the reachable objects (or the objects which a user can refer
to) to 1(true). Now to perform this operation we simply need to do a graph
traversal, a depth first search approach would work for us. Here we can consider
every object as a node and then all the nodes (objects) that are reachable from this
node (object) are visited and it goes on till we have visited all the reachable nodes.
Root is a variable that refer to an object and is directly accessible by local variable.
We will assume that we have one root only.

We can access the mark bit for an object by: markedBit(obj).


Algorithm -Mark phase:
Mark(root)
If markedBit(root) = false then
markedBit(root) = true
For each v referenced by root
Mark(v)
Note: If we have more than one root, then we simply have to call Mark() for all the
root variables.

Sweep Phase
As the name suggests it sweeps the unreachable objects i.e. it clears the heap
memory for all the unreachable objects. All those objects whose marked value is
set to false are cleared from the heap memory, for all other objects (reachable
objects) the marked bit is set to false.
Now the mark value for all the reachable objects is set to false, since we will run
the algorithm (if required) and again we will go through the mark phase to mark all
the reachable objects.
Algorithm Sweep Phase
Sweep()
For each object p in heap
If markedBit(p) = true then
markedBit(p) = false
else
heap.release(p)

The mark-and-sweep algorithm is called a tracing garbage collector because is


traces out the entire collection of objects that are directly or indirectly accessible
by the program.
Example:
All the objects have their marked bits set to false.

b) Reachable objects are marked true

c) Non reachable objects are cleared from the heap.

Advantages of Mark and Sweep Algorithm

It handles the case with cyclic references, even in case of a cycle, this algorithm
never ends up in an infinite loop.
There are no additional overheads incurred during the execution of the algorithm.
Disadvantages of Mark and Sweep Algorithm
The main disadvantage of the mark-and-sweep approach is the fact that that normal
program execution is suspended while the garbage collection algorithm runs.
Other disadvantage is that, after the Mark and Sweep Algorithm is run several
times on a program, reachable objects end up being separated by many, small
unused memory regions. Look at the below figure for better understanding.

Figure:
Here white blocks denote the free memory, while the grey blocks denote the
memory taken by all the reachable objects.
Now the free segments (which are denoted by white color) are of varying size lets
say the 5 free segments are of size 1, 1, 2, 3, 5 (size in units).
Now we need to create an object which takes 10 units of memory, now assuming
that memory can be allocated only in contiguous form of blocks, the creation of
object isnt possible although we have an available memory space of 12 units and it
will cause OutOfMemory error. This problem is termed as Fragmentation. We
have memory available in fragments but we are unable to utilize that memory
space.
We can reduce the fragmentation by compaction; we shuffle the memory content to
place all the free memory blocks together to form one large block. Now consider
the above example, after compaction we have a continuous block of free memory
of size 12 units so now we can allocate memory to an object of size 10 units.
6. How many times finalize method is called on an Object?

Finalize() method is called only one time just before the object is garbage
collected.
7. Is it mandatory to define main method() in a class?
Its not mandatory to define main method .For example web application does not
have main method.If we want any program to execute then main method is
required.For standalone application we need main() method because it is the entry
point we dont have any entry point as we have for web applications.
8. If we dont define a main method and execute a class do we get any error?
main() method is not needed for compiling a program but we need it for executing
a program.When we try to execute a class without main method we get runtime
execution.
9. public static void main(String args[])
{
System.out.println(args[0]);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

10. public static void main(int args[])


{
Error: Main method not found in class

11.Default capacity of Vector, Arraylist, Hashtable, Hashmap,


Hashset

Java 6:
Vector = 10
Arraylist = 10
Hashtable = 11

Hashmap = 16
Hashset = 16
Java 7:
Vector = 10
Arraylist = 0. Size will change to 10 once we add the element in the list
Hashtable = 11
Hashmap = 0. Size will change to 16 once we add the element in the map
Hashset = 0. Size will change to 16 once we add the element in the set

12. difference between Size and Capacity


A vector has its default capacity which is 10 elements, here size is different from
capacity, after 10 element if we enter one element the capacity of vector changes to
20 were as size is 11 only, for example if you have entered 21 elements in a vector,
then if you print v.size it results 21 but v.capacity it results 30 If you have any
further queries pls let me know

13.Finally doesnt execute on

System.exit() is called.

The JVM crashes.

The try{} block never ends (e.g. endless loop).

14.Convert integer to roman


import java.util.LinkedHashMap;
import java.util.Map;
public class IntegerToRomanNumber {
public static void main(String[] args) {
System.out.println(getRomanEquivalentOfInteger(8));

}
private static String getRomanEquivalentOfInteger(int number){
if(number<=0){
return "not defined";
}
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");
String romanEqui="";
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
if(number/key!=0){
for (int i = 0; i < (number/key); i++) {
romanEqui = romanEqui + map.get(key);
}
number = number % key;
}
}
return romanEqui;
}
}

15. Why do we need polymorphism? When, where and how can we use it
Polymorphism is everywhere in daily life. Object oriented programming concepts
are developed from real life hence we can find several examples of every concept
of OOP in real life.

Lets come to the exact definition of polymorphism.


Polymorphism is occurrence an entity that has single name and many forms which
acts differently in different situations or circumstances. (the later part is very imp
in the definition). It reduces our complexities.
Note : Polymorphism can only be achieved through the behavior
(menthods/functions)
The best real life example is of an Air Conditioner (AC). Is is a single device
that performs different actions according to different circumstances. During
summer it cools the air and during winters it heats the air.
Another best example is Humans. We have different behaviors in different
situations and in front of different people. A man behaves differently with his
father, when he is with his friend he has different behavior, when he is with his
wife he has different behavior and so on.
So what is the need of polymorphism ?
Suppose you are the Principal of a school and you are going to conduct a meeting
of the teachers in our school. So instead of calling the teachers of different section
like teachers of science, teachers of mathematics and teachers of commerce you
simply called them as "all the teachers should attend the meeting". This reduced
the complexity of calling each and every teachers separately.
Now from programming point of view, if you have ever used Java just for basics
them you must know about the method "println()", single name many form. It is
an example of polymorphism.
println (10);
println ("Hello Java");
println (23.4);

// int Literal
// String
// Double

Hence you can see that we have to remember only one function name (reducing
our complexity) to print all the different values instead of having different
functions to print the values of different data types
16.length vs length()

length --- arrays (int[], double[], String[]) ---- to know the length of the arrays.
length() --- String related Object (String, StringBuilder etc)to know the length of
the String
size() --- Collection Object (ArrayList, Set etc)to know the size of the Collection

17.Difference between string constants and character constants.


The string constants are always enclosed in double quotes, while character
constants are enclosed in apostrophes (single quotation marks). A character
constant has an equivalent integer value, whereas a single-character string constant
does not have an equivalent integer value
18.Access Specifier vs Access Modifiers
Access Specifier: The access specifier determines how accessible the field is to
code in other classes. Access ranges from totally accessible to totally inaccessible.
You can optionally declare a field with an access specifier keyword: public,
private, or protected.
Access Modifier: You can optionally declare a field with a modifier keyword:
final or volatile and/or static and/or transient.
abstract,final, native, static, synchronized, transient, volatile and strictfp

19. Can we make main() thread as daemon?


The main thread cannot be set as daemon thread. Because a thread can be set
daemon before its running and as soon as the program starts the main thread starts
running and hence cannot be set as daemon thread.
As given in javadocs...

public final void setDaemon(boolean on)


Marks this thread as either a daemon thread or a user thread. The Java Virtual
Machine exits when the only threads running are all daemon threads.
This method must be invoked before the thread is started.
Parameters: on - if true, marks this thread as a daemon thread
Throws:

IllegalThreadStateException - if this thread is alive


SecurityException - if checkAccess() determines that the current thread
cannot modify this thread.

20. convert a HashSet to a TreeSet


import java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;
class ConvertHashSettoTreeSet{
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
//add elements to HashSet
hset.add("Element1");
hset.add("Element2");
hset.add("Element3");
hset.add("Element4");
// Displaying HashSet elements
System.out.println("HashSet contains: "+ hset);
// Creating a TreeSet of HashSet elements
Set<String> tset = new TreeSet<String>(hset);
// Displaying TreeSet elements

System.out.println("TreeSet contains: ");


for(String temp : tset){
System.out.println(temp);
}
}
}
Output:
HashSet contains: [Element1, Element2, Element3, Element4]
TreeSet contains:
Element1
Element2
Element3
Element4
21. Why is char[] preferred over String for passwords in Java?
While other suggestions here seem valid, there is one other good reason. With
plain String you have much higher chances of accidentally printing the
password to logs, monitors or some other insecure place. char[] is less
vulnerable.
Consider this:
public static void main(String[] args) {
Object pw = "Password";
System.out.println("String: " + pw);
pw = "Password".toCharArray();
System.out.println("Array: " + pw);
}
Prints:
String: Password
Array: [C@5829428e
22.Atomic variables in java

23. Why does Java not show an error for double semicolon at the
end of a statement?

An empty statement does nothing.


usually the second semicolon is interpreted as an empty statement, which is
permissible where ever a statement is permissible.
Actually, there are cases where a double semicolon does produce an error:
public int method() {
return 1;;
}
When the compiler determines that a location is not reachable (and this is defined
exactly in the JLS, but includes the locations directly after
a return, break, continue and throw), no statement is allowed there, not even an
empty one

24.Size of primitive types:

25. Long and Double Values Are Not Atomic in Java


Nonatomic 64-bit operations." I actually never knew that in Java 64bit, long and double values were treated as two 32-bit values. That means, a 64-bit
write operation is basically performed as two separate 32-bit operations. This
behavior can result in indeterminate values being read in code and that lacks
atomicity.
According to the Java Language Specification (JSL-17.7)
For the purposes of the Java programming language memory model, a single
write to a non-volatile long or double value is treated as two separate writes:
one to each 32-bit half. This can result in a situation where a thread sees the
first 32 bits of a 64-bit value from one write, and the second 32 bits from
another write.

Writes and reads of volatile long and double values are always atomic.
Writes to and reads of references are always atomic, regardless of whether
they are implemented as 32-bit or 64-bit values.
Some implementations may find it convenient to divide a single write action
on a 64-bit long or double value into two write actions on adjacent 32-bit
values. For efficiencys sake, this behavior is implementation-specific; an
implementation of the Java Virtual Machine is free to perform writes
to long and double values atomically or in two parts.
Implementations of the Java Virtual Machine are encouraged to avoid
splitting 64-bit values where possible. Programmers are encouraged to declare
shared 64-bit values as volatile or synchronize their programs correctly to
avoid possible complications.
So point is, in Java, long and double arent thread safe. When multiple threads are
going to access a long or a double value without synchronization, it can cause
problems. To ensure atomic/thread safety, it is essential to use volatile to ensure
changes made by one thread are visible to other threads. Thats how we can ensure
the read/write is atomic and thread safe.
However, if all reads and writes of 64-bit long and double values occur within a
synchronized block, the atomicity of the read/write is guaranteed.
26. java primitive data types atomic, reliable, threadsafe in multi threaded
programming ?
primitive datatypes are not threadsafe in java !!
Use AtomicIntger for threadsafe.

27. What is AtomicInteger class and how it's functioning is different from
using a volatile or synchronized?
AtomicInteger uses combination of volatile & CAS (compare and swap) to achieve
thread-safety for Integer Counter. It is non-blocking in nature and thus highly
usable in writing high throughput concurrent data structures that can be used under
low to moderate thread contention.

Compare-And-Swap
In computer science, compare-and-swap (CAS) is an atomic instruction used in
multi-threading to achieve synchronization. It compares the contents of a memory
location to a given value and, only if they are the same, modifies the contents of
that memory location to a given new value. This is done as a single atomic
operation. The atomicity guarantees that the new value is calculated based on upto-date information
Thread Contention
Essentially thread contention is a condition where one thread is waiting for a
lock/object that is currently being held by another thread. Wwaiting thread cannot
use that object until the other thread has unlocked that particular object.

Read & write to volatile variables have same memory semantics as that of
acquiring and releasing a monitor using synchronized code block. So the visibility
of volatile field is guaranteed by the JMM (Java Memory Model).
AtomicInteger class stores its value field in a volatile variable, thus it is a decorator
over the traditional volatile variable, but it provides unique non-blocking
mechanism for updating the value after requiring the hardware level support for
CAS (compare and set/swap). Under low to moderate thread contention, atomic
updates provides higher throughput compared to synchronized blocking increment
operation.
Here is the implementation for getAndIncrement() method of AtomicInteger Class
(as of Java 7).
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}

You can see that no lock is acquired to increment the value, rather CAS is used
inside infinite loop to update the new value, thats why it can be used to write
scalable application where thread contention is low to medium

You might also like