Example Program – Armstrong Number


Below sample programs finds whether the given number is an Armstrong Number or not.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371. Few more Examples for the Armstrong numbers are : 153, 371, 9474, 54748.

 

package in.javatutorials;

/**
* @author malliktalksjava.in
*
*/
public class ArmstrongNumber {

/**
* @param inputNumber
* @return boolean true/false will be return
*/
public static boolean isArmstrong(int inputNumber) {
String inputAsString = inputNumber + “”;
int numberOfDigits = inputAsString.length();
int copyOfInput = inputNumber;
int sum = 0;
while (copyOfInput != 0) {
int lastDigit = copyOfInput % 10;
sum = sum + (int) Math.pow(lastDigit, numberOfDigits);
copyOfInput = copyOfInput / 10;
}
if (sum == inputNumber) {
return true;
} else {
return false;
}
}

/**
* @param args
*/
public static void main(String[] args) {
int inputNumber = 153;
System.out.print(“Enter a number: “);
boolean result = isArmstrong(inputNumber);
if (result) {
System.out.println(inputNumber + ” is an armstrong number”);
} else {
System.out.println(inputNumber + ” is not an armstrong number”);
}
}
}

 

Example program to reverse a Number in Java


 

package in.javatutorials;

public class ReverseNumber {

public static void main(String[] args) {
System.out.println(“The reversed number is ” + reverse(1234));
}

public static int reverse(int input) {
int result = 0;
int rem;
while (input > 0) {
rem = input % 10;
input = input / 10;
result = result * 10 + rem;
}
return result;
}
}

 

Struts Internationalization Example


web.xml :

<?xml version=”1.0″ encoding=”Shift_JIS”?>

<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
http://java.sun.com/dtd/web-app_2_3.dtd”&gt;

<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-nested</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>

</web-app>

struts-config.xml:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 1.2//EN” “http://struts.apache.org/dtds/struts-config_1_2.dtd”&gt;
<struts-config>
<data-sources>
</data-sources>
<form-beans>
<form-bean name=”loginform” type=”org.apache.struts.validator.DynaValidatorForm”>
<form-property name=”username” type=”java.lang.String”></form-property>
<form-property name=”password” type=”java.lang.String”></form-property>
</form-bean>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
</global-forwards>
<action-mappings>
<action path=”/login” type=”in.javatutorials.actions.LoginAction” name=”loginform” validate=”true” input=”/login.jsp”>
<forward name=”success” path=”/welcome.jsp”></forward>
<forward name=”failure” path=”/login.jsp”></forward>
</action>
</action-mappings>
<controller locale=”true” processorClass=”org.apache.struts.tiles.TilesRequestProcessor”/>
<message-resources parameter=”ApplicationResources”/>
<plug-in className=”org.apache.struts.tiles.TilesPlugin”>
<set-property property=”definitions-config” value=”/WEB-INF/tiles-defs.xml”/>
<set-property property=”moduleAware” value=”true”/>
</plug-in>
<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
<set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml”/>
</plug-in>
</struts-config>

login.jsp :

<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-nested” prefix=”nested” %>

<html:html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=Cp1252″/>
<title></title>
</head>
<body bgcolor=”yellow”>
<center>
<html:errors/>
<bean:message key=”welcome.message”/>
<html:form method=”POST” action=”login”>
<bean:message key=”username”/><html:text property=”username”></html:text><br><br>
<bean:message key=”password”/><html:text property=”password”></html:text><br><br>
<html:submit><bean:message key=”register.submit”/></html:submit>
</html:form>
</center>
</body>
</html:html>

LoginAction.java:

 package in.javatutorials.actions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

/**
* LoginAction Class
*/

public class LoginAction extends Action {
/**
* Action class execute method
*/

public ActionForward execute(ActionMapping actionMapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)throws Exception{

String responseKey=”failure”;
DynaValidatorForm dynaValidatorForm=(DynaValidatorForm) actionForm;
String user=(String)dynaValidatorForm.get(“username”);
String pwd=(String)dynaValidatorForm.get(“password”);

if(user.equals(pwd))
responseKey=”success”;
return actionMapping.findForward(responseKey);

}
}

welcome.jsp :

