How to check duplicated value in array


package com.test;

import java.util.Set;
import java.util.HashSet;

public class CheckDuplicate
{
	public static void main(String args[])
	{
		String [] sValue = new String[]{"a","b","c","d","","","e","a"};

		if(checkDuplicated_withNormal(sValue))
			System.out.println("Check Normal : Value duplicated! \n");
		if(checkDuplicated_withSet(sValue))
			System.out.println("Check Set : Value duplicated! \n");

	}

	//check duplicated value
	private static boolean checkDuplicated_withNormal(String[] sValueTemp)
	{
		for (int i = 0; i < sValueTemp.length; i++) {
			String sValueToCheck = sValueTemp[i];
			if(sValueToCheck==null || sValueToCheck.equals(""))continue; //empty ignore
			for (int j = 0; j < sValueTemp.length; j++) {
					if(i==j)continue; //same line ignore
					String sValueToCompare = sValueTemp[j];
					if (sValueToCheck.equals(sValueToCompare)){
							return true;
					}
			}

		}
		return false;

	}

	//check duplicated value
	private static boolean checkDuplicated_withSet(String[] sValueTemp)
	{
		Set<String> sValueSet = new HashSet<String>();
		for(String tempValueSet : sValueTemp)
		{
			if (sValueSet.contains(tempValueSet))
				return true;
			else
				if(!tempValueSet.equals(""))
					sValueSet.add(tempValueSet);
		}
		return fals

Percentage Calculation in Java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class Percent {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“enter the total no.of sub”);
int n = Integer.parseInt(br.readLine());
int marks[] = new int[n];
int i, tot = 0;
for (i = 0; i < n; i++) {
System.out.println(“enter ur marks”);
marks[i] = Integer.parseInt(br.readLine());
tot = tot + marks[i];
}
System.out.println(“total marks: ” + tot);
System.out.println(“percentage of marks: ” + (float) tot / n);
}
}

What are Marker or Tag Interfaces?


An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations.

Java Marker Interface Examples

  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Why we need Marker Interface?

e.g.  Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.

Suppose the interface Clonable is neither implemented by a class named Myclass nor it’s any super class, then a call to the method clone() on Myclass’s object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.

equals() and hashCode() methods of Object Class


HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. In all these Collection classes except HashSet, objects are stored as key-value pairs. For the storage and the retrieval of any user-defined objects it is a good practice to override the following methods which is mentioned below,

  • hashCode()
  • equals()

These methods are available in the Object class and hence available to all java classes.Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.

hashCode() method

This method returns a hashcode value as an int for the object. Default implementation for hashcode() should be overridden in order to make searching of data faster. The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.

equals() method

This method returns a boolean which specifies whether two objects are equal or not. The default implementation of equals() method given by the Object Class uses the ‘==’ operator to compare two object references, and returns true only if they refer to the same object. But, we can meaningfully re-define this equals() method to have en equality check based on our own criterias.

Consider the following code, which defines two user defined classes Employee and EmployeeId which are supposed to be stored in a Map.

Employee.java

 

public class Employee {

private String name;

public Employee(String name){

this.name = name;

}

public String toString(){

return name;

}

}

EmployeeId.java

 

public class EmployeeId {

private String id;

public EmployeeId(String id){

this.id = id;

}

public String toString(){

return id;

}

}

The following class makes use of the above classes by storing it in a Map for later retrieval. We are adding Employee objects into the Map keyed with Employee Id.

HashCodeTest.java

 

public class HashCodeTest {

public static void main(String[] args) {

Map<EmployeeId, Employee> employees = new HashMap<EmployeeId, Employee>();

employees.put(new EmployeeId(“111”), new Employee(“Johny”));

employees.put(new EmployeeId(“222”), new Employee(“Jeny”)); // Line A

employees.put(new EmployeeId(“333”), new Employee(“Jessie”));

Employee emp =  employees.get(new EmployeeId(“222”)); // Line B

System.out.println(emp); // Line C

}

}

