All posts by Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 12 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.

Java Program: How to convert Units?


In this program you will see, way to convert one length measuring unit to another unit.Generally such type of questions asked to check programming logics.

See Also : Java Program : Convert time hour minute and seconds

Example

import java.util.Scanner;

public class UnitConversionCalculator {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

	      System.out.println("Convert from:");
	      String fromUnit = in.nextLine();
	      UnitConverter from = new UnitConverter(fromUnit);

	      System.out.println("Convert to: ");
	      String toUnit = in.nextLine();
	      UnitConverter to = new UnitConverter(toUnit);

	      System.out.println("Value:");
	      double val = in.nextDouble();
	      //convert to meter
	      double meters = from.toMeters(val);
          //convert meter to required unit
	      double converted = to.fromMeters(meters);

	      System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
	}

}

That is main class for unit conversion for length measurement.

public class UnitConverter {
	static double INCHES = 39.37;
	static double FEET = 3.28;
	static double MILES = 0.00062;
	static double MILLIMETERS = 1000;
	static double CENTIMETERS = 100;
	static double METERS = 1;
	static double KILOMETERS = 0.001;

	private double meters, converted;

	String fromUnit, toUnit;

	public UnitConverter(String afromUnit) {
		fromUnit = afromUnit;
		toUnit = afromUnit;
	}

	// method to convert given value to meter
	public double toMeters(double val) {
		if (toUnit.equals("in")) {
			meters = (val / INCHES);
		} else if (toUnit.equals("ft")) {
			meters = (val / FEET);
		} else if (toUnit.equals("mi")) {
			meters = (val / MILES);
		} else if (toUnit.equals("mm")) {
			meters = (val / MILLIMETERS);
		} else if (toUnit.equals("cm")) {
			meters = (val/ CENTIMETERS);
		} else if (toUnit.equals("m")) {
			meters = (val / METERS);
		} else {
			meters = (val / KILOMETERS);
		}
		return meters;
	}

	// method to convert meter to required unit
	public double fromMeters(double meters) {
		if (fromUnit.equals("in")) {
			converted = Math.round(INCHES * 100 * meters);
		} else if (fromUnit.equals("ft")) {
			converted = Math.round(FEET * 100 * meters);
		} else if (fromUnit.equals("mi")) {
			converted = Math.round(MILES * 100 * meters);
		} else if (fromUnit.equals("mm")) {
			converted = Math.round(MILLIMETERS * 100 * meters);
		} else if (fromUnit.equals("cm")) {
			converted = Math.round(CENTIMETERS * meters);
		} else if (fromUnit.equals("m")) {
			converted = Math.round(METERS * meters);
		} else {
			converted = Math.round(KILOMETERS * meters);
		}
		return converted;
	}
}

Output


Convert from:
m
Convert to: 
cm
Value:
1
1.0 m = 100.0 cm
Advertisements

Java : How to remove duplicate elements from List?


Here you will see way to remove duplicate from ArrayList. I am using HashSet because it keeps unique values only.

See Also : Java : How to remove duplicate objects from List

Example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateElements {
	public static void main(String[] args) {
		ListstrList=new ArrayList();
		strList.add("Facing");
		strList.add("Issues");
		strList.add("On");
		strList.add("IT");
		//duplicate
		strList.add("Facing");
		strList.add("IT");

		System.out.println("==========Before Duplicate Remove :"+strList.size());
		for(String str:strList)
		System.out.println(str);

		//Convert ArrayList to HashSet
		Set set=new HashSet(strList);
		//Convert HashSet to ArrayList
		strList=new ArrayList(set);

		System.out.println("==========After Duplicate Remove :"+strList.size());
		for(String str:strList)
		System.out.println(str);
	}
}

Output


==========Before Duplicate Remove :6
Facing
Issues
On
IT
Facing
IT
==========After Duplicate Remove :4
Facing
Issues
IT
On

Eclipse : [Top 50] Keybord Shortcuts


Why eclipse shortcuts?

To make developer more productive eclipse provides keyboard shortcuts to perform faster for more common actions.

“The less you touch the mouse, the more code you can write”

Eclipse also supports most common shortcuts used with all common editors like , Ctrl+C for copy, Ctrl+S for saving, Ctrl+V for paste etc.

How to get complete list of eclipse shortcuts?

You can get complete list of eclipse shortcuts after following below steps:

  1. Open Eclipse IDE
  2. Got to help. (Screen 1)
  3. Click on “Show active key bindings” or “Key Assist” depend on IDE. (Screen 2)
  4. On eclipse bottom right corner you will see complete list of eclipse shortcuts.

or

For getting these shortcuts also have one shortcut as Ctrl + Shift + L. (Screen 2)

Screen 1

Eclipse keyboard Short Cuts -1

Screen 2

Eclipse keyboard Short cuts

From above screen you can gets list of all eclipse shortcuts but here we will focus on most common used by developers in day to day development activity.

What are most commonly used shortcuts by developers to make more productive?

Here is list of most frequently used shortcuts by developers and corresponding description.

  • Ctrl+Shift+R  : Search dialog for resources,  java files,  xml files and properties etc. based on name and matches. as in screen below.

eclipse short key cntr short R

same way you can also try others as below.

  • Ctrl+Shift+T : Search dialog for finding files from jar.
  • Ctrl+F8 : Shortcut for switching perspectives
  • Ctrl + Sift +F : for auto formatting
  • Ctrl + Shift + P : find closing braces
  • Ctrl+O : Shows quick outline for going to class method.
  • Ctrl + /  : for commenting, uncommenting lines and blocks

Shortcuts to navigation between editors

  • Ctrl+E : Search dialog to select an editor from the currently open editors
  • Alt+← :Go to previous opened editor. Cursor is placed where it was before you opened the next editor
  • Alt+→ : Similar Alt + ← but opens the next editor
  • Ctrl+Q : Go to editor and the position in this editor where the last edit was done
  • Ctrl+PageUp : Switch to previous opened editor
  • Ctrl+PageDown : Switch to next opened editor

Shortcuts to navigation between views

  • Ctrl + F7 : Shortcut for switching views. Choose the view to switch to with your mouse or cycle through the entries with repeating the keystroke
  • Shift+Alt+Q : Open menu for switch view keybindings
  • Shift+Alt+Q+P, Shift +Alt +W : Show package explorer
  • Shift+Alt+Q+C : Show console

