Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java.lang and Java.io

The document is a transcript of an interview discussing Java concepts, specifically focusing on the differences between String, StringBuilder, and StringBuffer, as well as topics like object cloning, streams, serializability, and enums. The candidate provides detailed explanations and examples, highlighting key points such as mutability, thread safety, and performance considerations. The interviewer prompts the candidate to clarify and expand on their answers, leading to a comprehensive discussion of the Java programming language features.

Uploaded by

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

Java.lang and Java.io

The document is a transcript of an interview discussing Java concepts, specifically focusing on the differences between String, StringBuilder, and StringBuffer, as well as topics like object cloning, streams, serializability, and enums. The candidate provides detailed explanations and examples, highlighting key points such as mutability, thread safety, and performance considerations. The interviewer prompts the candidate to clarify and expand on their answers, leading to a comprehensive discussion of the Java programming language features.

Uploaded by

bhavanipriy73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CODERS FORUM

QOF Series

Date: Nov 8th to Nov 15th


Topic: java.lang & java.io
QUERY:

Interviewer: What's the Difference between String, StringBuilder & StringBuffer class?

Candidate: you are asking the 3 big answers with Single-line/One-liner Approach Question?

Interviewer:

Candidate: Anyways,
Split 1:
String is only type of immutable while String Builder and String Buffer are mutable.
Reason: IN STRING Class, there will be multiple object creation in Heap Area. When performing
concatenation.
Like Keep on Changing the Reference for each concat.
S1 : "Hello" -> Obj 1
S1 = S1 + " World" -> Obj 2 --> "Hello World" (New Object)
Now S1 will have reference of Obj 2. So, it reveals the type of immutable.

Split 2:
While in StringBuilder and StringBuffer it can change in Existing Object itself (In Heap Area).

Split 3:
StringBuffer have some similar qualities of StringBuilder.
The only difference
StringBuffer has special feature of Thread Safe in Sync Process.

Special Note:
Thread Safety means the guarantee in handling controls of threads in synchronized methods.

Interviewer: Super. The "Reason" part is excellent, because you have talked about internal working (Heap
Area). This will give you more score in Interview. But, Differentiate StringBuilder & StringBuffer even
more.
Candidate: About Memory Efficiency

» String: High
» StringBuilder: More Efficient
» StringBuffer: Less Efficient

Q: Why "High" in String?


A: Because of Garbage Collector which makes collect non used to flush it off

Q: Why "More Efficient" in StringBuilder?


A: Because only updating in existing object. Thread safety is not included. So, it can't handled well in sync.

Q: Why "Less Efficient" in StringBuffer?


A: Because here also only updating in existing object. But Thread safety given priority here

Interviewer: Which one is faster? StringBuilder or StringBuffer?

Candidate: StringBuilder is Faster. Due to the no sync

Interviewer: Absolutely Right!! Which is Light-weight? String or StringBuilder?

Candidate:
1. Thread Safety:

» StringBuilder is not thread-safe, meaning it doesn’t guarantee synchronization. This makes it more
efficient in a single-threaded environment because no extra overhead is needed for synchronization.
» StringBuffer is thread-safe, as all its methods are synchronized. This makes it safer in a multi-
threaded environment but can add some performance overhead due to synchronization.

2. Performance:

» StringBuilder is generally faster than StringBuffer in a single-threaded context because it avoids the
synchronization overhead.
» StringBuffer can be slower than StringBuilder due to the synchronization, which is unnecessary in
single-threaded environments.

3. Use Cases:
» Use StringBuilder when you are working in a single-threaded environment and need to manipulate
strings frequently, as it provides better performance.
» Use StringBuffer if your code involves multiple threads and requires string manipulation, as its
synchronized methods ensure thread safety.

Interviewer: Nicely differentiated StringBuilder & StringBuffer

Candidate: In short, if thread safety is not a concern string builder is preferred. If thread safety is preferred,
we should go for string buffer

Interviewer: Read the question Carefully, Candidate.

Candidate: String is lightweight than string builder in terms of memory usage, for smaller, immutable text
values

Interviewer: Correct