In Line B, we try to retrieve the Employee object who has Employee Id with a value of 222. We expect the output to be ‘Jeny’, because the Employee with Employee Id (222) was already there in the Collection, but surprisingly, the output of the above code is null. The reason is that we did not override the equals() method for EmployeeId and Employee classes because the default implementation of equals() in the Object class considers the new EmployeeId(“222”) in the put statement and new EmployeeId(“222”) in the get statement as two different instances, and hence the call to get() in Line B returns null.

Let us look at how the same code works when we provide our desired implementation for hashcode() and equals() methods. We basically override hashcode() here just to make the object to be searched fast.

Employee.java

 

public class Employee {

private String name;

public Employee(String name){

this.name = name;

}

public String toString(){

return name;

}

 

@Override

public boolean equals(Object obj){

if(obj == null) {

return false;

}

if(obj.getClass() != getClass()){

return false;

}

Employee emp = (Employee)obj;

if(this.name == emp.name){

return true;

}

return false;

}

@Override

public int hashCode(){

return name.hashCode();

}

}

EmployeeId.java

 

public class EmployeeId {

private String id;

public EmployeeId(String id){

this.id = id;

}

public String toString(){

return id;

}

 

public boolean equals(Object obj){

if(obj == null)

return false;

if(obj.getClass() != getClass()){

return false;

}

 

EmployeeId empId = (EmployeeId)obj;

if(this.id == empId.id){

return true;

}

return false;

}

@Override

public int hashCode(){

return id.hashCode();

}

}

Now, we get the desired output ‘Jeny’, because as per our implementation for the equals() method, the new EmployeeId(“222”) in the put statement and new EmployeeId(“222”) in the get statement are considered one and the same.

 

Sorting of int values in an array


package in.javatutorials.test;

public class ManualSorting {
int[] arr = { 12, 1, 3, 22, 222, -9 };
public void ascendingOrder() {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int temp = 0;
if (arr[i] < arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
System.out.print(arr[i] + " ,");
}
System.out.println();
}
public void descendingOrder() {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int temp = 0;
if (arr[i] > arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
System.out.print(arr[i] + " ,");
}
System.out.println();
}
public static void main(String arr[]) {
ManualSorting ms = new ManualSorting();
ms.ascendingOrder();
ms.descendingOrder();
}
}

Read Properties file in Java