Shortcuts to start Java programs

  • Ctrl+F11 : Run last launched
  • F11 : Run last launched in debug mode
  • Ctrl+Alt+B : Skip all breakpoints. Let’s you use debug mode for code reloading
  • Alt+Shift+X, J : Run current selected class as Java application
  • Alt+Shift+X, T : Run JUnit test
  • Alt+Shift+X, P : Run JUnit Plug-in test

Shortcuts to editing in the Java editor

  • Shift+Alt+↑ : Selects enclosing elements.,result depending on cursor position
  • Ctrl+1 : Quickfix; result depending on cursor position
  • Ctrl+Space : Content assist/ code completion
  • Ctrl+T : Show the inheritance tree of the current Java class or method.
  • Ctrl+O : Show all methods of the current class, press Ctrl + O again to show the inherited methods.
  • Ctrl+M : Maximize active editor or view
  • Ctrl+Shift+F : Format source code
  • Ctrl+I : Correct indentation, e.g., format tabs/whitespaces in code
  • Ctrl+F : Opens the find dialog
  • Shift+Enter :  Adds a link break at the end of the line
  • Ctrl+Shift+O : Organize the imports; adds missing import statements and removes unused ones
  • Alt+Shift+Z : Wrap the select block of code into a block, e.g. try/catch.
  • Ctrl + /  : for commenting, uncommenting lines and blocks
  • Ctrl + Shift + /  : for commenting, uncommenting lines with block comment
  • Selecting class and pressing F4 to see its Type hierarchy
  • Ctrl + F4 , Ctrl + w : for closing current file
  • Ctrl+Shift+W :  for closing all files.
  • Ctrl + l :  go to line
  • Select text and press Ctrl + Shift + F for formatting.
  • Ctrl + F :  for find, find/replace
  • Ctrl + D :  to delete a line
  • Ctrl + Q :  for going to last edited place

Shortcuts to cursor navigation and text selection

  • Ctrl+← or Ctrl+→ : Move one text element in the editor to the left or right
  • Ctrl+↑ or Ctrl+↓ : Scroll up / down a line in the editor
  • Ctrl+Shift+P : Go to the matching bracket
  • Shift+Cursor movement : Select text from the starting position of the cursor
  • Alt+Shift ↑ / ↓ : Select the previous / next syntactical element
  • Alt+Shift ↑ / ↓ / ← / → : Extending / reducing the selection of the previous / next syntactical element

Shortcuts to copy and move lines

  • Ctrl+Alt+↓ : Copy current line below the line in which the cursor is placed
  • Ctrl+Alt+↑ : Copy current line above the line in which the cursor is placed
  • Alt+Up : Move line one line up
  • Alt+Down : Move line one line down

Shortcuts to delete lines

  • Ctrl+D : Deletes line
  • Ctrl+Shift+DEL : Delete until end of line
  • Ctrl+DEL : Delete next element
  • Ctrl+BACKSPACE : Delete previous element

Shortcuts to create new lines

  • Shift+Enter : Adds a blank line below the current line and moves the cursor to the new line. The difference between a regular enter is that the currently line is unchanged, independently of the position of the cursor.
  • Ctrl+Shift+Enter : Same as Shift + Enter but above

Shortcuts to variable assignment

  • Ctrl+2, L : Assign statement to new local variable
  • Ctrl+2, F : Assign statement to new field

Shortcuts to coding

  • Shift+F2 : Show the Java doc for the selected type / class / method
  • Alt+Shift+N : Shortcut for the menu to create new objects
  • Alt+Shift+Z : Surround block with try and catch

Shortcuts to refactoring

  • Alt+Shift+R : Rename
  • Ctrl+2, R : Rename locally (in file), faster than Alt + Shift + R
  • Alt+Shift+T : Opens the context-sensitive refactoring menu, e.g., displays

Shortcuts must known by every developer

The following shortcuts are the absolute minimum a developer should be familiar with to work efficient in Eclipse.

  • Ctrl+S : Saves current editor
  • Ctrl+1 : Quick fix; shows potential fixes for warnings, errors or shows possible actions
  • Ctrl+Space : Content assist/ code completion
  • Ctrl+Q : Goes to the last edited position
  • Ctrl+D : Deletes current line in the editor
  • Ctrl+Shift+O : Adjusts the imports statements in the current Java source file
  • Ctrl+2, L or F : Assign statement to new local variable or field
  • Ctrl+Shift+T : Open Type Dialog
  • Ctrl+F11 : Run last launched application
  • Shift+F10 : Opens context menu. Keyboard equivalent to Mouse2
  • Ctrl+F10 : Opens view menu for current view.

If you are using some more useful Eclipse keyboard shortcuts which are not included then please post as comments, I will include them in this list. Let me know if you face any issues while using these eclipse shortcuts in any particular version of Eclipse IDE.

 

Java : java.lang.Object Class & Methods


java.lang.Object  is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class.

Methods of Object Class

Below are methods of Object Class for different purpose  as below:

  1. protected Object clone() : Creates and return copy of this object.
  2. boolean equals(Object obj) : Indicate weather other object is equal or not.
  3. protected void finalize() : To make object finalize for garbage collection.
  4. Class getClass() : Returns the runtime class of this Object.
  5. int hashCode() : Returns a hash code value of Object.
  6. void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  7. void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  8. String toString() : Returns string representation of object.
  9. void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  10. void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  11. void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

In this below examples you can see how to override and utilize these methods in different ways.

Example of clone() method

Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface. There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

Java : Shallow and Deep Object Cloning

Eample of finalize() method

Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

Java : Garbage Collection finalize() method example and uses

Example of hashCode(), equals() and toString() method

Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract

For example of toString(), hashcode() and equals() follow below link:

Java : How to remove duplicate objects from list?

Example of getClass() method

The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

import java.util.Calendar;

public class GetClassExample {

	public static void main(String[] args) {
		GetClassExample test=new GetClassExample();

		System.out.println("Class Name :"+test.getClass().getName());

		Calendar calendar=Calendar.getInstance();
		System.out.println("Calendar Class Name :"+calendar.getClass().getName());

		Integer integer=new Integer(10);
		System.out.println("Integer Class Name :"+integer.getClass().getName());

	}
}

Output


Class Name :com.Object.GetClassExample
Calendar Class Name :java.util.GregorianCalendar
Integer Class Name :java.lang.Integer

Example of wait(), notify() and notifyAll() method

Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

public class Order {
    private String msg;
    public Order(String msg){
        this.msg=msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String str) {
        this.msg=str;
    }
}

Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

