Monday 14 December 2015

Database cannot be opened due to inaccessible files or insufficient memory or disk space

Database 'db' cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server errorlog for details. 


Here is Solution/Fix/workaround of this problem.

1. check the DB status, most of the time , it will return 1

use master
select databaseproperty('dbname','isShutdown')

2. Change the database to offline to clear the db status 

use master
alter database
 dbname set offline

3. Now change the database to online, at this step log file and data files will be verified by sql server


use master
alter database dbname set online

Tuesday 24 November 2015

Serialization

Serialization is a mechanism by which you can save or transfer the state of an object by converting it to a byte stream. This can be done in java by implementing Serialiazable interface. Serializable is defined as a marker interface which needs to be implemented for transferring an object over a network or persistence of its state to a file. Since its a marker interface, it does not contain any methods. Implementation of this interface enables the conversion of object into byte stream and thus can be transferred. The object conversion is done by the JVM using its default serialization mechanism.Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object’s state in a file. Additionally, manipulation of the state of an object as streams of bytes is required.

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

What would happen if the SerialVersionUID of an object is not defined?

If you don't define serialVersionUID in your serilizable class, Java compiler will make one by creating a hash code using most of your class attributes and features. When an object gets serialized, this hash code is stamped on the object which is known as the SerialVersionUID of that object. This ID is required for the version control of an object. SerialVersionUID can be specified in the class file also. In case, this ID is not specified by you, then Java compiler will regenerate a SerialVersionUID based on updated class and it will not be possible for the already serialized class to recover when a class field is added or modified. Its recommended that you always declare a serialVersionUID in your Serializable classes.


Hibernate

Hibernate ORM (Hibernate in short) is an object-relational mapping framework for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Persistence:

Hibernate ORM is concerned with helping your application to achieve persistence.

we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.



Hibernate vs myBatis

Hibernate works well for case 1 allowing you to just make a POJO and persist/update it. It also does this quickly, unless your domain is quite large.
myBatis is great for fetch queries (case 2) where you just want an answer. Hibernate would attempt to load the entire object graph and you'd need to start tuning queries with LazyLoading tricks to keep it working on a large domain. This is important when running complex analytic queries that don't even return entity objects. Hibernate only offers SqlQuery and bean Transformers in this case with huge default types like BigDecimal, while myBatis could easily map to a simple POJO non-entity.
These two cases are the difference between Commands where you want to change the domain data and Responses where you just want to fetch some data.
So, consider these two cases and what your application does. If you have a simple domain and just fetch information, use myBatis. If you have a complex domain and persist entities, use Hibernate.

MyBatis

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

Simple example:

1. database.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mydb
db.username= ************
db.password= ************


2. configuration.xml

<configuration>
    <properties resource="database.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mybatis/demo/user/UserMapper.xml"/>
    </mappers>
</configuration>

3. UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.mybatis.my.user.dao.UserDAO"></mapper>

4. ConnectionFactory Class

package com.mybatis.my.util;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ConnectionFactory {
    private static SqlSessionFactory sqlMapper;
    private static Reader reader;
    static{
        try{
            reader    = Resources.getResourceAsReader("configuration.xml");
            sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession(){
        return sqlMapper;
    }
}

5. UserVO Class

package com.mybatis.my.user.vo;

import java.io.Serializable;


public class UserVO implements Serializable {
    
    private static final long serialVersionUID = 4872640461000241018L;
    private long id;
    private String fullName;
    private String address;
    private String email;
    private String mobile;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    
     @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserVO other = (UserVO) obj;
        if (fullName == null) {
            if (other.fullName != null)
                return false;
        } else if (!fullName.equals(other.fullName))
            return false;
        if (id != other.id)
            return false;
        return true;
    }

}


6. UserDAO Interface


package com.mybatis.my.user.dao;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.mybatis.my.user.vo.UserVO;

public interface UserDAO {
    String MQL_GET_ALL_USERS  = "select * from users";
    String MQL_GET_USER_BY_ID = "select * from users where id = #{id}";
    String MQL_CREATE_USER    = "insert into users (fullName, email, address, mobile) values (#{fullName},#{email},#{address},#{mobile})";
    String MQL_UPDATE_USER    = "update users set fullName=#{fullName}, email=#{email}, address=#{address}, mobile=#{mobile} where id=#{id}";
    String MQL_DELETE_USER    = "delete from users where id=#{id}";
    @Select(MQL_GET_ALL_USERS)
    public List<uservo> getAllUsers() throws Exception;
    @Select(MQL_GET_USER_BY_ID)
    public UserVO getUserById(long id) throws Exception;
    @Insert(MQL_CREATE_USER)
    public int doCreateUser(UserVO vo) throws Exception;
    @Update(MQL_UPDATE_USER)
    public int doUpdateUser(UserVO vo) throws Exception;
    @Delete(MQL_DELETE_USER)
    public int doDeleteUser(UserVO vo) throws Exception; 
}



7. UserBO Class

package com.mybatis.my.user.bo;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.mybatis.my.util.ConnectionFactory;
import com.mybatis.my.user.dao.UserDAO;
import com.mybatis.my.user.vo.UserVO;

public class UserBO {
    public List<uservo> getUsers() throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            List<uservo> users= dao.getAllUsers();
        session.close();
        return users;
    }
    public UserVO getUserById(long id) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            UserVO user =dao.getUserById(id);
        session.close();
        return user;
    }
    public UserVO createUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            dao.doCreateUser(vo);
        session.commit();
        session.close();
        return vo;
    }
    public UserVO updateUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            dao.doUpdateUser(vo);
        session.commit();
        session.close();
        return vo;
    }
    public int deleteUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            int cnt= dao.doDeleteUser(vo);
        session.commit();
        session.close();
        return cnt;
    }
    public static void main(String a[])throws Exception{
        UserBO bo = new UserBO();
        UserVO vo= new UserVO();
        vo.setAddress("Test");
        vo.setEmail("test@gmail.com");
        vo.setFullName("Full Name");
        vo.setMobile("12411515");
        System.out.println(bo.createUser(vo));
        System.out.println(bo.getUsers());
        vo= bo.getUserById(1);
        vo.setAddress("Test Updated11 Address");
        vo.setEmail("testupdated@gmail.com");
        vo.setFullName("Full Name Test");
        vo.setMobile("1241151511");
        bo.updateUser(vo);
        vo=bo.getUserById(1);
        System.out.println(vo);
        bo.deleteUser(vo);
    }

}

