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”);
}
}
}
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;
}
}
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>
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.
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>();
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());
}
}
}
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.
What is a thread ? What are the ways we have in Java to create a thread ?
Write a program to create a thread using Thread class or Runnable interface.
Which is the default thread that runs in every java program internally ?
What is the difference between extends Thread or implements Runnable ? Which one is more useful.
What is thread deadlock? Describe it.
Which methods are used in thread communication.
How can you set priorities to a thread ? And, what is the default priority number of a thread ?
What is a Thread Scheduler ?
What is a Daemon Thread ?
What id thread life cycle ? Explain.
How can you improve communication between two threads?
What is ThreadGroup ? What are the benefits of ThreadGroup ?
What is the difference between Process and Thread ?
What is the difference between notify() and notifyAll() methods ?
An access specifier is a keyword that specifies how to access or read the members of a class or the class itself.
There are four access specifiers in Java as mentioned below:
private
public
protected
default
1. Private : Private members of a class are not accessible in other class either in the same package or in another package. The scope of private specifier is class scope.
2. Public : Public members of a class are accessible any where in the same package or another package. The scope of public specifier is Global.
3.Protected : Protected members are available in the same package. They are not available in the class of another package. You can access the protected members in sub class of same package or another package.
4. Default : Default members are available in the class of same package but they are not available in another package. The scope of default specifier is Package level.
In Spring MVC, view resolvers enable you to render models in a browser without tying you to a specific view technology like JSP, Velocity, XML…etc.
There are two interfaces that are important to the way Spring handles views are ViewResolver and View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
Below are the important view resolvers provided by spring framework:
AbstractCachingViewResolver : Abstract view resolver that caches views. Often views need preparation before they can be used; extending this view resolver provides caching.
XmlViewResolver : Implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring’s XML bean factories. The default configuration file is /WEB-INF/views.xml.
ResourceBundleViewResolver : Implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle base name. Typically you define the bundle in a properties file, located in the classpath. The default file name is views.properties.
UrlBasedViewResolver : Simple implementation of the ViewResolver interface that effects the direct resolution of logical view names to URLs, without an explicit mapping definition. This is appropriate if your logical names match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.
InternalResourceViewResolver : Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views generated by this resolver by using setViewClass(..).
VelocityViewResolver/FreeMarkerViewResolver : Convenient subclass of UrlBasedViewResolver that supports VelocityView (in effect, Velocity templates) or FreeMarkerView ,respectively, and custom subclasses of them.
ContentNegotiatingViewResolver : Implementation of the ViewResolver interface that resolves a view based on the request file name or Accept header.
This post explains how to create spring based web application.
Folder Structure:
Typical folder structure of the spring web application contains as below.
web.xml:
Below is the web.xml file which contains the spring configuration. DispatcherServlet is controller of the spring mvc application, all the requests which coming to the application will be passed through it. DispatcherServlet loads the spring-context.xml file during server start up and keeps the all the configurations in servlet context. Action path configured for this applications is *.html.
index.jsp file configured in web.xml as a welcome file, so this file will be loaded when user hit the http://localhost:8080/SpringMVC/ url in the browser.
<jsp:forward page=”sayhello.html”></jsp:forward>
HelloWorldController.java:
When ever index.jsp loaded into the browser, it will forward the request to sayhello.html. Thissayhello request is mapped to sayHello() method in HelloWorldController class. So, sayHello() method will be executed and it will return the ‘hello’ string after completion of method execution.
/**
*
* @author Javatutorials
*
*/
@Controller
public class HelloWorldController {
/**
* Controls the ‘sayhello’ and return to hello.jsp
* @return
*/
@RequestMapping(value = “/sayhello”, method = RequestMethod.GET)
public String sayHello() {
System.out.println(“Sample Spring Application”);
return “hello”;
}
}
spring-context.xml:
Package of HelloWorldController class is configured as a controller package in the spring-context file as mentioned below. This sample application is configured with the InternalResourceViewResolver, when ever sayHello() method returns the hello string, request will be redirected to hello.jsp based upon the InternalResourceViewResolver configuration as mentioned in the below file.
Finally ‘Hi, This is Sample Spring MVC Application’ message will be shown to the user as it is mentioned in the below 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>Sample Spring MVC Application</title>
</head>
<body>Hi, This is Sample Spring MVC Application
</body>
</html>
Below post talks about the Spring MVC integration with the tiles framework.
You can build developer friendly and user friendly web applications using the tiles framework.
Basic Folder structure of the application:
Typical folder structure of the Spring MVC application has mentioned below:
Spring MVC Application folder structure
Web.xml:
Below is the web.xml file which contains the spring configuration. DispatcherServlet is controller of the spring mvc application, all the requests which coming to the application will be passed through it. DispatcherServlet loads the spring-context.xml file during server start up and keeps the all the configurations in servlet context. Action path configured for this applications is *.html.
index.jsp file configured in web.xml as a welcome file, so this file will be loaded when user hit the http://localhost:8080/SpringMVC/ url in the browser.
<jsp:forward page=”contacts.html”></jsp:forward>
HelloWorldController .java:
When ever index.jsp loaded into the browser, it will forward the request to contacts.html. Thiscontacts request is mapped to contollContacts() method in HelloWorldController class. So, contollContacts() method will be executed and it will return the ‘contact’ string after completion of method execution.
/**
*
* @author Javatutorials
*
*/
@Controller
public class HelloWorldController {
/**
* Controls the ‘contacts’ and return to respective layout page
* @return
*/
@RequestMapping(value = “/contacts”, method = RequestMethod.GET)
public String contollContacts() {
String message = “Hi, You are in Controller !!!”;
System.out.println(message);
return “contact”;
}
}
spring-context.xml:
As the Tiles framework has been configured in the spring-context file as below with UrlBasedViewResolver, whenever contact will be returned by contollContacts() methods, request will be reached to tiles.xml and contact tile configuration will be loaded.
Below will be the tiles configuration made for our sample application. contact tiles definition is extending to base.definition and base definition will be using layout.jsp as the layout file for our application.
<definition name=”contact” extends=”base.definition”>
<put-attribute name=”title”
value=”Sample Spring MVC With Tiles Appliacation” />
<put-attribute name=”body” value=”/jsp/contact.jsp” />
</definition>
</tiles-definitions>
layout.jsp:
This layout.jsp is divided the complete application page as header, menu, body, footer. So, once the layout.jsp called, all the other jsps will be included as per the configuration mentioned in the tiles.xml file.