Posts

Singleton design pattern

S ingleton pattern is a design solution where an application wants to have one and only one instance of any class.It saves memory because object is not created with each request. Only single instance is reused again and again. But how to make any class singleton is not so easy task, because there are several way in which singleton can break. Steps: 1.       Make constructor private, so not directly instantiated class 2.       Make a static method which produce existing instance if one available else new 3.       Override clone() method. One cannot create a cloned object which also violates singleton pattern. 4.       If Singleton is class is serializable then once it serialized again deserialized it, but it will not return singleton object.

Difference between Java 8 interface and Java 7 interface

Before Java 8, interface having only abstract methods that means method without body (implementation). But Java 8 interface can contain abstract method as well as default implemented method and interface level method (static method). That means now in Java 8 interface can contain three types of methods.

A new date and time API has been designed for Java SE 8.

There are several problems with existing Date and Time API some of them are- 1. The existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe 2. Poor API design. E.g. years in java.util.Date start at 1900, months start at 1, and days start at 0.

Simple Chat Application Using Applet

Image
1. Client.java package chatterapi; /*   @navindra k. jha   */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class Client extends Applet implements ActionListener, Runnable {         Image Icon = Toolkit.getDefaultToolkit().getImage("D:/Example/emperian/jsf/ChatterAPI/src/chatterapi/hi.gif") ;

Hit Counter for a Web site, time of hitting and no. of current users

Many times you would be interested in knowing total number of hits of your site, time of hitting, and number of users currently using your site. This post is about creating a hit counter that counts number of site visit. There are various ways for creating hit counter in servlet but here we have implemented hit counter using ServletContextListener.   ServletContextListener is a listener interface that gets notified when the context is initialized and destroyed . index.html <body>         <form name="loginForm" method="get" action="LoginServlet">             Username<input type="text" name="txtname" size="20"><br>             Password<input type="password" name="txtpass" size="20"><br>              <input type="submit" value=...

How to export data from database to excel sheet

It is very simple to import data from database to Excel, follow below steps I have “student” table in “stu” database and book1.xlsx excel file in x drive. Student table has three field name, roll, and marks Before importing data you must have an Excel file in which data is imported and specify field name in cell like NAME, ROLL, and MARKS in different cells. NAME ROLL MARKS I am using MySql database.

Abstraction and Encapsulation

In an object-oriented programming language   Encapsulation and Abstraction are very confusing words, everyone feels confused to understand. Here I give in my own style of explanation. Abstraction:   The essential characteristics of an entity that distinguishes it from all other kinds of entities. In other word, “Only the characteristics of the system that are essential to the problem being studied are modelled; minor or irrelevant details are ignored.”   It defines a boundary relative to the perspective of the viewer. It allows us to manage complexity by concentrating on the essential characteristics of an entity.

ARE YOU KNOW ANSWER OF THIS QUESTION?

1. How to get last inserted id in hibernate? 2. How to insert date in database? 3. You can override static method in java? 4. Which one is better struts2 or spring? 5. How many ways to create object in java? 6. Why java use both compiler and interpreter? 7. Why and where uses throw keyword? 8. When stack over follow error is occurred? 9. Difference between heap and stack memory, why not everything store in heap? 10. Difference between abstract factory and factory design pattern? ANSWER:

DatabaseMetaData

The simple meaning of metadata is data about data. There are two metadata available in the JDBC API - ResultSetMetaData and DatabaseMetaData. This interface provides method to find out information about the database product being used, Driver Information, Operation Supported by Database, Details of Table, Procedures, Sequence etc. getMetaData() method of Connection interface is used to obtained the reference of database metadata object. Commonly used methods:

ResultSetMetaData

The simple meaning of metadata is data about data. There are two metadata available in the JDBC API - ResultSetMetaData and DatabaseMetaData . This interface provide method to find out information such as number of columns return in the result set , name and types of column their source table etc. getMetaData() method of ResultSet Interface is used to obtained the reference of ResultSetMetaData. public   ResultSetMetaData getMetaData();

Reflection API

Reflection API provide the facility find out the details of a class at execution time as well as facility to load a class, to create an instance of a class to invoke a constructor or method on a class object to get and set value of a field etc. java.lang.reflect package provide classes of reflection API. Commonly use class of Reflection API Method: A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). Field: A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field. Constructor: Constructor provides information about and access to, a single constructor for a class.