Monday 23 November 2015

Spring MVC 3.2 Execution Flow

Step 1: First request will be received by DispatcherServlet
Step 2: DispatcherServlet will take the help of HandlerMapping and get to know theController class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModeAndView object (contains Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

AJAX VS JQUERY

AJAX

  1. AJAX = Asynchronous JavaScript and XML.
  2. AJAX is a technique for creating fast and dynamic web pages.
  3. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
  4. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

JQUERY

  1. JQuery is a lightweight, "write less, do more", JavaScript library.
  2. The purpose of jQuery is to make it much easier to use JavaScript on your website.
  3. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
  4. jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.


Thursday 29 October 2015

Fail- fast iterator and Fail-safe iterator


Java iterator provides us with interface to parse the items of the underlying collection.
When we are using the iterator the underlying collection should not be modified.
If this treaty is not honoured and it is possible in a multi-threaded environment, then we get a ConcurrentModificationException.

What is the difference between Fail- fast iterator and Fail-safe iterator ?

Fail fast : it may fail ... and the failure condition is checked aggressively so that the failure condition is detected before damage can be done.

 This behaviour is not guaranteed.
 Detecting modification in the collection and parsing the collection is not done synchronously.
 Modification on the collection may go unnoticed under certain circumstances.
 So while programming, this behaviour should not be banked upon. Example for fail fast iterators are ArrayList, Vector, HashSet.

 fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.

fail safe : it won't fail.
 iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator.
Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException in Java.

 Even if the underlying collection is modified, it does not fail by throwing ConcurrentModificationException.
 When an iterator is created, either it is directly created on the collection, or created on a clone of that collection. One example which supports failsafe iterator is ConcurrentHashMap.


 ConcurrentModificationException : Fail Fast and Fail Safe iterators
The ConcurrentModificationException is thrown if the Collection is modified while Iterating over the data structure.
We know that the collection represents a set of objects for which it manages an internal data structure (i.e. an Object array). Now when we want to iterate over the collection of objects. We have two approaches:

1. Fail Fast : In this case the iterator refers the internal data structure directly (i.e. object array) reading the objects. Here it considers the underlying data structure (i.e. the object[]) is not modified while iterating through the collection. To do this it manages an internal flag which is set on any modification to the data structure (like add / remove), and every time we call the iterator to get the next element it checks the flag. If it finds the data was modified after this iterator was created, it throws exception; ConcurrentModificationException.

2. Fail Safe : In this case the iterator will make a copy of the internal data structure and iterates over the copied data structure. Thus any modifications done to the internal data structure will not effect the iterator. In this case we dont find ConcurrentModificationException. But in this approach we can find the following two issues:
a. The overhead of copying the data structure (time and memory)
b. The fail safe iterator doesnt guarantees the data being read is the data currently in the data structure with the created collection.
The java.util.Iterator is implemented using fail fast approach. That means using the Iterator (i.e. the iterator() method of List) will not result in creating a copy of internal object array but will reset the flag.
The java.util.Enumeration is a fail safe approach implemented. That means using the Enumeration (like elements() method of Vector) results to create a copy of internal data structure.

Fail fast or fail safe – which is better?

fail fast is best.


a. Fail-fast throw ConcurrentModificationException while Fail-safe does not.
b. Fail-fast does not clone the original collection list of objects while Fail-safe creates a copy of the original collection list of objects.

Monday 26 October 2015

Generics

The Java Generics features were added to the Java language from Java 5.

Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at runtime which was quite frequent error in Java code, for those who doesn’t know what is type-safety at compile time, it’s just a check by compiler that correct Type is used in correct place and there should not be any ClassCastException.


There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.

3)  Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

