Java String
intern
The java string
intern() method returns the interned string. It returns the canonical
representation of string.
It can be used to
return string from pool memory, if it is created by new keyword.
Signature
The signature of
intern method is given below:
public String
intern()
Returns :
interned string
Java String
intern() method example
public class
InternExample{
public static
void main(String args[]){
String s1=new
String("hello");
String
s2="hello";
String
s3=s1.intern();//returns string from pool, now it will be same as s2
System.out.println(s1==s2);//false
because reference is different
System.out.println(s2==s3);//true
because reference is same
}
}
}
Output:
false
true
Why StringBuffer
and StringBuilder classes are introduced in java when there already exist
String class to represent the set of characters?
The objects of
String class are immutable in nature. i.e you can’t modify them once they are
created. If you try to modify them, a new object will be created with modified
content. This may cause memory and performance issues if you are performing
lots of string modifications in your code. To overcome these issues,
StingBuffer and StringBuilder classes are introduced in java.
Which class will
you recommend among String, StringBuffer and StringBuilder classes if I want
mutable and thread safe objects?
StringBuffer
I am performing
lots of string concatenation and string modification in my code. which class
among string, StringBuffer and StringBuilder improves the performance of my
code. Remember I also want thread safe code?
StringBuffer
class gives better performance in this scenario. As String class is immutable,
if you use this class, a new object will be created after every string
concatenation or string modification. This will lower the performance of the
code. You can use StringBuilder also, but it is not thread safe. So,
StringBuffer will be optimal choice here.
What is the main
difference between Java strings and C, C++ strings?
In C and C++,
strings are terminated with null character. But in java, strings are not
terminated with null character. Strings are treated as objects in java.
Why String is
popular HashMap key in Java?
As we discuss
above String is immutable, its hashcode is cached at the time of creation and
it doesn’t need to be calculated again. This makes it a great candidate for key
in a Map and it’s processing is fast than other HashMap key objects. This is
why String is mostly used Object as HashMap keys.Key’s hash code is used
primarily in conjunction to its equals() method, for putting a key in map and
then getting it back from map. So, our only focus point is these two methods.
So if hash code of key object changes after we have put a key value pair in
map, then its almost impossible to fetch the value object back from map. It is
a case of memory leak.
On runtime, JVM
computes hash code for each object and provide it on demand. When we modify an
object’s state, JVM set a flag that object is modified and hash code must be
AGAIN computed. So, next time you call object’s hashCode() method, JVM
recalculate the hash code for that object.
For this basic
reasoning, key objects are suggested to be IMMUTABLE. IMMUTABILITY allows you
to get same hash code every time, for a key object. So it actually solves most
of the problems in one go. Also, this class must honor the hashCode() and
equals() methods contract.
example:
import
java.util.HashMap;
public class
stringhashtest {
public static
void main(String[] args) {
// Create new
HashMap.
// ... Uses
diamond inference on right side.
HashMap<String,
Integer> hash = new HashMap<>();
// Put three keys
with values.
hash.put("banana",
1);
hash.put("orange",
2);
hash.put("mango",
3);
// Look up some
known values.
int a =
hash.get("banana");
int b =
hash.get("orange");
// Display
results.
System.out.println(a);
System.out.println(b);
}
}
}
}
What are the
different ways to create object in Java?
There are five
different ways to create objects in java:
Using new keyword
Using Class.forName():
Using clone():
Using Object Deserialization:
Using newIntance() method
Using new
keyword:
This is the most
common way to create an object in java. Almost 99% of objects are created in
this way.
MyObject
object=new Object();
Using
Class.forName():
If we know the
name of the class & if it has a public default constructor we can create an
object in this way.
Syntax:
Myobject obj=(MyObject)
class.forName("object").newInstance();
Using clone():
The clone() can
be used to create a copy of an existing object.
Syntax:
MyObject obj=new
MyObject();
MyObject
object=(MyObject )obj.clone();
Using Object
Deserialization:
Object deserialization
is nothing but creating an object from its serialized form.
Syntax:
objectInputStream
istream=new objectInputStream(some data);
MyObject
object=(MyObject) instream.readObject();
Using
newInstance() method
Object obj =
DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();
How many objects
will be created in the following code and where they will be stored in the
memory?
String s1 =
"abc";
String s2 =
"abc";
Only one object
will be created and this object will be stored in the string constant
pool.
How many objects
will be created in the following code and where they will be stored?
String s1 = new
String("abc");
String s2 =
"abc";
Here, two string
objects will be created. Object created using new operator(s1) will be stored
in the heap memory. The object created using string literal(s2) is stored in
the string constant pool.
Can we call
String class methods using string literals?
Yes, we can call
String class methods using string literals. Here are some examples,
"abc".charAt(0)
"abc".compareTo("abc")
"abc".indexOf('c')
What is the
difference between Primitive data types vs. reference data types?
The values of
Primitive data types and Reference data types are stored differently (in Java):
Variables of
Primitive data types store the actual value
Variables of
Reference data types store the reference (= address) of the memory cells where
the actual values are stored.
What is the
difference between class variable and object variable?
If you have a
class including name, surname and age variables, then all these variables will
be created and valued separately for each instance of the class. This type of
variables are named as “object variables” because they belong to a specific
object. In Java, there are also variables that belong to a class rather than an
object. That’s where static keyword comes into play.
Variables defined
by using static keyword are named “class variables”. This kind of variables
hold values related to a class, not to a specific object and they occupy space
in memory even if there is no existing object created from that class. On the
other hand, object variables are created along with an actual object. Another
difference between object and class variables is that there is only one
instance of a class variable no matter how many objects are created.
What is a Static
Keyword?
Java static
keyword is used to create a Class level variable in java. static variables and
methods are part of the class, not the instances of the class.
Why we use static
keyword in java?
Class variables
also known as static fields share characteristics across all Objects within a
Class. When you declare a field to be static, only a single instance of the
associated variable is created, which is common to all the Objects of that Class.
Hence when one Object changes the value of a Class variable, it affects all the
Objects of the Class. We can access a Class variable by using the name of the
Class, and not necessarily using a reference to an individual Object within the
Class. Static variables can be accessed even when no Objects of that Class
exists. Class variables are declared
using the static keyword.
What is Static
Method ?
Class Methods/Static
Method, similar to Class variables can be invoked without having an instance of
the Class. Class methods are often used to provide global functions for Java
programs. For example, Methods in the java.lang.Math package are Class methods.
You cannot call non-static Methods from inside a static Method.
Static Keyword
Rules
1. Variable or Methods marked static belong to the Class rather then
to any particular Instance.
2. Static Method or variable can be used without
creating or referencing any instance of the Class.
3. If there are instances, a static variable of
a Class will be shared by all instances of that class, This will result in only
one copy.
4. A static Method can’t access a non static
variable nor can directly invoke non static Method (It can invoke or access
Method or variable via instances).
Static Important
Points:
1. Static is a Non Access Modifier.
2. The Static modifier can be applied to a
variable or Method or block or inner Class.
3. Static members belong to Class only not an
instance.
4. A Static Method cannot access an instance
variable.
5. Static Methods cannot be overridden as they
are Class specific and don’t belong to an Instance.
6. Static Methods can be redefined.
7. If a Class contains any static blocks then
that block will be executed only when the Class is loaded in JVM. Creating
multiple instances does not execute the static block multiple time. Only the
constructor will be executed multiple time.
8. If Class.forName(“class_name“) is called then
the static block of the Class will get executed.
What is a Static Block?
Static blocks are
nothing but a normal block of code, enclosed in braces { }, preceded with
static keyword. These static blocks will be called when JVM loads the class
into memory. In case a class has multiple static blocks across the class, then
JVM combines all these blocks as a single block of code and executes it. Static
blocks will be called only once, when it is loaded into memory. These are also
called initialization blocks.Static block does not return anything.
Static blocks is
mostly used in JDBC.
Static block can
be used as conditional checker before the control begin the execution of main
block.
If we have
developed an application for windows operating system and if it runs on any
other operation system, the application terminates. We check the operating
system installed on our user machine and stop the program execution if the OS
is other than windows
package
com.amrit.staticexmp;
import
java.util.ArrayList;
import
java.util.List;
public class
MyStaticBlock {
private static List<String> list;
static{
//created required instances
//create ur in-memory objects here
list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
}
public void testList(){
System.out.println(list);
}
public static void main(String a[]){
MyStaticBlock msb = new
MyStaticBlock();
msb.testList();
}
}
Output:
[one, two, three,
four]
Can you overload
static method in java?
Yes, we can
overload static method in Java. In terms of method overloading static method
are just like normal methods and in order to overload static method you need to
provide another static method with same name but different method signature.
Static overloaded method are resolved using Static Binding during compile time.
Can you override
static method in java?
We cannot
override static methods. Static methods are belogs to class, not belongs to
object. Inheritance will not be applicable for class members.
Can we access
instance variables within static methods ?
Yes Can we access
instance variables within static methods .
we cannot access
them directly but we can access them using object reference.
Static methods
belong to a class and not objects whereas non static members are tied to an instance.
Accessing instance variables without the instance handler would mean an
ambiguity regarding which instance the method is referring to and hence its
prohibited.
What will happen
if we remove the static keyword from main method ?
Program will compile
but will give a "NoSuchMethodError" during runtime.
How can we run a
java program without making any object?
By putting code
within either static method or static block.
How can we create
objects if we make the constructor private ?
We can do so
through a static public member method or static block.
Can we serialize
static variables ?
No. Only Object
and its members are serialized. Static variables are shared variables and
doesn't correspond to a specific object.
Can we override
private method in java?
Private method is
not inherited by subclass in Java. Sub class can not even see private methods
of super class. when you declare private method in subclass no body knows about
it except code in that class. That's why term method hiding is used. Accessing
private method outside class is compile time error in Java.
Why can't I
declare a static variable inside main() method in Java?
You cannot
declare a static variable within ANY method. Static variables have to be
declared at a class level
(You might have
read that static variables are shared by all objects of that class - same value
is accessed by all objects, change in value by one object is also experienced
by all objects)
Any variable
declared within a method is supposed to be local to the method (It gets stored
in the method stack in the JVM, which is one per thread), and static variables
are common to all objects of a class (obviously a class can be invoked by many
threads - each thread can invoke different object of the same class), so why
would java allow you to keep many copies of a static variable (at every
thread's stack) when all it needs is one copy to implement the functionality it
needs to give for the keyword static.
If main is a
static method in Java, then how can it access instance variables?
Static methods
cannot access non-static variables directly, but can access through object.
If you want to
use some non-static variables of some class, create an object/instance of that
class and using that object access the non static variables.
Same happens in
main method too. If you want to access a non static variable you have to do it
through the object no direct access is possible.
How can we run a
java program without making any object?
By putting code
within either static method or static block.
Can we have
Private constructor in a Class?
So I would like
to say, Yes you can have private Constructors in a class.
Private: anything
private can be accessed from within the class only.
Constructor: a
method which has same name as that of class and it is implicitly called when
object of the class is created.
or you can say,
to create an object you need to call its constructor, if constructor is not
called then object cannot be instantiated.
It means, if we
have a private constructor in a class then its objects can be instantiated
within the class only. So in simpler words you can say, if the constructor is
private then you will not be able to create its objects outside the class.
What's the
benefit This concept can be implemented to achieve singleton object (it means
only one object of the class can be created).
See the following
code,
class MyClass{
private static MyClass obj = new MyClass();
private MyClass(){
}
public static MyClass getObject(){
return obj;
}
}
class Main{
public static void main(String args[]){
MyClass o = MyClass.getObject();
//The above statement will return you
the one and only object of MyClass
//MyClass o = new MyClass();
//Above statement (if compiled) will
throw an error that you cannot access the constructor.
}
}
What is the
difference between static and final keyword in java?
The static
keyword is used to define the class members that accessed independently of the class
object whereas a final keyword is used to create a constant variable, a method
which cannot be overridden and a class that cannot be inherited.
A final variable
cannot be reassigned.
A final method
cannot be overridden.
A final class
cannot be inherited.
Why can't we use
this keyword in a static method?
Because this
refers to the object instance. There is no object instance in a call of a
static method. But of course you can access your static field (only the static
ones!). Just use
class Sub {
static int y;
public static void foo() {
y = 10;
}
}
If you want to
make sure you get the static field y and not some local variable with the same
name, use the class name to specify:
class Sub {
static int y;
public static void foo(int y) {
Sub.y = y;
}
}
What is the
difference between an Inner Class and a Sub-Class?
A subclass is
class which inherits a method or methods from a superclass. like:
class Car{
}
class HybridCar
extends Car {
}
HybridCar is a subclass
of Car.
innerclass is a
class defined inside another class. they are a type of "nested
classes"
class OuterClass
{
...
class NestedClass {
...
}
}
What is the
difference between double and float variables in Java?
In java, float
takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single
precision floating point decimal number while Double is double precision
decimal number.
What is the
difference between int and Integer?
The int type
int foo;
foo is a primitive
foo stores 32
bits of information
The Integer type
Integer bar;
bar is an object
reference
bar points to an
object of type java.lang.Integer (or to null)
Choosing between int and Integer
Prefer int for
performance reasons
Methods that take
objects (including generic types like List<T>) will implicitly require
the use of Integer
Use of Integer is
relatively cheap for low values (-128 to 127) because of interning - use
Integer.valueOf(int) and not new Integer(int)
Do not use == or
!= with Integer types
Consider using
Integer when you need to represent the absence of a value (null)
What is a Ternary
Operator?
The ternary
operator "?:" earns its name because it's the only operator to take
three operands. It is a conditional operator that provides a shorter syntax for
the if..then..else statement. The first operand is a boolean expression; if the
expression is true then the value of the second operand is returned otherwise
the value of the third operand is returned:
boolean
expression ? value1 : value2
Examples:
The following
if..then..else statement:
boolean isHappy =
true; String mood = ""; if (isHappy == true) { mood = "I'm
Happy!"; } else { mood = "I'm Sad!"; }
can be reduced to
one line using the ternary operator:
boolean isHappy =
true; String mood = (isHappy == true)?"I'm Happy!":"I'm
Sad!";
Generally
the code is easier to read when the if..then..else statement is written in full
but sometimes the ternary operator can be a handy syntax shortcut.
How can you
generate random numbers in Java?
Using
Math.random() you can generate random numbers in the range 0.1 to 1.0
Using Random
class in package java.util
Super keyword in
java
The super keyword
in java is a reference variable that is used to refer immediate parent class
object.
Whenever you
create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
Usage of java
super Keyword
super is used to
refer immediate parent class instance variable.
super() is used
to invoke immediate parent class constructor.
super is used to
invoke immediate parent class method.
Can we call super
class methods from static methods of sub class?
Yes we can call
super class static method inside sub class using super_class_method();
We can also call
super class static method using Sub_class_name.superclass_staticMethod()
If the same
static method defined in sub class also then we can not call super class method
using sub class name if we call them sub class static method will be executed.
Can we use both
"this" and "super" in a constructor ?
No, because both
this and super should be the first statement.
What are the
Rules in defining a constructor?
Constructor name
should be same as class name.
It should not
contain return type.
It should not
contain Non Access Modifiers: final ,static, abstract, synchronized
In it logic
return statement with value is not allowed.
It can have all
four accessibility modifiers: private , public, protected, default
It can have
parameters
It can have
throws clause: we can throw exception from constructor.
It can have
logic, as part of logic it can have all java legal statement except return
statement with value.
We cannot place
return in constructor.
If we place
return type in constructor prototype will it leads to Error?
No, because
compiler and JVM considers it as a method.
How compiler and
JVM can differentiate constructor and method definitions of both have same
class name?
By using return
type , if there is a return type it is considered as a method else it is
considered as constructor.
Why return type
is not allowed for constructor?
As there is a
possibility to define a method with same class name , return type is not
allowed to constructor to differentiate constructor block from method block.
Why constructor
name is same as class name?
Every class
object is created using the same new keyword , so it must have information
about the class to which it must create object .
For this reason
constructor name should be same as class name.
Can we declare
constructor as private?
Yes we can
declare constructor as private.
All four access
modifiers are allowed to constructor.
We should declare
constructor as private for not to allow user to create object from outside of
our class.
Basically we will
declare private constructor in Singleton design pattern.
Is Constructor
definition is mandatory in class?
No, it is
optional . If we do not define a constructor compiler will define a default
constructor.
Why compiler
given constructor is called as default constructor?
Because it obtain
all its default properties from its class.
They are
1. Its
accessibility modifier is same as its class accessibility modifier
2. Its name is
same as class name.
3. Its does not
have parameters and logic.
What is default
accessibility modifier of default constructor?
It is assigned
from its class.
When compiler
provides default constructor?
Only if there is
no explicit constructor defined by developer.
When developer
must provide constructor explicitly?
If we want do
execute some logic at the time of object creation, that logic may be object
initialization logic or some other useful logic.
If class has
explicit constructor , will it has default constructor?
No. compiler
places default constructor only if there is no explicit constructor.
What is No-arg
constructor?
Constructor
without arguments is called no-arg constructor. Default constructor in java is
always a no-arg constructor.
class MyClass
{
public MyClass()
{
//No-arg
constructor
}
}
Private
constructors are used to restrict the instantiation of a class. When a class
needs to prevent other classes from creating it’s objects then private
constructors are suitable for that. Objects to the class which has only private
constructors can be created within the class. A very good use of private
constructor is in singleton pattern. This ensures only one instance of a class
exist at any point of time. Here is an example of singleton pattern using
private constructor.
class MyClass
{
private static
MyClass object = null;
private MyClass()
{
//private
constructor
}
public MyClass
getObject()
{
if(object ==
null)
{
object = new
MyClass(); //Creating object using private constructor
}
return object;
}
}
Difference between & and &&:
& is bitwise && is logical.
& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.
Is there a difference between x++ and ++x in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
Difference between & and &&:
& is bitwise && is logical.
& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.
Is there a difference between x++ and ++x in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
No comments:
Post a Comment