What is JAXB?

It has become common for enterprise applications to exchange, represent any data using XML. It is possible to represent binary and character based data in XML files.

Read here Advantages of storing data in XML format.

And it would be often required to convert an object to an XML and vice versa.

Process of converting an object to XML is called Marshalling. And the process of converting XML to an object is called Un Marshalling.

J2EE has provided JAXB for the same. JAXB stands for Java Architecture for XML Binding.

JAXB is provided in package javax.xml

Below is an example for Marshalling, i..e converting an object to its XML representation.
This example has POJO classes Address8 and Employee8.
Employee8 and Address8 has composition relationship.
Annotations are used in Employee8 and Address8 classes, to specify XML Root Element, XML Elements and XML attributes.
MainAppl8 class creates marshaller, and marshalls Employee8 object to my_emp.xml XML file.


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
     public class Address8 {
    
    private int id;
    private String city;
    private int postCode;
 
    public Address8(){}


    @XmlElement(name="aId")  
    public int getId() {
        return id;
    }

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

    @XmlElement(name="aCity")  
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @XmlElement(name="aPostC")  
    public int getPostCode() {
        return postCode;
    }

    public void setPostCode(int postCode) {
        this.postCode = postCode;
    }
}
_________________________________________________________________________________________________________________
import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
import javax.xml.bind.annotation.XmlAccessorType;
  
@XmlRootElement
public class Employee8 {  
private int id;  
private String name;  
private float salary;  
private int age;
private Address8 address;

public Employee8(){}

@XmlAttribute(name="id")  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement(name="name")  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
@XmlElement(name="salary")  
public float getSalary() {  
    return salary;  
}  
public void setSalary(float salary) {  
    this.salary = salary;  
}  

@XmlElement(name="age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @XmlElement(name="address")  
    public Address8 getAddress() {
        return address;
    }

    public void setAddress(Address8 address) {
        this.address = address;
    }
}  
___________________________________________________________________________________________________________________
import java.io.FileOutputStream;  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.Marshaller;  
  
public class MainAppl8 {  
public static void main(String[] args) throws Exception{  
    JAXBContext contextObj = JAXBContext.newInstance(Employee8.class);  
  
    Marshaller marshallerObj = contextObj.createMarshaller();  
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  
    Address8 adr=new Address8();
      
    adr.setId(1);
    adr.setCity("Bangalore");
    adr.setPostCode(123456);
    
    Employee8 emp=new Employee8();
    emp.setId(2);
    emp.setAge(45);
    emp.setAddress(adr);
    emp.setName("Kiran Kumar");
    emp.setSalary(46000);
    
    marshallerObj.marshal(emp, new FileOutputStream("my_emp.xml"));  
       
}  
}  

JAXB marshall example(Netbeans)

Below is an example for UnMarshalling, i..e converting XML to an object. In this example XML String is converted into Employee object, using JAXB.

public class Employee {
 private String firstName;
 private String lastName;
 private String fatherName;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

  public String getFatherName() {
  return fatherName;
 }

 public void setFatherName(String fatherName) {
  this.fatherName = fatherName;
 }
}
______________________________________________________________________________________________________
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class CreateEmployeeFromXml {
 public static void main(String[] args) {
  try {
   String xml = "<Employee><firstName>Kiran</firstName><lastName>Kumar</lastName><fatherName>Kishore</fatherName></Employee>";
   JAXBContext jaxbc = JAXBContext.newInstance(Employee.class);
   Unmarshaller unmarshaller = jaxbc.createUnmarshaller();
   StreamSource ss = new StreamSource(new StringReader(xml));
   JAXBElement jbe = unmarshaller.unmarshal(ss,
     Employee.class);
   
   Employee employee = (Employee)jbe.getValue();
   System.out.println("Employee's First Name is" +  employee.getFirstName());
   System.out.println("Employee's Last Name is" +  employee.getLastName());
   System.out.println("Employee's father Name is" +  employee.getFatherName());
   
  } catch (JAXBException e) {
      System.out.println(e.getMessage());
   e.printStackTrace();
  }
 }
}

JAXB unmarshall example(Netbeans)

You may also like to read:
What is DTD in XML?
How many Servlet filters can be used?

What is static import? What are advantages and disadvantages of static import?

By static importing a class, all static members in that class can be directly used. This avoids using class name for each and every static member. Also, note that even pre defined classes like System,etc… can be static imported.

static import was introduced in Java 1.5 version
Below is an example of static import. As shown in below example, Test is a class in com.p1 package, and Test class has few static members.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
		return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
		return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
		return PI*Math.pow(radius, 2);
	}
	
}