package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
public class ReadPropetiesFile {
public static void main(String a[]){
String fileName = "test.properties";
ReadPropetiesFile readProp = new ReadPropetiesFile();
readProp.readProperties(fileName);
}
public void readProperties(String fileName){
try {
ResourceBundle labels = ResourceBundle.getBundle(fileName, Locale.ENGLISH);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
    String key = (String)bundleKeys.nextElement();
    String value = labels.getString(key);
    System.out.println("key = " + key + ", " +   "value = " + value);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}

Interface in Java


Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy.  Using Interface, you can specify what a class must do but not how it does.

  1. A class can implement more than one Interface.
  2. An Interface can extend one or more interfaces, by using the keyword extends.
  3. All the data members in the interface are public, static and Final by default.
  4. An Interface method can have only Public, default and Abstract modifiers…. More

Difference between Struts and JSF


Struts is an Action framework and JSF is component framework.
Action Framework: Struts (both 1 and 2) are action frameworks. In essence they give you the ability to map URLs to activities and code on the back end. Here, the layout and workflow tends to be more page oriented. As a developer you tend to interact with the HTTP request cycle directly, though Struts 2 helps isolate at least the binding of the request data to the action implementation classes.
Action framework coders can have more control of the structure and presentation of URLs, since their systems are more intimately tied to them compared to a component framework.
Component Framework: In a component framework, artifacts that are rendered on the page are initially developed as individual components, much like in modern GUI “fat client” libraries. You have components, they have events, and your code is written to work with those events against the components. Most of the time, in mainstream development, your code is pretty much ignorant of the HTTP request cycle and processing.
JSF eliminated the need of Form Bean and DTO classes as it allows the use of same pojo class on all tiers of the application because of the Backing Bean.
In struts framework we can access the request and response objects directly, as in case of JSF we can access request and response objects indirectly.
Struts has a more sophisticated controller architecture than does JavaServer Faces technology. Struts is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller.
In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.
Struts frameworks is  better for “web sites”, site like this one, sites that focus on delivering content to the user. Where it’s mostly a “read only” experience for the end user who is likely to want to bookmark things, come back to arbitrarily deep pages, etc.
JSF framework is better for CRUD screens, back office applications, lots of forms and controls, etc. Here, the workflow is more controlled. You tend to not get to a “detail” screen with going through the “list” screen or “header” screen first, for example.
struts validate full beans (validator.xml) jsf has a pluggable validator-mechanism

Difference between Abstract Class and Interface:


Most of the people confuses with Abstract class and interface. Here I am planning to share some information with examples, I hope this will help you more………

Simple abstract class looks like this:

public abstract class KarateFight{

public void bowOpponent(){

//implementation for bowing which is common for every participant       }

public void takeStand(){

//implementation which is common for every participant

}

public abstract boolean fight(Opponent op);

//this is abstract because it differs from person to person

}

The basic interface looks like this:

public interface KarateFight{

public boolean fight(Opponent op);

public Integer timeOfFight(String person);

}

The differences between abstract class an interface as fallows:

1.  Abstract class has the constructor, but interface doesn’t.

2.  Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.

3.  Abstract classes should have subclasses else that will be useless..

4. Interfaces must have implementations by other classes else that will be useless

5. Only an interface can extend another interface, but any class can extend an abstract class..

6.  All variable in interfaces are final by default

7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.

8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

9.  A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

10. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier

12.  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

13.  An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.

14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

15.  Abstract scope is upto derived class.

16.  Interface scope is upto any level of its inheritance chain.

Other Useful Links:

What are the differences between object and instance?

What are the differences between EAR, JAR and WAR file?

Differences between callable statements, prepare statements, createstatements

WEB Services Interview Questions


1)What is web Services ?
Getting the services through the web.

2)What is JAX-RPC?
JAX-RPC means java api for xml based RPC is a java api for developing and using web-services.
An RPC based web-service is a collection of procedures that can be called by remote client over the internet.
Ex: A typical RPC based web service is a stock quote service that takes a SOAP request for the price of a specified stock and returns the price via SOAP.

3)Explain about Web Services
A Web service, a server application that implements the procedures that available for clients to call, deployed on server-side container.
A web service can make itself available to potential clients by describing itself in a Web Service Description Language (WSDL) document.

4)What is WSDL?
WSDL is an XML document that gives all pertinent information about web service, the operation that can be called on it, parameters for those operations, and the location of where to send requests.
A web client can use WSDL document to discover the what the service offers and how to access it.

5)Explain some of the features of the web services?
Some of the features of the web services are:
1.Interoperability
Using JAX-RPC, a client written in a language other than Java programming language can access a web service developed and deployed on the Java platform. Conversely,a client written in the Java programming language can communicate with a service that was developed and deployed using some other platform.
2.Ease of use:
Using JAX-RPC makes the user to feel comfortable over the RPC. The internal complicated infrastructure, like marshaling, unmarshaling, and transmission details..etc, will be taken care automatically.
3.Advanced features

6)What makes interoperability is possible?
JAX-RPC support for SOAP and WSDL.

7)What is JAXM?
Java API for Messaging provides a standard way to send XML documents over the Internet from the Java platform. It is based on SOAP 1.1 and SOAP with attachments specifications, which define a basic framework for exchanging XML messages.
8)The features of JAXM over the RPC including JAX-RPC
a) One way(asynchronous)messaging.
b) Routing of message to more than one party.
c) Reliable messaging features such as guarantied delivery.

9)What is JAXR?
Java API for XML registries provides a convenient way to access standard business registries over the Internet. Using JAXR one can register the business registry and one can search for a business registry for other business.

10) What tools do you use to test your Web Services?

 SoapUI tool for SOAP WS and the Firefox “poster” plugin for RESTFul services.

11) What is the difference between SOA and a Web service? 

SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).

Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.