<%@ page contentType=”text/html; charset=Cp1252″ %>
<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-nested” prefix=”nested” %>

<html:html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=Cp1252″/>
<title></title>
</head>
<body bgcolor=”green”>
<h1><bean:message key=”welcome”/></h1>
</body>
</html:html>

ApplicationResources_it.properties :

welcome.message=Dare if benevenuato all aperatoreitaliano(in english:welcome to italian user)
welcome=<b>Dare if benevenuato all aperatoreitaliano</b>
username=<b>nome de operatore</b>
password=<b>parola de ordine</b>
register.submit=registero
errors.required=<li><i>if compo di{0}non puo essere vuoto</i></li>
errors.minlength=<li><i>la {0}non puo essere vuoto {2} carreteri.</i></li>

ApplicationResources_en.properties :

welcome.message = welcome to english user
welcome=<b>Hello english user welcome to our website</b>
username=<b>username</b>
password=<b>password</b>
register.submit=register
errors.required=<li><i>{0}field cannot be empty.</i></li>
errors.minlength=<li><i>{0}cannot be lessthan {2} charecters.</i></li>

How to find count of duplicates in a List


There are many different ways to find out the duplicates in a List or count of duplicates in a List object. Three best ways have been implemented in the below sample class. I suggest to go with 2nd sample, when there is a requirement in your project.

package in.javatutorials;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CountOfDuplicatesInList {

public static void main(String[] args) {

List<String> list = new ArrayList<String>();
list.add(“a”);
list.add(“b”);
list.add(“c”);
list.add(“d”);
list.add(“b”);
list.add(“c”);
list.add(“a”);
list.add(“a”);
list.add(“a”);

// Find out the count of duplicates by passing a String – static way
System.out.println(“\n Output 1 – Count ‘a’ with frequency”);
System.out.println(“a : ” + Collections.frequency(list, “a”));

// Find out the count of duplicates using Unique values – dynamic way
System.out.println(“\n Output 2 – Count all with frequency”);
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
System.out.println(temp + “: ” + Collections.frequency(list, temp));
}

// Find out the count of duplicates using Map – Lengthy process
System.out.println(“\n Output 3 – Count all with Map”);
Map<String, Integer> map = new HashMap<String, Integer>();

for (String temp : list) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(“Key : ” + entry.getKey() + ” Value : ”
+ entry.getValue());
}
}
}

 

Other Useful Links:

Avoid nested loops using Collection Framework in Java

Replace special characters in a String using java

Singleton Design pattern in JAVA

Convert Array to Vector in Java

How to Copy an Array into Another Array in Java

Tips to follow while doing java code

How to Create a Thread Using Runnable Interface


In Java, a Thread can be created by extending to a Thread class or by implementing the Runnable Interface. In below example, I have tried to create the thread by implementing Runnable interface.

package in.javatutorials;

public class CreateThredByRunnable {

public static void main(String[] args) {
Thread myThreadA = new Thread(new MyThread(), “threadA”);
Thread myThreadB = new Thread(new MyThread(), “threadB”);
// run the two threads
myThreadA.start();
myThreadB.start();

try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
// Display info about the main thread
System.out.println(Thread.currentThread());
}

}

class MyThread implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread());
}
}
}

 

Other Useful Links

Threads Interview questions in Java

Multi-Threading Interview questions


Thread concept is the most important topic for all the interviews. This post contains most important interview questions on Thread concepts. The answers for these questions will be covered in further posts.

  1. What is a thread ? What are the ways we have in Java to create a thread ?
  2. Write a program to create a thread using Thread class or Runnable interface.
  3. Which is the default thread that runs in every java program internally ?
  4. What is the difference between extends Thread or implements Runnable ? Which one is more useful.
  5. What is thread deadlock? Describe it.
  6. Which methods are used in thread communication.
  7. How can you set priorities to a thread ? And, what is the default priority number of a thread ?
  8. What is a Thread Scheduler ?
  9. What is a Daemon Thread ?
  10. What id thread life cycle ? Explain.
  11. How can you improve communication between two threads?
  12. What is ThreadGroup ? What are the benefits of ThreadGroup ?
  13. What is the difference between Process and Thread ?
  14. What is the difference between notify() and notifyAll() methods ?
  15. Explain some of the methods in Thread class.