QUERY:
Interviewer:
a) Convert a float value to an integer (float to double etc.) [HINT: use wrapper classes, do not
typecast them!].
b) What is System.exit(), runtime.exit() and runtime.halt(). What's the difference?

Candidate: For the first one, we can use valueOf method. For Example:
Similarly, it can be used along with Double too.

Interviewer: This is typecasting: (int) Say without that. Almost correct

Candidate: Okay so first convert the float or double value to String and then we can convert it to int.

For Example:

Interviewer: This is Python-ish way....

Candidate:

Interviewer: This message was deleted.

Candidate:
Interviewer: Correct

Candidate:

Interviewer: This is also correct, but calling more functions....

Candidate:

» System.exit() is used to terminate JVM but it follows a shutdown sequence before terminating (by
default resource clean up takes place we can also add a custom Shutdown hook ).

» Runtime.halt() is used to terminate JVM immediately and forcibly without executing any shutdown
sequence.

Runtime.getRuntime.exit() this works same as System.exit() infact System.exit() internally calls


Runtime.getRuntime.exit() .

Interviewer: Correct. (But you missed one () there... ) If System.exit() internally calls
Runtime.getRuntime().exit(), then why use that ?

Candidate: is it coz System.exit() is simpler to use comparatively?

Interviewer: No....... The real reason is not easy to find... But find it

Candidate: When we use Runtime.getRuntime.exit() it might skip some shutdown hooks and terminate
immediately, while System.exit() ensures that all the Shutdown hooks are executed before terminating .
Interviewer: Correct!! Sometimes we include some custom code in Shutdown hooks... That will be
executed only if System.exit() is used.

QUERY:
Interviewer: What is Object Cloning?

Candidate: Object Cloning is the process of creating the exact copy of the object. The clone() method
reduces the extra processing time. Like if we use new keyword it will consume lot of processing time so we
use clone() method instead.

Interviewer: Why won't this work?

Candidate: Because they will be in same memory location and it's shallow copy

Interviewer: If we change anything in "v", will "copy" automatically change too??

Candidate: Yes, since it's not a deep copy. When we assign one object reference to another (like copy = v),
both variables point to the same memory location. So whenever we change something in "v", "copy" will
also reflect the same changes.

For Example:
So, the above code snippet justifies the answer. But there is a way we shall avoid this ie, changes in v
should not reflect in copy in that case we need to approach like this:

Interviewer:

So now, copy will also change?


Candidate: No, copy will not change. In Java, Integer is an immutable wrapper class, meaning that once an
Integer object is created, its value cannot be changed. When you increment num with num++, it creates a
new Integer object with the value 6 and assigns it to num. However, copy still references the original Integer
object with the value 5, so copy will remain 5.

Interviewer: Correct. Actually there's more to this topic...... But it's more Coding oriented... (I can't type
it in WhatsApp...)

QUERY:
Interviewer:
a) Bring out differences between char streams and byte streams.
b) How do you convert char streams to byte streams?

Candidate:
(a)

» Character stream Works on textual data and reads character by character There is an inbuilt
encoding and decoding process which helps in converting the textual data into binary data when
feeding it into the computer and the binary data is converted to textual data for attaining the human
readable form when needed.

» Byte stream Works on raw binary data and reads byte by byte. There is no inbuilt encoding and
decoding mechanism and the processes are carried out without decoding the underlying data

(b) OutputStreamWriter class helps in the conversion of character stream to byte stream. For Example:
Interviewer: (a) is okay. Correct. For (b) too, answer is correct. But I am just curious... is there any other
way to do it?

Candidate: ….

Interviewer: Okay, let's leave it... Actually, there are more programs in these topics (like redirecting print
statement to streams/files or parsing string using streams) ...But those are hard to type in WhatsApp. So,
let's wind-up Streams... We have already seen What is Serializability. Today let's go deeper:

QUERY:
Interviewer:
a) How & Why is Serializability is done?

b) Write a class, serialize its instance and write it to a file. Also read from the file and deserialize.

Candidate: How serializability can be achieved ?

» The object class should implement Serializable interface.


» Create objects for FileOutputStream, ObjectOutputStream.
» write to the object.

