Saturday, 22 October 2016

Program to determine Odd or Even Number without using Arithmetic Operators in Java

Checking a number is Odd or Even is very simple. To determine the number is odd or even, one can use of modulus or division operator.

But what if, we have condition to check the number is odd or even without using Arithmetic operators? 

It is very simple to check whether the number is odd or even, if we have knowledge of Bitwise operators.Using Bitwise And (&) Operator we can achieve the requirement easily.

Our logic of using Bitwise And (&) to find Odd or Even is , if "Number & 1 == 0" then the Number is Even else Odd.

Lets us see the program -

package com.mylogicalindian.oddeven;

public class OddOrEven {

public static void checkOddOrEven(int number){

if((number & 1) == 0){
System.out.println(number+" is Even");
}else{
System.out.println(number+" is Odd");
}

}

public static void main(String args[]){

checkOddOrEven(34);
checkOddOrEven(75);

}
}

Output -

34 is Even

75 is Odd

Friday, 21 October 2016

How to find list of all Class Names from inside .jar file?

Today we will see how to get list of all Class names from inside of .jar file. With the help of JarEntry and JarInputStream utility all classes inside jar can be extracted.

Let us see the example -

package com.mylogicalindian.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class JarClasses {

private static JarInputStream inputStream;

public static Map<String, Object> getListOfClasses(String fileName) throws FileNotFoundException, IOException{

Map<String, Object> map = new HashMap<String, Object>();
List<String> list = new ArrayList<String>();

inputStream = new JarInputStream(new FileInputStream(fileName));

JarEntry jarEntry;

while(true){

jarEntry = inputStream.getNextJarEntry();

if(jarEntry == null){
break;
}

if(jarEntry.getName().endsWith(".class")){

String className = jarEntry.getName().replaceAll("/", "\\.");
String myclass = className.substring(0, className.lastIndexOf("."));
list.add(myclass);

}

map.put("Jar File Name", fileName);
map.put("Classes", list);

}

return map;

}

public static void main(String args[]) throws FileNotFoundException, IOException{

String fileName = "C:/lib/ojdbc14.jar";
Map<String, Object> map = getListOfClasses(fileName);
System.out.println("Jar Name : " + map.get("Jar File Name"));
System.out.println("Classes : " + map.get("Classes").toString());
  System.out.println("No. of Classes present in "+map.get("Jar File Name")+" is "+((List)map.get("Classes")).size());

}

}

Output -

Jar Name : C:/lib/ojdbc14.jar
Classes : [oracle.net.TNSAddress.Address, oracle.net.TNSAddress.AddressList, oracle.net.TNSAddress.Description, oracle.net.TNSAddress.DescriptionList, oracle.net.TNSAddress.SOException, 
....
....
....
oracle.jdbc.OraclePreparedStatement, oracle.jdbc.OracleParameterMetaData, oracle.jdbc.OracleDatabaseMetaData, oracle.jdbc.OracleCallableStatement, oracle.jdbc.OracleTypes, oracle.jdbc.Const, oracle.jdbc.StructMetaData, oracle.jdbc.OracleDriver, oracle.jpub.runtime.MutableArray, oracle.jpub.runtime.Util, oracle.jpub.runtime.MutableStruct]
No. of Classes present in C:/lib/ojdbc14.jar is 623

Program to add two numbers without using Arithmetic Operators in Java

Addition of two numbers is very simple but if we have to add two numbers without using Arithmetic operators, then it might be problem for us. But luckily its very simple. For adding two numbers we can use Bitwise Operators instead of Arithmetic Operators.

Here we have implemented Addition of two numbers using Recursion as well as Non-recursion. 

Let us see the program -

package com.anjan.test;