public class Waiter implements Runnable{
    private Order msg;
    public Waiter(Order msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis());
            //process the order now
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

public class Notification implements Runnable {
    private Order msg;
    public Notification(Order msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg(name+" Notification work done");
                msg.notify();
                //use notify all when lots of thread are running
                // msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below test class having multiple threads of Waiter and notification to execute order.

public class WaitNotifyExample {
	public static void main(String[] args) {
		Order order= new Order("My Order");
	        Waiter waiter1 = new Waiter(order);
	        new Thread(waiter1,"waiter 1").start();

	        Waiter waiter2 = new Waiter(order);
	        new Thread(waiter2, "waiter 2").start();

	        Notification notification = new Notification(msg);
	        new Thread(notification, "notification").start();
	        System.out.println("All the threads are started");
	}
}

When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

Output


waiter 2 waiting to get notification at time:1552127934935
waiter 1 waiting to get notification at time:1552127934935
notification started
All the threads are started
waiter 2 waiter thread got notification at time:1552127935946
waiter 2 processed: notification Notification work done

or


waiter 1 waiting to get notification at time:1552127972873
All the threads are started
notification started
waiter 2 waiting to get notification at time:1552127972873
waiter 1 waiter thread got notification at time:1552127973876
waiter 1 processed: notification Notification work done

Conclusion

Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Java : How to remove duplicate objects from List


In this below example list having duplicate object of AccountTransaction which need to remove from list. Here I am using HashSet because it always keep unique records. Now question comes how to decide uniqueness of object. As you know contract between hashcode() and equals() method deciding uniqueness and equality of object.

Here used Comparable interface to sort values based on transaction date.

hashcode() and equals() contract :

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract.”

Example


import java.math.BigDecimal;
import java.util.Date;

public class AccountTransaction implements Comparable{
	private Date date;
	String transactionType;
	private String reference;
	private BigDecimal amount;

	public AccountTransaction(Date date, String transactionType, String reference, BigDecimal amount) {
		super();
		this.date = date;
		this.transactionType = transactionType;
		this.reference = reference;
		this.amount = amount;
	}
//Overriding toString() method to print object
	@Override
	public String toString() {
		return "AccountTransactions [date=" + date + ", transactionType=" + transactionType + ", reference=" + reference
				+ ", amount=" + amount + "]";
	}
//Overriding hashcode() and equals() method to check equality and uniqueness
//of objects
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((amount == null) ? 0 : amount.hashCode());
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result + ((reference == null) ? 0 : reference.hashCode());
		result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AccountTransaction other = (AccountTransaction) obj;
		if (amount == null) {
			if (other.amount != null)
				return false;
		} else if (!amount.equals(other.amount))
			return false;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (reference == null) {
			if (other.reference != null)
				return false;
		} else if (!reference.equals(other.reference))
			return false;
		if (transactionType == null) {
			if (other.transactionType != null)
				return false;
		} else if (!transactionType.equals(other.transactionType))
			return false;
		return true;
	}
	//Sort object by date
	@Override
	public int compareTo(AccountTransaction o) {

		return this.getDate().compareTo(o.getDate());
	}

	//use getter and setter of properties
}

Here is the class having sample data which is having duplicate objects in list. calling removeDuplicate() method which is converting list to hashSet() to remove duplicate and then again converting to list then sorting by date.


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateObjects {

	public static void main(String[] args) {
		List transactionList = new ArrayList();
		try {
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:50 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:48 AM"), "Account Debits", "Burger king",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:55 AM"), "Account Debits", "Papa Johns",new BigDecimal("2.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Debits", "Pizza hut",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));
			//Duplicate record
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));

		   System.out.println("Transactions before removing duplicate=============");
		   for(AccountTransaction transaction:transactionList)
		   System.out.println(transaction);
		   System.out.println("Transactions after removing duplicate=============");
		   transactionList=removeDuplicate(transactionList);
		   for(AccountTransaction transaction:transactionList)
			   System.out.println(transaction);

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

	private static List removeDuplicate(List transactionList)
	{
		//Convert List to Set
		Set transactionSet=new HashSet(transactionList);
		//Convert Set to Array List
		transactionList=new ArrayList(transactionSet);

		//Sort object by transaction date and time
		Collections.sort(transactionList);

		return transactionList;
	}

	private static Date getDate(String dateStr) throws ParseException {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm a").parse(dateStr);
	}
}

Output


Transactions before removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
Transactions after removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]

See Also:

Java : Garbage Collection finalize() method example and uses


finalize() is a Object class method that is called by Garbage Collector just before deleting/destroying the object which are eligible for garbage collection before clean-up activity.Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation.

Points to Remember:

  • finalize() is method not reserved keyword.
  • If finalize() method call manually by object instance then it will treat as normal method;
  • Once finalize() method completes immediately Garbage Collector destroy that object.
  • There is no guarantee about the time when finalize() method is called. It may be called any time after the object is not being referred anywhere (can be garbage collected).

Syntax  of finalize() method:


protected void finalize throws Throwable{}

Since Object is the super class of all the classes and finalize() is Object class method hence finalize() method is available for every java class hence Garbage Collector can call finalize method on any java object. We also override this finalize() method for code clean-up activities.

finalize() method Example

In this example first calling finalize() method manually by test object which will  behave as normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call garbage collector method. Now it’s upto JVM to call Garbage Collector or not. Usually JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

	public static void main(String[] args) {
		FinalizeMethodTest test=new FinalizeMethodTest();
		//manually calling finalize method is call like normal method
		test.finalize();

		//unreferenced object to make eligible for garbage collector
		test=null;

		//Requesting JVM to call Garbage Collector method
		System.gc();

		System.out.println("Main Method Completed !!");
	}
	@Override
	 public void finalize()
	    {
	        System.out.println("finalize method overriden");
	    }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

Exception Handling in finalize() method
If any exception happen in finalize method then if we calling finalize manually then we have to handle it otherwise program will terminate abnormally. If finalize() method call by Garbage collector and then any unchecked exception happen then JVM will take care of it and program will not terminate.

public class FinalizeMethodTest {

public static void main(String[] args) {
FinalizeMethodTest test=new FinalizeMethodTest();
//manually calling finalize method is call like normal method
try
{
test.finalize();
}
catch(Exception ex)
{
ex.printStackTrace();
}

//unreferenced object to make eligible for garbage collector
test=null;

//Requesting JVM to call Garbage Collector method
System.gc();

System.out.println("Main Method Completed !!");
}
@Override
public void finalize()
{
System.out.println("finalize method overriden");
//Exception occured here
System.out.println(10 / 0);
}<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
}

