--> String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.
Java Buzz
Thursday, 5 September 2019
What is the difference between creating a Java String as new() and literal ?
Just have a look in below example :-
String str = new String("abc");
String str = "abc";
Here we are creating object of a String in two ways.
-> Using the new operator
String str = new String("abc");
This will always create two object, One in the Heap Area and One in the String constant pool and the String object reference always points to heap area object.
-> Using String Literals
String str = "abc";
When compiler encounters String literal, it checks the String Constant Pool to see if the given string already exists.
To make java more memory efficient JVM provide a special area of memory i.e “ String constant pool”.
If it exists or you can say match is found then the reference to the new literal is directed to the existing String and no new String literal object is created.( The existing String simply has an additional reference )
So basically it search in String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), Otherwise it will create a new string object and put in string pool for future re-use.
From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.
WHY STRING IS IMMUTABLE OR FINAL??
If more than one reference variable refer to the one or same String, and any bad programer by mistake or knowingly change the value of String then what will happen?? oopsss..
Thanks my string is final..
Or some one override the string class functionality, couldn't that cause problem in the pool??
Well that one of the best reason String marked as a Final.
Still confused with String Literal pool??
Thursday, 27 September 2018
Checked vs Unchecked Exception in Java
Checked and Unchecked exceptions are part of the Exception Handling in Java.
What are checked exceptions?
Ans : Checked exceptions are checked at the compile-time.
What do you mean by above line ?
What kind of exceptions are checked by compiler ?
All the checked exceptions are part of Exception class.
Below are few checked exceptions :
CloneNotSupportedException
ClassNotFountException
IOException (subclass of IOException : FileNotFoundException )
ParseException
InterruptedException
SQLException
There are many scenario where compiler knows very well the code may throw exception so it must be checked during compile time or in other words the code must be written inside try/catch block or it should declare the exception using throws keyword. If we fail to do that then it will throw compile time error.
Lets see one example for checked exception.
Below is the program without try/catch. This will throw compile time error as here we are doing IO operation and compiler mandate to handle IOException using try-catch or throws.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
FileOutputStream fout=new
FileOutputStream("D:\\TextFile.txt");
String s="Welcome to FileHandling program.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
}
OUTPUT :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
at FileOutputStreamExample.main(FileOutputStreamExample.java:5)
Note : Since we didn’t handled/declared the exceptions, above program gave the compilation error.
Same program with proper exception handling :
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new
FileOutputStream("D:\\TextFile.txt");
String s="Welcome to FileHandling program.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(IOException e){System.out.println(e);}
}
}
OUTPUT :
success...
What are Unchecked checked exceptions?
Ans : Unchecked exceptions are not checked at the compile-time.
Here compiler cannot estimate what kind of exception going to occur and so it doesn't force you to keep try/catch or throws. It is up to the programmer to judge the conditions in advance and handle them appropriately.
All Unchecked exception are part for RuntimeException class.
Below are few Unchecked exceptions :
ArithmeticExeception
NumberFormatException
NullPointerException
ArrayIndexOutOfBoundException
ClassCastException
Example 1 : In this example we are not handling exception and also compiler doesn't force to keep try/catch as mathematical operation is done during runtime.
public class O {
public static void main(String[] args) {
System.out.println("main begin");
System.out.println(1);
int i = 10 / 0;
System.out.println(2);
System.out.println(3);
System.out.println("main end");
}
OUTPUT :
main begin
1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at O.main(O.java:15)
Note : This kind of exceptions are more dangerous as it occur during runtime so you have to judge and keep try-catch or throws accordingly.
Example 2 : In this example we are handling Runtime Exception.
public class O {
public static void main(String[] args) {
System.out.println("main begin");
try {
System.out.println(1);
int i = 10 / 0;
System.out.println(2);
}
catch (ArithmeticException ex) {
System.out.println(3);
}
System.out.println("main end");
}
}
OUTPUT :
main begin
1
3
main end
Other then above all runtime exceptions, all the Error are also unchecked as this also occur duirng runtime. Error occurs due to some external environment and it occurs at runtime like StackOverflowError.
If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).
For example :
StackOverflowError
OutOfMemoryError
NoClassDefFoundError
NoSuchMethodError
AssertionError
NoSuchMethodError
AssertionError
Saturday, 16 December 2017
Write a java program to reverse a string or line using recursion.
public class Reverse {
public static void main(String[] args) {
String rev="Hello here is reverse using recursion";
revrec(rev);
//System.out.println(rev);
System.out.println(revrec(rev));
}
static String revrec(String rev)
{
String reverse ="";
// TODO Auto-generated method stub
if(rev.length() == 1){
return rev;
}
else
{
reverse += rev.charAt(rev.length()-1)+revrec(rev.substring(0, rev.length()-1));
return reverse;
}
}
}
Thursday, 12 January 2017
Write a program to create deadlock between two threads.
Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other to release a lock.
Code:
package com.javakickoff
Code:
package com.javakickoff
public class MyDeadlockClass { String str1 = "Oracle"; String str2 = "MySQL"; Thread trd1 = new Thread("My Thread 1"){ public void run(){ while(true){ synchronized(str1){ synchronized(str2){ System.out.println(str1 + str2); } } } } }; Thread trd2 = new Thread("My Thread 2"){ public void run(){ while(true){ synchronized(str2){ synchronized(str1){ System.out.println(str2 + str1); } } } } }; public static void main(String a[]){ MyDeadlockClass mdl = new MyDeadlockClass(); mdl.trd1.start(); mdl.trd2.start(); } }
How to call stored procedure in Hibernate
MySQL store procedure
Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data.
DELIMITER $$
CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20))
BEGIN
SELECT * FROM stock where stock_code = int_stockcode;
END $$
DELIMITER ;
In MySQL, you can simple call it with a call keyword :
CALL GetStocks('7277');
Hibernate call store procedure
In Hibernate, there are three approaches to call a database store procedure.
1. Native SQL – createSQLQuery
You can use createSQLQuery() to call a store procedure directly.Query query = session.createSQLQuery(
"CALL GetStocks(:stockCode)")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
Stock stock = (Stock)result.get(i);
System.out.println(stock.getStockCode());
}
2. NamedNativeQuery in annotation
Declare your store procedure inside the @NamedNativeQueries annotation. //Stock.java
...
@NamedNativeQueries({
@NamedNativeQuery(
name = "callStockStoreProcedure",
query = "CALL GetStocks(:stockCode)",
resultClass = Stock.class
)
})
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable {
Call it with getNamedQuery().
Query query = session.getNamedQuery("callStockStoreProcedure")
.setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
Stock stock = (Stock)result.get(i);
System.out.println(stock.getStockCode());
}
3. sql-query in XML mapping file
Declare your store procedure inside the "sql-query" tag.
<!-- Stock.hbm.xml -->
...
<hibernate-mapping>
<class name="com.mkyong.common.Stock" table="stock" ...>
<id name="stockId" type="java.lang.Integer">
<column name="STOCK_ID" />
<generator class="identity" />
</id>
<property name="stockCode" type="string">
<column name="STOCK_CODE" length="10"
not-null="true" unique="true" />
</property>
...
</class>
<sql-query name="callStockStoreProcedure">
<return alias="stock" class="com.mkyong.common.Stock"/>
<![CDATA[CALL GetStocks(:stockCode)]]>
</sql-query>
</hibernate-mapping>
Call it with getNamedQuery().Query query = session.getNamedQuery("callStockStoreProcedure")
.setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
Stock stock = (Stock)result.get(i);
System.out.println(stock.getStockC
Why multiple inheritance is not supported in java?
First of all try to understand what is diamond problem?
Consider the below diagram which shows multiple inheritance as Class D
extends both Class B & C. Now lets say we have a method in
class A
and Class B
& C
overrides that method in their own way. Now problem comes here –
Assume, method hello() is overridden in Class B and C.
Class D is extending both B & C, so now if Class D wants to use the same
method i.e. hello(), which method would be called ? the overridden method hello() of B or or C ?. Because of this ambiguity java doesn’t support multiple inheritance.
Also, multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc
and given that there are not many scenario on which you need multiple
inheritance its wise decision to omit it for the sake of simplicity.
Also java avoids this ambiguity by supporting single inheritance with
interfaces. Since interface only have method declaration and doesn't
provide any implementation there will only be just one implementation of
specific method hence there would not be any ambiguity.
However, you can achieve multiple inheritance in Java using interfaces. Assume in above diagram B and C is interface not a class, then class D can implement the method hello() and this will be common implementation in class D.
interface B { public void hello(); } interface C { public void hello(); } class D implements B, C { public void hello() { System.out.println(" Multiple inheritance example using interfaces"); } }
Subscribe to:
Posts (Atom)