Why serializability?
Serialization allows you to save the state of an object to a file or database for later use and also helps
transport the code from one JVM to another and then de-serialize it there.

Interviewer: For "How", it's not enough to implement "Serializable" Interface, but we should also ensure
that all the Instance Variables that we are using inside the Class must also be Serializable.

Interviewer: Okay. So (a) is answered. (b) is pending yet.

Candidate:
Interviewer: Program may look like a lengthy program...But actually, it's very simple and good This
explains how easily an Object can be directly stored in a File (without a complicated Database!!)

QUERY:
<today is a simple query, split into 6 parts>

Interviewer: Query-a: What is enum in Java?

Candidate: Enum datatype is used for declareing the constant variable

Interviewer: Hmmmmm........ Not exactly.. "final" keyword is used for "declaring constant variable"

Candidate: Enums are useful when you have a fixed set of related constants, such as days of the week,
directions, or states.

Interviewer: Yes, correct. And what value does those constants will be assigned to? Can you please give a
Small Example of declaring an enum?
Candidate: Each constant in an enum is implicitly an instance of the enum type itself, and Java handles
their ordering internally

Interviewer: Example is okay... But what value is exactly being assigned here? Variable means it should
have a value right.... ?

Candidate: the days are the values here and only those that are declared could be assigned

Interviewer: How it will be stored internally? (Please don't say binary... ) Like, are the days String
values? Like "MONDAY”?

Candidate: each enum value is a public static field of the class type, they are all instances of the Day class.
while enum itself is a subclass of java.lang.Enum

Interviewer: The answer is: Numbers. Each day will be represented internally by numbers like 0, 1, 2...

Interviewer: Query-b: What is .ordinal() method?

Candidate: It is used to convert numbers to its ordinal form i.e, 1-1"st", 2-2"nd" , 3- 3"rd" and everything
else has the suffix "th"(11th,12th....)
Candidate: It is used to return the index of the enum instance it is internally stored with , starts from 0,1,2..
Ordinal value. The order in which it was declared in enum class

Interviewer: Correct. Can we EXPLICITLY assign the values for them? (Instead of auto-assigning like
Index)

Candidate: Yes, we can assign the values to enum. We can assign to this like Monday(10), Tuesday (30)....
To do this define a private variable within the enum and create a constructor that accepts this variable.

Interviewer: Oh... I had no Idea about this... In C language, it's rather straightforward approach...

Interviewer: Query-c: Is enum Serializable?

Candidate:

Interviewer:

Candidate: yep, they are serializable by default as enum class implements serializable interface. only the
name of the enum constant is stored, along with the fully qualified class name, which helps in identifying the
enum type during deserialization

Interviewer: Correct

Interviewer: Query-d: Is it Primitive Datatype, or Pre-Defined class, or user-defined custom class?

Candidate: just a clarification, the query is related to enum right?

Interviewer: Yes

Candidate: it is an user defined class, enum implicitly extends java.lang.Enum class and each constant is
an instance of the enum class itself. the compiler converts it into a class and adds certain methods like
values() and more

Interviewer: "its an user defined class..." Nope.

Candidate: a special type of class? java.lang.Enum is predefined.

Interviewer: Enum is a predefined class. enum is keyword that refers to the SAME predefined class.

Interviewer: Query-e: Difference between enum and Enum?

Candidate:

» enum is a keyword and a special data type that allows you to create new enum types (fixed constants,
like days of the week). It is a part of Java's language syntax.
» Enum is a special class that helps work with enum types. The Enum class provides methods like
values(), ordinal(), and valueOf(String name). It is part of the standard Java library, located in the
java.lang package.

Interviewer: Absolutely correct But missed one point: enum internally refers to Enum... both refer to
the same datatype... not different... like Integer and int

Candidate:
Interviewer: Query-f: Does it inherit Object class?

Candidate: enum do not directly inherit the Object class but indirectly do so…through the Enum class,
which extends Object. They still inherit all the methods from Object. This is because every enum implicitly
extends the java.lang.Enum class, and Enum itself extends Object.

Interviewer: Correct. Thus all 6 Sub-Queries are over.

You might also like