Output


finalize method overriden
java.lang.ArithmeticException: / by zero
    at classes.ObjectClass.FinalizeMethodTest.finalize(FinalizeMethodTest.java:30)
    at classes.ObjectClass.FinalizeMethodTest.main(FinalizeMethodTest.java:10)
Main Method Completed !!
finalize method overriden

In this example we have to handle exception explicitly while calling finalize() method manually while calling by Garbage Collector no exception thrown.

Conclusion

In this blog we learn about finalize() method calling manually and by Garbage Collector. Also see by example to handle exception for both cases.

Java : Shallow and Deep Object Cloning


Pr-requisite : Marker Interface in Java and Use, CloneNotSupportedException

In object oriented programming object copy or copy of object are possible many ways like copy constructor or copy of object. Here we will focus on both the ways for copy of object.

  • Shallow Copy or Shallow Cloning
  • Deep Copy or Deep Cloning

See also : Java : Shallow Cloning Vs Deep Cloning

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Copy or Shallow Cloning

Whenever we use default implementation of copy of object means it create new instance of object and copies all the fields to the object new fields and if fields are non primitive or reference type variable to copy to new fields as reference of that non-primitive fields.

clone() method by default support shallow copy of object().  for implementing clone() method you have to implement Cloneable interface which is marker interface.

Shallow copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;
	// Shallow copy by constructor because in copy taking reference of object
	public Courses(String[] courseArr) {
		super();
		this.courseArr = courseArr;
	}
	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
	String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
	Courses courses = new Courses(courseArr);
	System.out.println(courses);
	courseArr[2] = "Computer";//while changing in passed object will reflect on copy of object
	System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Computer, Hindi, English]]

Shallow copy by clone method

In this example doing  shallow copy by clone method default way by implementing Cloneable interface and overriding clone() method which will by default make copy of object but here sub object course field in Student object will take reference of copied student object. It means if make any change on course object values will reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses {
	String course1;
	String course2;
	String course3;

	public Courses(String course1, String course2, String course3) {
		this.course1 = course1;
		this.course2 = course2;
		this.course3 = course3;
	}
}

class Student implements Cloneable {
	int id;
	String name;
	Courses courses;

	public Student(int id, String name, Courses courses) {
		this.id = id;
		this.name = name;
		this.courses = courses;
	}

	// Default version of clone() method. It creates shallow copy of an object.
	// CloneNotSuportedException is checked exception always need to handle that
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

public class ShallowCopyInJava {
	public static void main(String[] args) {
		Courses science = new Courses("Physics", "Chemistry", "Math");
		Student student1 = new Student(1020, "Saurabh", science);
		Student student2 = null;

		try {
			// Creating a clone of student1 and assigning it to student2
			student2 = (Student) student1.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

		// Printing the subject3 of 'student1'
		System.out.println(student1.courses.course3); // Output : Maths

		// Changing the course3 of 'student2'
		student2.courses.course3 = "Biology";

		// This change will be reflected in original student 'student1'
		System.out.println(student1.courses.course3); // Output : Biology
	}
}

Output


Math
Biology

Note: If class is having only primitive type values or Immutable object there is no difference between Shallow and Deep Cloning of object.

Deep Copy or Deep Cloning

Whenever we need own copy not to use default implementation (shallow copy or shallow cloning) of object. Always implement according to our need and make sure all the member of  class also having deep copied of fields.

If using cloneable interface and overriding clone() method of object class make sure member objects /reference objects also having deep copy of fields.

Deep copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;

	// Deep copy object because copy actual fields value not references
	public Courses(String[] courseArr) {
		super();
		if (courseArr != null) {
			this.courseArr = new String[courseArr.length];
			for (int i = 0; i <courseArr.length; i++) {
				this.courseArr[i] = courseArr[i];
			}
		}
	}

	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
		String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
		Courses courses = new Courses(courseArr);
		System.out.println(courses);
		courseArr[2] = "Computer";// while changing in passed object will reflect on copy of object
		System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]

Deep copy by clone method
In this example doing  deep copy by clone method but handle copying each individual reference object copy separately as in Student class clone() method. It means if make any change on course object values will not reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses implements Cloneable{
String course1;
String course2;
String course3;

public Courses(String course1, String course2, String course3) {
this.course1 = course1;
this.course2 = course2;
this.course3 = course3;
}

protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

class Student implements Cloneable
{
int id;
String name;
Courses courses;

public Student(int id, String name, Courses courses)
{
this.id = id;
this.name = name;
this.courses = courses;
}

//Overriding clone() method to create a deep copy of an object.
//CloneNotSuportedException is checked exception always need to handle that

protected Object clone() throws CloneNotSupportedException
{
Student student = (Student) super.clone();
student.courses = (Courses) courses.clone();
return student;
}
}

public class DeepCopyInJava
{
public static void main(String[] args)
{
Courses science = new Courses("Physics", "Chemistry", "Math");
Student student1 = new Student(1020, "Saurabh", science);
Student student2 = null;

try
{
//Creating a clone of student1 and assigning it to student2
student2 = (Student) student1.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}

//Printing the subject3 of 'student1'
System.out.println(student1.courses.course3); //Output : Math
//Changing the subject3 of 'student2'
student2.courses.course3 = "Biology";
//This change will not be reflected in original student 'student1'
System.out.println(student1.courses.course3); //Output : Math
}
}

Output


Math
Math

Conclusion

Here you learn about Shallow and Deep copy  of object by constructor and implementing by clone() method of Cloneable Interface which is marker interface.

Java : Shallow Cloning Vs Deep Cloning


Pre-requisite : 

Below are  the list of differences between shallow cloning and deep cloning in java.

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Cloning

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object or vice versa.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.

Example: Shallow Cloning Example

Deep Cloning

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object or vice versa.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.

Example: Deep Cloning Example

Java : Immutable Class/Collection Creation


What is Mutable/Immutable Class?

A class is called as immutable class once object is created , we can not change it’s fields/objects values. If values are changeable then it’s mutable class.

Designing Rule

Classes should be immutable unless there’s a very good reason to make them mutable….
If a class cannot be made immutable, limit its mutability as much as possible.

In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.

How to make a class Immutable Class?

Below are step by step guide to make a class Immutable:

Step 1 : Don’t provide “setter” methods that modify fields or objects referred to by fields.
Step 2 : Make all fields final and private.
Step 3 : Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Step 4 : If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
Step 5 : Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

What are Benefits of Immutable Object?

  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. Immutable objects internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

How to create Immutable Lists, Sets or Maps?

In JAVA 8 added “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets and maps as immutable.  for example :

JAVA 8


Unmodifiable List
List stringList = Arrays.asList("Facing", "Issues", "On", "IT");
stringList = Collections.unmodifiableList(stringList);

Unmodifiable Set
Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT"));
stringSet = Collections.unmodifiableSet(stringSet);

Unmodifiable Map
Map<String,Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("Facing",1);
stringMap.put("Issues",2);
stringMap.put("On",3);
stringMap.put("IT",4);
stringMap = Collections.unmodifiableMap(stringMap);

JAVA 9


Unmodifiable List
List stringList = List.of("Facing", "Issues", "On", "IT");
Unmodifiable Set
Set stringSet = Set.of("Facing", "Issues", "On", "IT");

Unmodifiable Map
Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

 

Immutable Class Example


//make class final so that method not override
public final class ImmutableClass {
	final String pancardNumber;
	final String aadharNumber;
	final DOB dob;

	// Create object
	public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) {
		this.pancardNumber = pancardNumber;
		this.aadharNumber = aadharNumber;
		this.dob = dob;
	}
    //No setter method so that no fields get modifiable
	public String getPancardNumber() {
		return pancardNumber;
	}

	public String getAadharNumber() {
		return aadharNumber;
	}

	@Override
	public String toString() {
		return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob
				+ "]";
	}
}
public class  DOB {
	private int day;
	private int month;
	private int year;
	public DOB(int day, int month, int year)
	{
	this.day=day;
	this.month=month;
	this.year=year;
	}

