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
Core Java
How to create XML file in Java
package com.test;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXMLInJava {
public static void main(String argv[]) {
CreateXMLInJava createXml = new CreateXMLInJava();
createXml.createXML();
}
public void createXML() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(“Company”);
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement(“Dept”);
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute(“id”);
attr.setValue(“1”);
staff.setAttributeNode(attr);
// can be written as
// staff.setAttribute(“id”, “1”);
// firstname elements
Element firstname = doc.createElement(“Firstname”);
firstname.appendChild(doc.createTextNode(“mallik”));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement(“Lastname”);
lastname.appendChild(doc.createTextNode(“Gunda”));
staff.appendChild(lastname);
// salary elements
Element salary = doc.createElement(“Salary”);
salary.appendChild(doc.createTextNode(“100000”));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(“D:\\test.xml”));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println(“File saved!”);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
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();
}
}
}
Connecting SQL Server using Java/JDBC
Below program consists of steps to connect SQL server using JDBC
package com.javatutorials;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SqlServerConnection {
public static Connection connection = null;
public static Connection getDbConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager
.getConnection("jdbc:odbc:mydsn;user=sa;password=sa12$");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeConnection() {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Inner classes in Java
There are four types of classes in Java, those are loosely called as inner classes. Used correctly, inner classes are an elegant and powerful feature of the Java language.
The inner classes are
- Static member classes
- Member classes
- Local classes
- Anonymous classes.
Static member classes
A static member class is a class (or interface) defined as a static member of another class. A static method is called a class method, so, by analogy, we could call this type of inner class a “class class,” but this terminology would obviously be confusing. A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. Interfaces can be defined as static members of classes.
Member classes
A member class is also defined as a member of an enclosing class, but is not declared with the static modifier. This type of inner class is analogous to an instance method or field. An instance of a member class is always associated with an instance of the enclosing class, and the code of a member class has access to all the fields and methods (both static and non-static) of its enclosing class. There are several features of Java syntax that exist specifically to work with the enclosing instance of a member class. Interfaces can only be defined as static members of a class, not as non-static members.
Local classes:
A local class is a class defined within a block of Java code. Like a local variable, a local class is visible only within that block. Although local classes are not member classes, they are still defined within an enclosing class, so they share many of the features of member classes. Additionally, however, a local class can access any final local variables or parameters that are accessible in the scope of the block that defines the class. Interfaces cannot be defined locally.
Anonymous classes:
An anonymous class is a kind of local class that has no name; it combines the syntax for class definition with the syntax for object instantiation. While a local class definition is a Java statement, an anonymous class definition (and instantiation) is a Java expression, so it can appear as part of a larger expression, such as method invocation. Interfaces cannot be defined anonymously.
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