In below code snippet, since com.p1.Test.* is imported using static, it is possible to use static members of com.p1.Test class directly, without using class name.

package com.p2;

import static com.p1.Test.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
	}
}

Can we use multiple static import

Yes, we can use multiple static import statement in a java file. How ever, ensure that there is no ambiguity in the static members of static imported classes.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
	return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
	return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
	return PI*Math.pow(radius, 2);
	}
	
	public static void display()
	{
	System.out.println("display() in com.p1.Test");
	}
}

package com.p3;

public class Abc {
	public static void display()
	{
	System.out.println("display() in com.p3.Abc");
	}
}

package com.p2;

import static com.p1.Test.*;
import static com.p3.Abc.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
		
	//below method call causes compiler error, as display() method
	//is available in both the classes, com.p1.Test and com.p3.Abc
	//display();
	}
}

Disadvantages of static import

Below are disadvantages of static import
1.This may arise readability issues.
2.It may also cause ambiguity, when same member is declared in more than one static imported classes.

You may also like to read:
What is use of static members
Can we have more than one static block
Role of static method in abstract class
how to use packages in Java

What is JAR File and How to create JAR File

A JAR File, stands for Java Archive file. Like ZIP file, JAR is compressed file format, which is used to share software resources required for Java Applications. For example Hibernate, Struts, Spring,etc… provide their framework implementation through multiple JAR files. Similarly you can provide Jar files to your clients, or other Teams dependent on your Classes or packages. Even JDBC driver is provided as a Jar file. A Jar file may contain
1. bunch of .class files
2. any other resource files, like images, icons,etc… required by .class files

Also note that a jar file can have multiple packages or sub packages.

How to create JAR file in Eclipse

Below are the steps involved in creating jar file in Eclipse IDE.
1. Create a Java Project
2. Add class Files
3. Build the Project, do Testing
4. Right click on Project, and Select Export

export jar file
export jar file

5. In Export Window, select java, then JAR file, then Next button.
create-jar
create-jar

6. Now Below JAR File Specification window appears. Select various options, based on your requirement.
Select or unselect appropriate checkbox to specify if you want to Export generated class files and resources or Export Java source files and resources as well.

jar-file-specification
jar-file-specification

Browse to select a location for the JAR file, which will get created.

Select or unselect, Compress the contents of the JAR file checkbox.
Select or unselect, Overwrite existing files without warning checkbox. If you unselect this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten.

In this way you can create JAR file, out of your class files, and other required resources, and distribute it.

You may also like to read:

How to Compress and Uncompress file in Java


How to create a Jar file in a Netbeans Project?
How to create Jar file, in run time, using Java program?
How to add an external Jar file to a Eclipse Project?
How to add an external jar file to a Netbeans Project?

What is the difference between DTD and XSD

Before getting into the difference between DTD and XSD, lets take a look at XML, eXtensible Markup Language.

XML is basically used to store, exchange or transfer between Software Programs or Applications.
Almost any complex data can be represented using XML.
Most of the popular software languages and third party software provides XML parsers.
Application Settings or Configurations, are generally stored in a XML file.

Difference between XML and HTML

Though both are Markup Languages. Purpose of both XML and HTML is entirely different.
HTML(Hyper Text markup Language) is used to display web pages on Web Browser. Web Browsers like Chrome, Firefox, Internet Explorer,etc… parses and renders the HTML file being server, from Web Server.
In HTML tags are pre defined, and we cannot create new HTML Tags.
Another Advantage of XML is data represented or transferred is language and platform independent.