	public int getDay() {
		return day;
	}

	public int getMonth() {
		return month;
	}

	public int getYear() {
		return year;
	}

	@Override
	public String toString() {
		return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]";
	}

}
public class ImmuTableClassTest {

	public static void main(String[] args) {
		DOB dob = new DOB(24, 04, 1992);
		ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob);
		System.out.println(immutableClass);

	}

}

Output


ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

Conclusion

In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets and maps  immutable by Java 8 and Java 9?
  • Immutable class example.

References

https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm

JDBC : Exception and Warning Handling


SQLException is Checked Exception it encounters an error when interacting with database , executing query on Databases etc. It throws instance of SQLException.

SQLException contains several kind information on a database access error or other errors which can help to determine the cause of error:

  • Description of Error : A string describing the error mesage. It can be retrieved by SQLException.getMessage().
  • SQLStateCode : These codes and their respective meanings have been standardized by ISO/ANSI and Open Group (XOPEN), although some codes have been reserved for database vendors to define for themselves. This String object consists of five alphanumeric characters. Retrieve this code by calling the method SQLException.getSQLState().
  • DatabaseMetaData: The DatabaseMetaData method getSQLStateType can be used to discover whether the driver returns the XOPEN type or the SQL:2003 type.
  • ErrorCode: This is an integer value identifying the error that caused the SQLException instance to be thrown. Its value and meaning are implementation-specific and might be the actual error code returned by the underlying data source. Retrieve the error by calling the method SQLException.getErrorCode().
  • Exception Chaining: If more than one error occurs, the exceptions are referenced through this chain. Retrieve these exceptions by calling the method SQLException.getNextException() on the exception that was thrown.
  • Cause: A SQLException instance might have a causal relationship, which consists of one or more Throwable objects that caused the SQLException instance to be thrown. To navigate this chain of causes, recursively call the method SQLException.getCause() until a null value is returned.

Constructors

  • SQLException() : Constructs a SQLException object.
  • SQLException(String reason) : Constructs a SQLException object with given reason.
  • SQLException(String reason, String SQLState) : Constructs a SQLException with given reason and SQLState.
  • SQLException(String reason, String SQLState, int vendorCode) : Constructs a SQLException with given reason ,SQLState and vendorCode.
  • SQLException(String reason, String SQLState, int vendorCode, Throwable cause) : Constructs a SQLException with given reason ,SQLState ,vendorCode and cause.
  • SQLException(String reason, Throwable cause) : Constructs a SQLException with given reason  and cause.
  • SQLException( Throwable cause) : Constructs a SQLException with given  cause.

SQLException Sub-classes

Our JDBC driver might throw a subclass of SQLException that corresponds to a common SQLState or a common error state that is not associated with a specific SQLState class value. This enables you to write more portable error-handling code. These exceptions are subclasses of one of the following classes:

  • BatchUpdateException
  • RowSetWarning
  • SerialException
  • SQLClientInfoException
  • SQLNonTransientException
  • SQLRecoverableException
  • SQLTransientException
  • SQLWarning
  • SynchFactoryException
  • SynchProviderException

SQLException Hierarchy

Lets focus on some most common happening SQLException:

BatchUpdateException

BatchUpdateException is thrown when an error occurs during a batch update operation. In addition to the information provided by SQLException, BatchUpdateException provides the update counts for all statements that were executed before the error occurred.

SQLClientInfoException

SQLClientInfoException is thrown when one or more client information properties could not be set on a Connection. In addition to the information provided by SQLException, SQLClientInfoException provides a list of client information properties that were not set.

SQLWarning

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.

Example of SQLWarning

The most common warning is a DataTruncation warning, a subclass of SQLWarning. All DataTruncation objects have a SQLState of 01004, indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.

Complete Example for Handling SQLException and Warning

In below example i have created one JDBC utilities class which will help to handle SQLException, SQLWarning chained Exception related to Connection, Statement and ResultSet etc. Here you will also see like how we can skip particular warning and exceptions.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExceptionHandeling {

public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/facingissuesonitdb","root","root");
Statement stmt = conn.createStatement();
// Print JDBC Statement Warnings
JDBCUtilities.getWarningsFromStatement(stmt);
ResultSet rs = stmt.executeQuery("select * from employee");
// Print JDBC ResultSet Warnings
JDBCUtilities.getWarningsFromResultSet(rs);

while (rs.next()) {
System.out.println("ID :"+rs.getInt(1));
System.out.println("Name :"+rs.getString(2));
System.out.println("Job :"+rs.getString(3));
System.out.println("Salary :"+rs.getDouble(4));
System.out.println("*******************************");
	}
} catch (ClassNotFoundException ex) {
  System.err.println("SQL Driver is Not Found :"+ex.getMessage());
} catch (SQLException ex) {
  JDBCUtilities.printSQLException(ex);
 }
}
}