Scanner Class and Static Import with Example

java.util.Scanner class provides convenient methods to read data in the form of primitive type as well as string from the keyboard. A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. Constructor: public Scanner(InputStream) Methods:

What is Applet with Simple Example ?

An Applet is a java program that is transmitted over the network from server to the client and execute within browser of client. Applets are used to provide interactivity in web application. It is a managed object. Managed object is an object that is created and managed by a run time environment.   Lifecycle methods are used to manage the lifecycle of a managed object. Applets are managed object because their objects are created and managed by the Browser or another Java applet viewing program, such as the Applet Viewer. Lifecycle Methods of Applet :

Command Line Arguments in NetBeans IDE

Image
Problem of a student: I need to pass the command line arguments to my java program,   I'm using netbeans IDE, anyone please let me know how to pass comand line arguments to our program(to main method) in netbeans.   Solution: We will create a new Java Application project and will add some code to the Main method which will print the provided command line arguments on the console. Steps:

What is J2ME with simple example ?

The Java 2 Micro Edition (J2ME): J2ME is a Java platform that is designed for small devices. It contains specially designed, lightweight virtual machines; a bare minimum of core-class libraries; and lightweight substitutes for standard Java libraries. J2ME is the ideal mobile client platform for wireless PDAs and enhanced mobile phones. J2ME is divided into configurations , profiles , and optional APIs, which provide specific information about APIs and different families of devices.   A configuration is designed for a specific kind of device based on memory constraints and processor power. It specifies a Java Virtual Machine (JVM) that can be easily ported to devices supporting the configuration. It also specifies some subset of the Java 2 Platform, Standard Edition (J2SE) APIs that will be used on the platform, as well as additional APIs that may be necessary. Profiles are more specific than configurations. A profile is based on a configuration and adds APIs for user inte...

Can we override static method in Java ?

In sort,  Static method belongs to the class, rather than to an object of the class. As you know overriding a method means redefining behaviour of an object, but static method show the behaviour of a class as whole and it is referred by class name. So it does not redefine the behaviour of an object. In details, Static method should be invoked with the class name, without the need for creating an instance of the class, as below ClassName.methodName(if args) You can also refer to static methods with an object reference, as bellow instanceName.methodName(if args) A subclass inherits all the members including static member (fields, methods, and nested classes) from its superclass.

How to define custom Exception ?

To define custom exception crate a sub class of exception and either override toString() method or provide default as well as augmented constructor. Argumented constructor must receive message as String. public class MyException extends Exception{     String msg="Exception";     public MyException() {         super();     }     public MyException(String msg){         super(msg);     } //or     @Override     public String toString(){         return msg;     } }

Magic of Finally block

‘finally’ keyword is use to define a block of statement that is to be executed when an exception occurs or non. Magic  of finally block public class Main {     public static int divide(int x, int y) throws Exception{         boolean flag=false;         try{             if(y==0)                 throw new ArithmeticException("divide by zero");             int c = x / y;             return c;         }catch(Exception e){             System.out.println("Excetion is rethrowing..");             flag=true;             throw(e);         }finally{             if(flag==true){...

Reasons to use throw keyword

1. To customize the message display in case of an exception. Public Exception (); Public Exception (String msg); 2. To throw user defined exception throw new MyException(“ Emp is empty”); 3. To re-throw caught exception throw (e); Example of 1: customizing message public class Main {     public static void main(String[] args) {         try {             Scanner s=new Scanner(System.in);             System.out.println("Enter two no.");             int a = s.nextInt();             int b = s.nextInt();             if(b==0)                 throw new ArithmeticException("divide by zero");             int c = a / b;             System.out.pr...

Checked and Unchecked Exceptions

Except for RuntimeException, Error, and their subclasses, all exceptions are called checked exceptions. The compiler ensures that if a method can throw a checked exception, directly or indirectly, then the method must explicitly deal with it. The method must either catch the exception and take the appropriate action, or pass the exception on to its caller. Exceptions defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions, meaning that a method is not obliged to deal with these kinds of exceptions. They are either irrecoverable (exemplified by the Error class) and the program should not attempt to deal with them, or they are programming errors (examplified by the RuntimeException class) and should be dealt with as such and not as exceptions. Any method that can cause a checked exception to be thrown, either directly by using the throw statement or indirectly by invoking other methods that can throw such an exception, must deal with the e...