But purpose of XML is to store, exchange or transfer data.In XML we can create our own tags or elements, and we can specify name of the tag, data type, etc…

How DTD and XSD differ

1. Both DTD and XSD are used to describe an XML document.
2. DTD stands for Document Type Definition. XSD stands for XML Schema Docment.
3. DTD is older approach, where as XSD is latest one.
4. XSD has almost replaced DTD, though old ones continue to exist in DTD.
5. DTD provide only two data types CDATA and PCDATA, where as XSD provides more data types such as int, decimal, etc…
6. XSD has more control over restricting only certain values to an element or Attribute like only positive or negative values are allowed etc…, where as DTD do not restrict
7. XSD supports namespaces to avoid name collision between elements having same name.
8. XSD uses XML syntax, but DTD does not.

You may also like to read:
how to use Marquee tag in HTML
input tags in HTML

HTML ordered list and un ordered list tags

Below is an example showing how to display ordered and un ordered lists in HTML.

<html>
<head><title>Institute Trainign courses</title></head>
<BODY bgcolor="#E67A32">
<font color="#FFF">
Sample Ordered List
<ol type="1">
<li>Adv Java</li>
<li>Core Java</li>
<li>MySQL</li>
<li>Oracle</li>
</ol>
Sample Un Ordered List
<ul>
<li>Adv Java</li>
<li>Core Java</li>
<li>MySQL</li>
<li>Oracle</li>
</ul>
</font>
</body>
</html>

Core Java Assignments

1. Create two String objects and assign with different strings. For eg.
String str1=”Hello”;
String str2=”mayi”;

Write a program to create a new String object, as odd characters for str1, and even characters from str2
Considering above example: output: Hmealylio

2.Take six different one digit integers. output the largest integer that can be created, by combining these six integers. NOTE: six digits can be same or different

3.Two dimensional arrays(with same number of rows and columns), each element stores an object of below class

class Abc{
int i;
}

Write a program to change rows to columns, and columns to rows.

4.serialize employee objects, and write a client which serializes employee objects to OutputStream, of a socket. Receive the object stream, at the server, and write to a file.

5. Take some String as below
String str=”Hello, how are you? Can you come here?”;

create two child threads, from main thread. Each child thread prints one character at a time. But the thread need to be locked until it completes printing the word. Hint: you can use synchronized method or block.

6. For a given integer value, for eg. 4823, print it in words, like four thousands, eight hundreds and twenty three.

7. Find transpose a matrix of given number of rows and cols?

8. multiply two matrices, and generate third matrix?

9. print factorial of a given number, using recursion?

10. Ask user to enter a name, if name is numeric, then throw NotaNameException. Create your own Exception called NotaNameException

11. Declare and initialize an array of size 5, each element can be any number between 0 and 9. Print each element in string equivalent with comma separated.
For eg. int arr[]={4,2,5,1,6}; need to print four,two,five,one,six

12. Billing amount is entered by shop keeper. If the bill amount is less than 5000, give 5% discount.
If bill amount between 5001 and 10000, give 8% discount.
If bill amount between 10000 and 20000, give 10% discount.
If bill amount between 20001 and 50000, give 15% discount.
If bill amount is greater than 50001, give 18% discount.

In all cases compute, the result bill amount, after giving discount.

13. Declare an array of Object elements. Store objects of different types in the array. Fetch each element(which is an object) from array, and print object’s class name, methods available, etc… by using Reflection.

14. A String is provided in the format 19,8,23 . Write a program to extract integers, check if these numbers occur in sequential order.

15. Declare an array of odd length. In this array swap only elements with even index.

16. Write a program to print a String “abcdef”
(1) fedcba
(2) a
ab
abc
abcd
abcde
abcdef
(3)a
b
c
d
e
f

(4) a
b
c
d
e
f
(5)a f

b e

cd

17.Write a program to convert a decimal number to binary form, and print.