Utilities Class to Handle JDBC Exception and Warnings

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;

public class JDBCUtilities {
// Write method so that can handle SQL exception easily
public static void printSQLException(SQLException ex) {

for (Throwable e : ex) {
  if (e instanceof SQLException) {
     if (ignoreSQLException(((SQLException) e).getSQLState()) == false) {
	e.printStackTrace(System.err);
        System.err.println("SQLState: " + ((SQLException) e).getSQLState());
	System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
	System.err.println("Message: " + e.getMessage());

	Throwable t = ex.getCause();
	while (t != null) {
	  System.out.println("Cause: " + t);
	  t = t.getCause();
					}
				}
			}
		}
	}

	// Some Exception we can ignore so that no any action required.
	public static boolean ignoreSQLException(String sqlState) {

	if (sqlState == null) {
	 System.out.println("The SQL state code is not defined!");
	 return false;
	}

	// X0Y32: Jar file already exists in schema
	if (sqlState.equalsIgnoreCase("X0Y32"))
	return true;

	// 42Y55: Table already exists in schema
	if (sqlState.equalsIgnoreCase("42Y55"))
	return true;

	return false;
	}
	//Print Batch update Exception
	public static void printBatchUpdateException(BatchUpdateException b) {

	System.err.println("----BatchUpdateException----");
	System.err.println("SQLState:  " + b.getSQLState());
	System.err.println("Message:  " + b.getMessage());
	System.err.println("Vendor:  " + b.getErrorCode());
	//BatchUpdateException contains array of update counts that is similar to execute update
	System.err.print("Update counts:  ");
	int [] updateCounts = b.getUpdateCounts();

	for (int i = 0; i < updateCounts.length; i++) {
	        System.err.print(updateCounts[i] + "   ");
	    }
	}

	// retrieve result set related warnings
	public static void getWarningsFromConnection(Connection conn) throws SQLException {
		JDBCUtilities.printWarnings(conn.getWarnings());
	}

	// retrieve result set related warnings
	public static void getWarningsFromResultSet(ResultSet rs) throws SQLException {
		JDBCUtilities.printWarnings(rs.getWarnings());
	}

	// retrieve statement related warnings
	public static void getWarningsFromStatement(Statement stmt) throws SQLException {
		JDBCUtilities.printWarnings(stmt.getWarnings());
	}

	// This method is to print any warning from JDBC statement or result set
	public static void printWarnings(SQLWarning warning) throws SQLException {

	if (warning != null) {
	System.out.println("\n---Warning---\n");

	while (warning != null) {
	System.out.println("Message: " + warning.getMessage());
	System.out.println("SQLState: " + warning.getSQLState());
	System.out.print("Vendor error code: ");
	System.out.println(warning.getErrorCode());
	System.out.println("");
	warning = warning.getNextWarning();
			}
		}

	}
}

below is one SQlException output detail for one example where String value retrive with getInt()


ID :301
Name :Tester
Job :Rajesh
java.sql.SQLException: Bad format for number 'Jain' in column 4.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
    at com.mysql.jdbc.ResultSetImpl.getDoubleInternal(ResultSetImpl.java:2549)
    at com.mysql.jdbc.ResultSetImpl.getDoubleInternal(ResultSetImpl.java:2488)
    at com.mysql.jdbc.ResultSetImpl.getDouble(ResultSetImpl.java:2449)
    at JDBCExceptionHandeling.main(JDBCExceptionHandeling.java:24)
SQLState: S1009
Error Code: 0
Message: Bad format for number 'Jain' in column 4.

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

[Solved] java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext


ClassCastException throws in code has attempted to cast an object to a subclass of which it is not an instance.

  • ClassCastException(): Constructs a ClassCastException with no detail message.
  • ClassCastException( String s): Constructs a ClassCastException with specified detail message.

Exception Stack Trace

Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
    at org.apache.logging.log4j.core.LoggerContext.getContext(LoggerContext.java:190) ~[log4j-core-2.10.0.jar:2.10.0]
    at org.apache.logging.log4j.core.config.Configurator.setLevel(Configurator.java:291) ~[log4j-core-2.10.0.jar:2.10.0]
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:149) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:144) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.SearchSlowLog.setLevel(SearchSlowLog.java:111) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.SearchSlowLog.(SearchSlowLog.java:106) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.index.IndexModule.(IndexModule.java:127) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.indices.IndicesService.createIndexService(IndicesService.java:440) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.indices.IndicesService.createIndex(IndicesService.java:413) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.metadata.MetaDataCreateIndexService$1.execute(MetaDataCreateIndexService.java:378) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:45) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.executeTasks(ClusterService.java:634) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.calculateTaskOutputs(ClusterService.java:612) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService.runTasks(ClusterService.java:571) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.ClusterService$ClusterServiceTaskBatcher.run(ClusterService.java:263) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:150) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:188) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:575) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:247) ~[elasticsearch-5.6.10.jar:5.6.10]
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:210) ~[elasticsearch-5.6.10.jar:5.6.10]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:1.8.0_151]
    at java.lang.Thread.run(Unknown Source) ~[na:1.8.0_151]

Issue

This exception “org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext” occurs because project build with maven and contains spring-boot-starter-web which imports the dependency because we can’t skip with spring-boot-starter-web and need log4j.

Solutions 1

Solution to get log4j with web project is to exclude log4j-to-slf4 from class path as given below:


    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
    </exclusion>
    </exclusions>
</dependency>

Solutions 2

If you are using simple Spring boot console based application or any Spring template and interfacing with this exception.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.0.2</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j;</artifactId>
<version>2.0.2-sources;</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl;</artifactId>
<version>2.0.2;</version>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl;</artifactId>
<version>2.0.2-sources;</version>
</dependency>

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/config/Configurator


java.lang.NoClassDefFoundError is sub class of LinkageError. This exception thrown if Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Constructor

  • NoClassDefFoundError():  Constructs a NoClassDefFoundError with no detail message.
  • NoClassDefFoundError(String s):  Constructs a NoClassDefFoundError with specific detail message.

Exception Stack Trace