Friday 16 October 2015

Synchronization


Synchronization in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization?

The synchronization is mainly used to

To prevent thread interference.
To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

Process Synchronization
Thread Synchronization



Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the method.

main point :

Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.

Synchronized method

Synchronized method is used to lock an object for any shared resource.

Difference between synchronized method vs block in Java

1.One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code.

2.Synchronized block provide control over lock, as you can use arbitrary lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword  or class level lock, if its static synchronized method.

3. Synchronized block can throw throw java.lang.NullPointerException.

4. In case of synchronized method, lock is acquired by thread when it enter method and released when they leaving method, either normally or by throwing Exception.
On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

The difference is in which lock is being acquired:

synchronized method acquires a method on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.




Tuesday 29 September 2015

LDAP(Lightweight Directory Access Protocol)

LDAP is mostly used by medium-to-large organi­zations.

"LDAP-aware" client programs can ask LDAP servers to look up entries in a wide variety of ways. LDAP servers index all the data in their entries, and "filters" may be used to select just the person or group you want, and return just the information you want.

LDAP is used to look up encryption certificates, pointers to printers and other services on a network, and provide "single signon" where one password for a user is shared between many services. LDAP is appropriate for any kind of directory-like information, where fast lookups and less-frequent updates are the norm.

As a protocol, LDAP does not define how programs work on either the client or server side. It defines the "language" used for client programs to talk to servers (and servers to servers, too). On the client side, a client may be an email program, a printer browser, or an address book. The server may speak only LDAP, or have other methods of sending and receiving data—LDAP may just be an add-on method.

If you have an email program (as opposed to web-based email), it probably supports LDAP. Most LDAP clients can only read from a server. Search abilities of clients (as seen in email programs) vary widely. A few can write or update information, but LDAP does not include security or encryption, so updates usually requre additional protection such as an encrypted SSL connection to the LDAP server.

If you have OS X and access to an LDAP server, you can enter your LDAP account into System Preferences--Internet Accounts. At bottom of the right pane, click Add Other Account, then choose the LDAP account option. This lets Address Book look up info from your server.

LDAP also defines: Permissions, set by the administrator to allow only certain people to access the LDAP database, and optionally keep certain data private. Schema: a way to describe the format and attributes of data in the server. For example: a schema entered in an LDAP server might define a "groovyPerson" entry type, which has attributes of "instantMessageAddress", and "coffeeRoastPreference". The normal attributes of name, email address, etc., would be inherited from one of the standard schemas, which are rooted in X.500 (see below).

LDAP was designed at the University of Michigan to adapt a complex enterprise directory system (called X.500) to the modern Internet. X.500 is too complex to support on desktops and over the Internet, so LDAP was created to provide this service "for the rest of us."

LDAP servers exist at three levels: There are big public servers, large organizational servers at universities and corporations, and smaller LDAP servers for workgroups. Most public servers from around year 2000 have disappeared, although directory.verisign.com exists for looking up X.509 certificates. The idea of publicly listing your email address for the world to see, of course, has been crushed by spam.

While LDAP didn't bring us the worldwide email address book, it continues to be a popular standard for communicating record-based, directory-like data between programs.

Monday 28 September 2015

Application server Vs Web server



An application server is a machine (an executable process running on some machine, actually) that "listens" (on any channel, using any protocol), for requests from clients for whatever service it provides, and then does something based on those requests. (may or may not involve a respose to the client)

A Web server is process running on a machine that "listens" specifically on TCP/IP Channel using one of the "internet" protocols, (http, https, ftp, etc..) and does whatever it does based on those incoming requests... Generally, (as origianly defined), it fetched/generated and returned an html web page to the client, either fetched from a static html file on the server, or constructed dynamically based on parameters in the incoming client request.

Application servers exposes business logic to a client. So its like application server comprises of a set of methods(not necessarily though, can even be a networked computer allowing many to run software on it) to perform business logic. So it will simply output the desired results, not HTML content. (similar to a method call). So it is not strictly HTTP based.