18.Write a program to convert a decimal number to octal form, and print.

19.Write a program to print multiples of 3 or 5 between 1000 and 1050.

20.Write a program to print multiples of 23 between 2000 and 1000, in reverse order.

21.Write a program to print all numbers having same digits between 10 and 999. For eg. 22 or 555,etc…

22.Display all prime numbers between 1 and 100. Note: A Prime number is a number whcih is divisible only by 1 or by itself. Eg. 3 is prime number.

23.Write a program to print all numbers, which has sequence digits, for eg. 234, 678, 1234, which are between 10 and 1000.

You may also like to read:
More Core Java assignments
Core Java assignments

Frequently asked Project interview Questions

How to display checkbox using HTML

On Webpages, checkbox is used to select one or multiple items in each group of checkboxes.

Below is simple example of using checkboxes, in HTML

<html> 
<body> 
<form action="abcd.jsp" method="POST"> 
<input type="checkbox" name="rose" checked="checked"/> Rose
<input type="checkbox" name="lilly"/> Lilly
<input type="checkbox" name="jasmine" checked="checked"/> Jasmine
<input type="submit"value="Select Flower"/> 
</form> 
</body> 
</html>

You may also like to read:
input tag in html
html marquee tag
favorite icon on webpages

Purpose of Input control in HTML

On a HTML webpage, Input Controls are displayed to get input from user.
On Web pages, user can enter/select/submit data, using Input Controls.
<input type=“text” name=“username” value=“” />
Other input Controls are
password
checkbox
radio
hidden
file
submit
Reset

<label for=“”> tag can be used to display label to any input control

<html>
<head><title>Just Test title</title></head>
<body bgcolor="#00ff00">
<center><h1>This is heading</h1></center><br>
<form action="./x/y/z/abc.jsp" method="post">

<font color="#FFFFFF">Enter Name:  
<input type="text" name="mytext" value="" /><br>
Enter Password:<input type="password" name="pwd" value="" /><br>
Select Hobbies:<input type="checkbox" name="cb1" /> Reading<br>
<input type="checkbox" name="cb2" checked/> Driving<br>
<input type="checkbox" name="cb3" /> Swimming<br>
<input type="checkbox" name="cb4"/> Others<br><br>

Select Age: Between<input type="radio" name="rd1"/> 20 and 30<br>
<input type="radio" name="rd1"/> 30 and 40<br>
<input type="radio" name="rd1"/> 40 and 50<br>
<input type="radio" name="rd1"/> Above 50<br>

Select Option: <select name="optn">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">THree</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select><br>
</font>©
<input type="button" name="btn" value="Click here"/> 
<input type="submit" name="submit1" value="Click to Signup" />  
<input type="reset" name="Reset1" value="Reset Values" /><br>
</form>
</body>
</html>

In HTML, how to use marquee tag

You might have seen, on web pages wherein text or any content scrolls on webpage left to right, top to bottom,etc… marquee HTML tag need to be used to achieve the same.

Below are attributes of HTML
direction – indicates direction of scroll
scrolldelay – by increasing the value, scrolling can be made slower, and vice versa
scrollamount – smoothness of scroll can be adjusted, by changing the value.

Below is an example of the same, please follow inline comments to change direction of scroll.

<html>
<head>
<title>HTML marquee Example</title>
</head>
<body>
<!--other values for direction are up,down,right,left-->
<marquee height="25%" direction="left" scrolldelay="5" scrollamount="8">
<img src="logos.JPG" >
This is an example of marquee<br>
line1<br>
line2<br>
line3<br></marquee>
</body>
</html>

In HTML, how to display favorite icon of a website

Almost all professional websites, need favorite icon, which will be displayed on top bar of the Browser.

Below is an example HTML code, on how to display favorite icon of a website.

<html>
<head>
<link rel="shortcut icon" href="./first.ico" />
<!-- ico is an image format used for icons 
Here gif and other img formats also can b used
-->
<title>Simple Title</title></head>
<body>
This is First HTML Page<br>
can u see this?
</body>
</html>