Exception in thread "elasticsearch[2befByj][clusterService#updateTask][T#1]" java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/config/Configurator
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:149)
    at org.elasticsearch.common.logging.Loggers.setLevel(Loggers.java:144)
    at org.elasticsearch.index.SearchSlowLog.setLevel(SearchSlowLog.java:111)
    at org.elasticsearch.index.SearchSlowLog.(SearchSlowLog.java:106)
    at org.elasticsearch.index.IndexModule.(IndexModule.java:127)
    at org.elasticsearch.indices.IndicesService.createIndexService(IndicesService.java:440)
    at org.elasticsearch.indices.IndicesService.createIndex(IndicesService.java:413)
    at org.elasticsearch.cluster.metadata.MetaDataCreateIndexService$1.execute(MetaDataCreateIndexService.java:378)
    at org.elasticsearch.cluster.ClusterStateUpdateTask.execute(ClusterStateUpdateTask.java:45)
    at org.elasticsearch.cluster.service.ClusterService.executeTasks(ClusterService.java:634)
    at org.elasticsearch.cluster.service.ClusterService.calculateTaskOutputs(ClusterService.java:612)
    at org.elasticsearch.cluster.service.ClusterService.runTasks(ClusterService.java:571)
    at org.elasticsearch.cluster.service.ClusterService$ClusterServiceTaskBatcher.run(ClusterService.java:263)
    at org.elasticsearch.cluster.service.TaskBatcher.runIfNotProcessed(TaskBatcher.java:150)
    at org.elasticsearch.cluster.service.TaskBatcher$BatchedTask.run(TaskBatcher.java:188)
    at org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:575)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:247)
    at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:210)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.core.config.Configurator
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 21 more

Issue

Lets focus on particularly on this exception. This exception was occurred because trying to use Spring Boot with Elasticsearch framework. ElasticsearchTemaplate framework internally use log4j dependency which was not included on pom.xml

Solutions

To resolve this issue include below dependency in you pom.xml to add log4j2 jar to your application.


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
   

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] JDBC : java.sql.SQLSyntaxErrorException: Unknown database ‘database_name’


java.sql.SQLSyntaxErrorException is unchecked runtime exception which is sub class of SQLException. Herejava.sql.SQLSyntaxErrorException: Unknown database database_name”  exception occurred when connecting to database schema by JDBC. Please check below for more detail.

Sample Code

try
{
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/FacingIssuesOnITDB", "root", "facingissuesonit");
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}

Output


java.sql.SQLSyntaxErrorException: Unknown database 'facingissuesonitdb'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862)
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.fioit.examples.jdbc.connection.MyConnection.getConnectionMain(MyConnection.java:59)
at com.fioit.examples.jdbc.crud.CRUDOperation.main(CRUDOperation.java:20)

Issue

Above issue “java.sql.SQLSyntaxErrorException: Unknown database database_name” occurred because no schema exist in MySQL database with name facingissuesonitdb.

Solution

In JDBC always handle java.sql.SQLException in your connection code also because if any issue happen for java.sql.SQLSyntaxErrorException can catch by SQLException block.

More Issues Solution

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

JDBC Architecture Model


JDBC is core part of java platform and is an API specification developed by Sun Microsystems. Nearly all relational DBMSs (Database Management Systems) support SQL, and JAVA itself runs on most platforms, JDBC makes it possible to write a single database application that can run on different platforms and interact with different DBMSs.

“JDBC is similar to ODBC, but specifically designed for JAVA while ODBC is language independent.”

The JDBC driver manager is a traditional backbone of the JDBC architecture, which specifies objects for connecting Java applications to a JDBC driver. The JDBC Test Suite helps to ensure that the JDBC drivers will run the program. The JDBC-ODBC Bridge software offers JDBC access via the open database connectivity drivers.

JDBC Architecture

The JDBC architecture supports two-tier and three-tier processing models for accessing a database.

Two-tier Model (Client/Server)

A Java applet or application communicates directly to the data source. The JDBC driver enables communication between the application and the data source. When a user sends a query to the data source, the answers for those queries are sent back to the user in the form of results. The data source may be located on  single machine or  different machine on a network to which a user is connected. This is known as a client/server configuration, where the user’s machine acts as a client and the machine having the data source running acts as the server. The network connection can be intranet or Internet.
JDBC Two Tiers Architecture

 

Three-tier Model

In this model having one more layer as middle tier where the user’s commands or queries are sent to middle-tier services, from which the commands are again sent to the data source. The results are sent back to the middle tier, and from there to the user. This type of model is found very useful to makes simple to maintain access control and make updates to corporate data in database. Application deployment also becomes easy and provides performance benefits. The middle tier is usually written in C or C++.

JDBC Three Tier Architecture

References

https://docs.oracle.com/javase/tutorial/jdbc/overview/architecture.html

JAVA : Get Host Name and IP address of Machine?


Below examples is to get local machine host name and IP  address by java api’s. Here also explained about to get host name and IP address by HttpServletRequest.

Classes and Methods

  • java.net.InetAddress : class represents an Internet Protocol (IP) address.
  • java.net.InetAddress.getLocalHost() : Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
  • java.net.InetAddress.getHostAddress() : Returns the IP address string in textual presentation.
  • java.net.InetAddress.getHostName() : Gets the host name for this IP address.

Example

package com.fiot.examples.java.socket;

import java.net.InetAddress;

public class GetIPAndHostName {

public static void main(String[] args) {
try
{
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("Local IP Address:- " + inetAddress.getHostAddress());
System.out.println("Local Host Name:- " + inetAddress.getHostName());
}
catch(java.net.UnknownHostException ex)
{
ex.printStackTrace();
}
}
}

Output


Local IP Address:- 192.168.100.27
Local Host Name:- LAPTOP-FacingIssuesOnIT

Host Name from HttpServletRequest

in below example code for web application will get host name from HttpServletRequest.

public void getAppStatus(HttpServletRequest request, HttpServletResponse response) {

String hostName=request.getServerName();
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}

Summary

Here we explained about to get host name and ip address of local machine and server machine from HttpServletRequest.

More Somples

For more other JAVA/JDBC sample code follow link JAVA/JDBC Issues.

[Solved] JDBC : com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.


com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException is runtime exception thrown while connecting with database. This exception can occurred with so many reasons.

Sample Code

 try
{
Class.forName("com.mysql.jdbc.Driver");
Connection	connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "facingissuesonit");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}
 

Output Message


com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:917)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2332)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:795)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:44)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.fioit.examples.jdbc.connection.MyConnection.getConnection(MyConnection.java:21)
    at com.fioit.jdbc.examples.schemasetup.DatabaseOperationTest.main(DatabaseOperationTest.java:15)
Caused by: java.lang.NullPointerException
    at com.mysql.jdbc.ConnectionImpl.getServerCharset(ConnectionImpl.java:3005)
    at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1916)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1845)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1215)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286)
    ... 14 more