public class Addition {
//Non-recursive implementation of Addition
public int addNonRecur(int a, int b){
while(b !=0){
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
//Recursive implementation of Addition
public int addRecur(int a, int b){
if(b == 0){
return a;
}else{
return addRecur(a ^ b, (a & b) << 1);
}
}
public static void main(String args[]){
Addition a = new Addition();
System.out.println(a.addNonRecur(2, 4));
System.out.println(a.addRecur(6, 4));
}

}


Output -


6
10

Thursday, 20 October 2016

How to access Private Methods and Fields from other class in Java?

Despite the common belief it is actually possible to access Private methods and fields from other class. This can be achieved using Java Reflection. It is not even that difficult but this only works as a Standalone Java applications.

Using Java Reflection one can examine or modify the run time behavior of a class at run time. The java.lang and java.lang.reflect provides classes for Java Reflection.

Now we'll see how to access Private Methods and Fields from other class. By the help of java.lang.Class class and java.lang.reflect.Method class we can call the private methods from any other class. Similarly by using  java.lang.reflect.Field class we can accessing Private Fields from any other class.

To access private methods, following methods are required -

1. getDeclaredMethod() method of Class class
2. setAccessible() and invoke() methods of Method class

And to access private fields, following methods are required -

1. getDeclaredField() method of Class class
2. get() method of Field class

Let us see and example -

package com.anjan.privat;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class MyPrivateClass{
private int value = 10;
private void printPrivate(){
System.out.println("Private Method");
}
private void multiply(int a, int b){
System.out.println("Product of "+a+" and "+b+" is "+a*b);
}
}

public class PrivateMethodDemo {
public static void main(String args[])throws Exception{
Class cl = Class.forName("com.anjan.privat.MyPrivateClass");
Object obj = cl.newInstance();
//Accessing Private Method without parameter
Method method = cl.getDeclaredMethod("printPrivate", null);
method.setAccessible(true);
method.invoke(obj, null);
//Accessing Private Method with parameter
method = cl.getDeclaredMethod("multiply", new Class[]{int.class, int.class});
method.setAccessible(true);
method.invoke(obj, 3, 4);
//Accessing Private Field
Field field = cl.getDeclaredField("value");
field.setAccessible(true);
System.out.println("Value of private field : "+field.get(obj));
}



Output -

Private Method
Product of 3 and 4 is 12
Value of private field : 10


Similarly we can access Private Classes and Private Constructors as well in Java using Java Reflection.

Monday, 10 October 2016

How to work with DatePicker in HTML5 and JSP?

Today we'll look how to work with Datepicker in HTML5 and display the date in different formats in JSP. 

Let us look into one simple example. For this we need one HTML5 web page with one form containing Date picker and one JSP page to parse and format the date.

Now we'll create our HTML page 

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Date Picker Demo</title>
</head>
<body>
<form action="result.jsp" method="post">
Select Date : <input type="date" name="myDate"><br/>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

After creating our HTML page, we'll create our JSP page to get the request from HTML page and process the request.

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result</title>
</head>
<body>
<%

String myDate = request.getParameter("myDate");

out.print("Date without formatting (yyyy-MM-dd): "+myDate);

%>
<br/>
<%

java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date dt = df.parse(myDate);

out.println("Parsing String into Date (yyyy-MM-dd) : "+dt);

%>
<br/>
<%

java.text.DateFormat dateFmt1 = new java.text.SimpleDateFormat("MM-dd-yyyy");
String date1 = dateFmt1.format(dt);

out.println("Formatting Date into String (MM-dd-yyyy) : "+date1);

%>
<br/>
<%

java.text.DateFormat dateFmt2 = new java.text.SimpleDateFormat("dd/MM/yyyy");
String date2 = dateFmt2.format(dt);

out.println("Formatting Date into String (dd/MM/yyyy) : "+date2);

%>
<br/>
<%

java.text.DateFormat dateFmt3 = new java.text.SimpleDateFormat("dd-MM-yyyy");
String date3 = dateFmt3.format(dt);

out.println("Formatting Date into String (dd-MM-yyyy) : "+date3);

%>
<br/>
<%

java.text.DateFormat dateFmt4 = new java.text.SimpleDateFormat("dd-MMM-yyyy");
String date4 = dateFmt4.format(dt);

out.println("Formatting Date into String (dd-MMM-yyyy) : "+date4);
%>
</body>

</html>


Now let us look into the output -

Output -

Date without formatting (yyyy-MM-dd): 2016-10-12
Parsing String into Date (yyyy-MM-dd) : Wed Oct 12 00:00:00 IST 2016
Formatting Date into String (MM-dd-yyyy) : 10-12-2016
Formatting Date into String (dd/MM/yyyy) : 12/10/2016
Formatting Date into String (dd-MM-yyyy) : 12-10-2016
Formatting Date into String (dd-MMM-yyyy) : 12-Oct-2016


In the above example, first we get the value of myDate parameter and store into one String myDate. To display the selected date first we parsed the String into Date dt using parse() method and change the Date dt into different formats using format() method.


Sunday, 9 October 2016

What is Lambda Expressions in Java?

In Java, we face issue with anonymous class is that if the implementation of our anonymous class is very simple, such as an interface that contain only one method then the syntax of anonymous class may seem unwieldy and unclear.

Prior to the introduction of Lambda Expressions in Java, we use anonymous class to implement the interface. But from Java 8, we have Lambda Expressions to resolve the issue.

Lambda Expressions provides flexibility to implement the interface directly without using anonymous class. The only condition is that the interface should contain only one method.

Let us look into one simple example -

interface LambdaOperation {

public int lambdaOpMethod(int a, int b);
}

public class LambdaExpDemo {

private static void operation(int a, int b, LambdaOperation lambdaOperation){
System.out.println(lambdaOperation.lambdaOpMethod(a, b));
}

public static void main(String args[]){

//Before Java 8, implementing interface without Lambda Expression
LambdaOperation operationWithoutLambdaExp = new LambdaOperation() {

@Override
public int lambdaOpMethod(int a, int b) {
return a+b;
}
};

operation(2, 3, operationWithoutLambdaExp);

//From Java 8, implementing interface with Lambda Expression
LambdaOperation operationLambdaExp = (int a, int b) -> a + b;

operation(2, 3, operationLambdaExp);

}
}

Output -

5
5


Lambda Parameters -

Since Java Lambda expressions are effectively just methods, lambda expressions can take parameters just like methods. These parameters have to match the parameters of the method on the single method interface.

There are minimum of two conditions -

1. The number of the parameters in the lambda expression and method must match.
2. If we have specified any parameter type in the lambda expression, then these type must match too.

For the above interface LambdaOperation, we can write any of the below lines to instantiate -

LambdaOperation operationLambdaExp = (a, b) -> a + b;

or 


LambdaOperation operationLambdaExp = (a, b) -> (a + b);


Now as the above interface have one method with two parameters. There might be possibility that we can have methods with no parameters or the method is not returning any value.

Lets us look for the above conditions -

1. If we have No or Zero Parameters in the method, then the Lambda Expression will be -

LambdaString lambdaString = () -> System.out.println("Lambda Expression for Zero Parameter");

2. If the method have One Parameter, then the Lambda Expression will be -

LambdaString lambdaString = (a) -> System.out.println("Lambda Expression with One Parameter : "+a);

or 

LambdaString lambdaString = a -> System.out.println("Lambda Expression with One Parameter : "+a);

or

LambdaString lambdaString = (int a) -> System.out.println("Lambda Expression with One Parameter : "+a);

3. If the method have Multiple Parameters, then the lambda Expression will be -

LambdaOperation operationLambdaExp = (int a, int b) -> a + b;

or

LambdaOperation operationLambdaExp = (a, b) -> a + b;

or

//Lambda Function Body
//returning value from Lambda Expression
LambdaOperation operationLambdaExp = (int a, int b) -> { return (a + b)};

or

//Lambda Function Body
//returning value from Lambda Expression
LambdaOperation operationLambdaExp = (ab) -> { return (b)};

Thursday, 6 October 2016

How to get address of an Object in Java?

Today we will look how to get address of an Object in Java. Generally if we have any object and we print the object, it will print the address of that Object.

But in case of String, if we create String object, and print the object it prints the value of String object instead of printing the address.

Therefore to get the address of any object we'll write one generic method which will return the address of the object.

To get the address of an Object we will use identityHashCode() method of System Class.

Here is the code snippet of the method -

public static String getObject(Object obj){
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj));
}

Now we have getObject() method which returns Address of an Object in java. 

Lets test the method -

public class FindObject {

public static String getObject(Object obj){
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj));
 }
