Posts

Showing posts from November, 2013

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...

Why java uses both compiler and interpreter?

The JVM runtime executes bytecode by interpreting it or using a just-in-time compiler (JIT). The Java compiler translates Java source code into a platform independent language called Java bytecode. Although bytecode is similar to machine language, but it is not the machine language of any actual computer. A Java interpreter or a just-in-time compiler (JIT) is used to run the compiled Java bytecode . Each platform needs its own Java bytecode interpreter, but all these interpreters interpret the same bytecode . JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed.

Multiple Inheritance In Java?

Most of the Java lover say that Java does not support multiple inheritance but this is not hundred percent correct. We will try to understand inheritance in java in detail with all possibilities. “ A relationship among classes where one class share the structure and/or behaviour of one of more classes. This mechanism is known as the name of inheritance. ” Type of inheritance                                        purpose 1.       Implementation inheritance           Code Reusability and Runtime Polymorphism 2.       Interface inheritance                      Runtime Polymorphism Syntax: implementation inheritance Class ClassName extends SuperClassName{ //additional methods of class }

What is JSF with Simple Example JSF

JSF is a specification given by Java Community Process (JCP).  JSF web application is based on the MVC design pattern. In addition it provides richer GUI based MVC environment than other web application frameworks. User events, like changed value in a text field or a clicked button, are main tasks to handle in GUI application. However, previously made web application only recognize the HTTP request. For a Web application to recognize these events, it has to process all request parameter. For example, if a user enters a text field in a standard desktop user interface, the client application is able to display a message as if the entered data is invalid to the user directly. A web application does not have this opportunity because the first HTTP request-response cycle is completed. It needs to redisplay the page and input fields including the previously entered data and an additional error message. JSF User interface components remember their value, which are called statefulness...

HOW TO ACCESS SESSION IN STRUTS 2 WITH EXAMPLE

Some of my friends are confused, how to deal with session in struts2, because struts 2 is Servlet API independent. We will try to understand all possible way to deal with session. You can obtain the session attributes by asking the ActionContext or implementing SessionAware. Implementing SessionAware is preferred. Using ActionContext: getContext()  static method of ActionContext return instance of ActionContext, on which getSession() method  is called which return Map of HttpSession value. Map attmap = ActionContext.getContext().getSession(); Now get(), put() and remove() method of Map is used for getting, putting and removing attribute in session scope.

Association, Aggregation, and Composition with example

Most confusing topics of java are association, aggregation, and composition. In this post, we will try to understand three important concepts: association, aggregation, and composition. The association relationship is a way of that a class holds a reference to another class. The relationship can be bi-directional with each class holding a reference to the other, but they have their own object life time. In this relationship no one is owner. They can exist without each other. Aggregation is a special type of association. The aggregate class contains a reference to another class and is owner of this relationship. It is whole-part relationship. Each class referenced is considered to be part-of the aggregate (whole) class. The referenced class objects can not belong to any other object. What do mean ownership? If a class X contain reference of class Y and again class Y contain reference of class X then no clear ownership can be determined and the relationship is simply associ...

LookupDispatchAction

LookupDispatchAction extends the functionality of DispatchAction class that support internationalization. LookupDispatchAction uses the value of the request parameter to reverse-map to a property in the Struts resource bundle file. ApplicationResources.properties. That is, the value of the request parameter is compared against the values of properties in the resource bundle until a match is found. The key for the matching property is then used as a key to another map that maps to a method in  your LookupDispatchAction subclass that will be executed. To use LookupDispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests. The subclass must also include a getKeyMethodMap( ) method that maps methods in the class to keys in the Struts resource bundle file.

DispatchAction class

The DispatchAction class provides a mechanism for modularizing a set of related functions into a single action, and thus eliminates the need to create separate, independent actions for each function. For example, consider a set of related functions for adding a user, updating a user, and removing a user. Instead of creating an AddUserAction class, an UpdateUserAction class, and a RemoveUserAction class, by extending DispatchAction, you can create one UserAction class that has three methods: add( ), update( ), and remove( ). At run time, DispatchAction manages routing requests to the appropriate method in its subclass. DispatchAction determines which method to call based on the value of a request parameter that is passed to it from the incoming request. To use DispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests. Additionally, you have to set up for the action an action mapping that specifies the name of a request pa...

hyperlinks in a struts 1

Global Forward: <html:link> tag is used to simulate hyperlinks in a struts application that is from hyperlinks request is send to the controller, Controller decide next view. In jsp page:- <html:link forward=”reg”> In Mapping:- <global-forwards> <forward name=”reg” path=”/reg.jsp”> </global-forwards>

DynaActionForm:

It is predefined form bean class that is use when no validation to be performs on the request data. Instead of creating a new ActionForm subclass and new get/set methods for each of your bean’s properties, you can list its properties, type, and defaults in the struts configuration file. <form-beans>     <form-bean name="DForm" type="org.apache.struts.action.DynaActionForm">         <form-property name="name" type="java.lang.String" initial="Naveen"></form-property>     </form-bean>     </form-beans>

Validator Framework

Validator framework is an optional sub framework of struts that provides predefines validation logic for common validation problem. Validation logic is provided in the form of static methods called validation rules. When validator framework is used for form data validation your ActionForm must be extends ValidatorForm class. Framework has following components: 1.     Set of rules defined in a xml file known as validator-rules.xml 2.     An xml file named validation.xml used by the application developer to apply validation rules on a form. Validator-rules.xml <form-validation>     <global>         <validator name="required"                    classname="org.apache.struts.validator.FieldChecks"               ...

Tiles

An optional framework of a struts used on composite view design pattern that facilitated faster development of views. Normally in a web application a view consist of different sub-views which are arrange according to a predefine structure that is common for all views. Usually structure is defined with the help of frameset, html table and style sheet. Tiles frame work provides a mechanism to change the structured of all views without individually applying changes to them. <titles:insert> tag is used to define place holder tiles. myLayout.jsp <table width="100%"  height="553">                        <tr bgcolor="#CC9999"><td height="60" colspan="2"><titles:insert attribute="header"/></td>             </tr>         ...

Log4j

Log4j , a popular logging package for java. The package is distributed under the Apache Software License, a fully-fledge open source license. Drawbacks           :               slow down an application, If two verbose. Advantage           :                It provides the precise context about a run of the application. One inserted into code, the generation of logging output requires no human intervention (involvement). Log output can be saved in persistent medium to be studied at a later time. Now it was important component of the development cycle. It has three main components: Logger Appender Layout These three type of component work together to enable developers to log message according to message type and level and to control at runtime how thes...