Issue

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException occurs  in above code for line DriverManager.getConnection().

Solutions

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException can occurred by many reasons for above example it was happening because of mismatch version of MYSQLServer 6.0.2 while I was using MYSQL jar for 5+ version that were  creating above exception. To solve I added below dependency on pom.xml and issue got resolved.



    mysql
    mysql-connector-java
    8.0.11

More Issues Solution

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

[Solved] JDBC: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near…


java.sql.SQLSyntaxErrorException is sub class of java.sql.SQLException which occurs in JDBC  while executing any SQL query not following syntax or any typo mistake with keywords. Here trying to drop database schema.

Constructors

  • SQLSyntaxErrorException() : Construct a SQLSyntaxErrorException Object.
  • SQLSyntaxErrorException(String reason) : Construct a SQLSyntaxErrorException Object with a given reason.
  • SQLSyntaxErrorException(String reason, String SQLState) : Construct a SQLSyntaxErrorException Object.,  with a given reason and SQLState.
  • SQLSyntaxErrorException(String reason, String SQLState, int vendorCode) : Construct a SQLSyntaxErrorException Object.with a given reason, SQLState and vendorCode.
  • SQLSyntaxErrorException(String reason, String SQLState, int vendorCode, Throwable cause) : Construct a SQLSyntaxErrorException Object .with a given reason, SQLState  vendorCode and cause..
  • SQLSyntaxErrorException(String reason, String SQLState, ,Throwable cause) : Construct a SQLSyntaxErrorException Object .with a given reason, SQLState and cause..
  • SQLSyntaxErrorException(tring reason, Throwable cause) : Construct a SQLSyntaxErrorException Object with reason and cause.
  • SQLSyntaxErrorException( Throwable cause) : Construct a SQLSyntaxErrorException Object with cause.

 

Sample Code

 try
{
Class.forName("com.mysql.jdbc.Driver");
Connection	connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "facingissuesonit");
Statement smt = conn.createStatement();
System.out.println("Drop Database ....");
smt.executeUpdate("drop database ifexist FacingIssuesOnITDB");
System.out.println("Database drop successfully ....");
		}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}
<span style="display:inline !important;float:none;background-color:transparent;color:#3d596d;cursor:text;font-family:'Noto Serif', Georgia, 'Times New Roman', Times, serif;font-size:16px;font-style:normal;font-variant:normal;font-weight:400;letter-spacing:normal;line-height:19.2px;orphans:2;text-align:left;text-decoration:none;text-indent:0;text-transform:none;white-space:normal;word-spacing:0;">catch (SQLSyntaxErrorException ex) { ex.printStackTrace(); } </span>

 

Output Message


java.sql.SQLException: Can't drop database 'facingissuesonitdb'; database doesn't exist
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:127)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1393)
    at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2353)
    at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1303)
    at com.fioit.jdbc.examples.schemasetup.DatabaseOperationTest.dropDatabase(DatabaseOperationTest.java:59)
    at com.fioit.jdbc.examples.schemasetup.DatabaseOperationTest.main(DatabaseOperationTest.java:19)

Issue

java.sql.SQLSyntaxErrorException occurs in JDBC SQL query because of typo mistake there should space between two words ifexist that what throwing this exception. 

Solutions

Use correct query as below for dropping database.

for Example

Drop Database:

drop database if exists FacingIssuesOnITDB

Issues Solution

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

[Solved] JDBC: java.sql.SQLException: Can’t drop database ‘database_name’; database doesn’t exist


java.sql.SQLException occurs in JDBC APIs failure while executing any query. Here trying to drop database schema. which is not exist that’s why server is throwing below exception as output.

Sample Code

 try
{
Class.forName("com.mysql.jdbc.Driver");
Connection	connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "facingissuesonit");
Statement smt = conn.createStatement();
System.out.println("Drop Database ....");
smt.executeUpdate("drop database FacingIssuesOnITDB"<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>);
System.out.println("Database drop successfully ....");
		}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}

 

Output Message


java.sql.SQLException: Can't drop database 'facingissuesonitdb'; database doesn't exist
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:127)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1393)
    at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2353)
    at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1303)
    at com.fioit.jdbc.examples.schemasetup.DatabaseOperationTest.dropDatabase(DatabaseOperationTest.java:59)
    at com.fioit.jdbc.examples.schemasetup.DatabaseOperationTest.main(DatabaseOperationTest.java:19)

Issue

java.sql.SQLException occurs in JDBC APIs failure while executing any query. Here trying to drop database schema. which is not exist that’s why server is throwing below exception as output.

Solutions

Instead of directly running drop sql quey .first check for existence of database/table then execute sql query.

for Example

Drop Database:

drop database if exists FacingIssuesOnITDB

Drop Table:

drop table if exists Students

Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.

[Solved] java.util.UnknownFormatConversionException: Conversion = ‘y’


java.util.UnknownFormatConversionException  is unchecked runtime exception which is sub class of java.util.IllegalFormatException. This exception occurs while using unknown parameter values while formatting data.

Constructors

  • UnknownFormatConversionException(String message) : Constructs a instance of this class with unknown conversion  message.

Sample Code

here in below example for extract values of date, day, month, year, hour and minute values from LocalDateTime and printing in particular format bySystem.out.printf()

System.out.println("*********Get Date and Time Values***************");
LocalDateTime dateTimePoint=LocalDateTime.now();
LocalDate datePoint = dateTimePoint.toLocalDate();
Month month = dateTimePoint.getMonth();
int day = dateTimePoint.getDayOfMonth();
int year = dateTimePoint.getYear();
int hour = dateTimePoint.getHour();
int minute = dateTimePoint.getMinute();
int second = dateTimePoint.getSecond();
System.out.println("Local Date :" + datePoint);
System.out.printf("Local Date time Format : %d/%d/%d %d:%d:%y", day, month.getValue(), year, hour, minute,second);

Output Message


Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'y'
    at java.util.Formatter$FormatSpecifier.conversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.(Unknown Source)
    at java.util.Formatter.parse(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)

Issue

Here throw UnknowFormatConversionException for parameter value as y for printing values of second. it is because of just typing mistake. But in below solution mentioned on what cases it can occurd and how to resolve it.

Solutions

To solve this issue replace System.out.printf value y as d because for representing numeric value param value is d.

Follow below links to know about supported conversion format and parameters

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

More Issues Solution

For more other JAVA/JDBC issues solution follow link JAVA/JDBC Issues.