But web servers passes HTML content to web browsers (Strictly HTTP based). Web servers were capable of handling only the static web resources, but the emergence of server side scripting helped web servers to handle dynamic contents as well. Where web server takes the request and directs it to the script (PHP, JSP, CGI scripts, etc.) to CREATE HTML content to be sent to the client. Then web server knows how to send them back to client. BECAUSE that's what a web server really knows.

Having said that, nowadays developers use both of these together. Where web server takes the

java SE 4 to 8 features

New features in Java SE 8

Lambda Expressions
Pipelines and Streams
Date and Time API
Default Methods
Type Annotations
Nashhorn JavaScript Engine
Concurrent Accumulators
Parallel operations
PermGen Error Removed
TLS SNI

New features in Java SE 7

Strings in switch Statement
Type Inference for Generic Instance Creation
Multiple Exception Handling
Support for Dynamic Languages
Try with Resources
Java nio Package
Binary Literals, underscore in literals
Diamond Syntax
Automatic null Handling

New features in Java SE 6

Scripting Language Support
JDBC 4.0 API
Java Compiler API
Pluggable Annotations
Native PKI, Java GSS, Kerberos and LDAP support.
Integrated Web Services.
Lot more enhancements.

New features in J2SE 5.0

Generics
Enhanced for Loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Metadata (Annotations)
Instrumentation

New features in J2SE 1.4

XML Processing
Java Print Service
Logging API
Java Web Start
JDBC 3.0 API
Assertions
Preferences API
Chained Exception
IPv6 Support
Regular Expressions
Image I/O API

XMl Parsing

There are 3 main parsers for which I have given sample code:
DOM Parser
SAX Parser
StAX Parser

Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.


Example on DOM parsing :

my.xml

<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>nag</firstname>
<lastname>R</lastname>
<nickname>King</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>sang</firstname>
<lastname>lee</lastname>
<nickname>lee</nickname>
<salary>200000</salary>
</staff>
</company>



import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

File fXmlFile = new File("my.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("staff");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

}
}
    } catch (Exception e) {
e.printStackTrace();
    }
  }

}

Friday 25 September 2015

String vs StringBuffer vs StringBuilder

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = " hi " ;

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hi") ;
// The above object stored in heap and its value can be changed .
demo1.Append(" king! ")
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .


StringBuilder demo2= new StringBuilder("Hi");
// The above object is stored in the heap and its value can be modified
demo2=new StringBuilder("end");
// Above statement is right as it modifies the value which is allowed in the StringBuilder

import java.lang.*;

public class test {

   public static void main(String[] args) {

   StringBuilder str = new StringBuilder("hi ");
   System.out.println("string = " + str);
 
   // appends the string argument to the StringBuilder
   str.append("king!");
   // print the StringBuilder after appending
   System.out.println("After append = " + str);
 
 
   }
}

output :

string = hi
After append = hi king!


Conclusion :

string vs string biffer vs string builder ?

string string immutable ,

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.



JSON Parsing

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/** Program to parse data from json file**/


public class JsonSimpleExample {
     public static void main(String[] args) {

JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("<file location>"));

JSONObject jsonObject = (JSONObject) obj;

String name = (String) jsonObject.get("name");
System.out.println(name);

long age = (Long) jsonObject.get("age");
System.out.println(age);

// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

     }

}

JAXB


jaxb
stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.




@XmlRootElement specifies the root element for the xml document.

@XmlAttribute specifies the attribute for the root element.


@XmlElement specifies the sub element for the root element.

Java pojo:

import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement  
public class Profile{  
    private int id;  
    private String name;  
  
public Profile() {}  
public Profile(int id, String name) {  
    super();  
    this.id = id;  
    this.name = name;  
}  
@XmlAttribute  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}    

}  


ObjectToXml.java::


import java.io.FileOutputStream;  
  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.Marshaller;  
  
  
public class ObjectToXml {  
public static void main(String[] args) throws Exception{  
    JAXBContext contextObj = JAXBContext.newInstance(Profile.class);  
  
    Marshaller marshallerObj = contextObj.createMarshaller();  
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  
    Profile p1=new Profile(1,"Vimal Jaiswal");  
      
    marshallerObj.marshal(p1, new FileOutputStream("profile.xml"));  
       
}  
}  


xml to object::

import java.io.File;  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.JAXBException;  
import javax.xml.bind.Unmarshaller;  
  
public class XMLToObject {  
public static void main(String[] args) {  
     try {    
            File file = new File("profile.xml");    
            JAXBContext jaxbContext = JAXBContext.newInstance(Profile.class);    
         
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    
            Profile p=(Profile) jaxbUnmarshaller.unmarshal(file);    
            System.out.println(p.getId()+" "+p.getName());  
              
          } catch (JAXBException e) {e.printStackTrace(); }    
         
}  

}