public static void main(String args[]){
FindObject fO = new FindObject();

  System.out.println("Address without calling getObject method : "+fO);

  System.out.println("Address calling getObject method : "+getObject(fO));

  String str = new String("India");
  
  System.out.println("String str : "+str);

  System.out.println("Address of String str : "+getObject(str));
}
}

Output -

Address without calling getObject method : com.anjan.time.FindObject@15db9742
Address calling getObject method : com.anjan.time.FindObject@15db9742
String str : India
Address of String str : java.lang.String@6d06d69c

How to pass Parameters in Custom tags in JSP?

In the previous blog post, we have learnt how to create custom tags in JSP. Today we'll look into passing parameters in custom tags in JSP.

Lets take an example for passing parameters in Custom tags in JSP. Suppose we want to find the cube of a given number using custom tags. So we will create custom tag like below -

<mytag:cube num="8" />

For passing parameter in Custom tag, we will follow the same steps which we followed for creating custom tags.

First of all we'll create Tag Handler Class -

Cube.java

package com.anjan;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class Cube extends TagSupport{

private int num = 0;

public void setNum(int num){
this.num = num;
}

public int getNum(){
return this.num;
}

public int doStartTag() throws JspException {  
JspWriter out=pageContext.getOut();  
   try{  
       out.print(num*num*num);  
   }catch(Exception e){e.printStackTrace();}  
     
   return EVAL_PAGE
}    

}

We'll now create TLD File where we'll specify our tag name, tag handler class and tag attribute.

customDemo.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://tomcat.apache.org/example-taglib</uri>  

<tag>
<name>cube</name>
<tag-class>com.anjan.Cube</tag-class>

<attribute>  
    <name>num</name>  
    <required>true</required>  
</attribute>
</tag>

</taglib>


Now we are done with the creation of our custom tags. Now we have to use the tags in JSP page.

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%@ taglib uri="WEB-INF/cutomDemo.tld" prefix="mytag" %>
<title>Demo Page</title>
</head>
<body>
Cube of 8 <mytag:cube num="8" />
</body>
</html>


We'll get the below output when we test our project in browser -

Cube of 8 : 512