Interview Questions On Java,Java EE


Enter your email address:



Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Code Snippet. Show all posts
Showing posts with label Code Snippet. Show all posts

Monday, January 26, 2015

Master List Of Code Snippets

Continue reading...

Sunday, September 27, 2009

Log4j Configuration With properties file

Log4j configuration can be done either using an XML or a properties file externally. This makes your code independent of logging related steps to be followed in your code, so no ongoing source code modifications.

All you require to achieve that are logger, appender and layout. The logger object is used to do logging, appender decides where you want to append logging messages, to a console or to a file and finally layout decides on format, the way you want logging messages to be logged.

In the previous post, where BasicConfigurator.configure() is used, the default appender ConsoleAppender and layout PatternLayout are in use.

First of all the contents of log4j.properties file looks like:

log4j.rootLogger=ERROR, CA log4j.appender.CA=org.apache.log4j.ConsoleAppender log4j.appender.CA.layout=org.apache.log4j.PatternLayout log4j.appender.CA.layout.ConversionPattern=%-1r [%t] %-5p %c %x - %m%n


And now the ExampleLog4j.java file:

package com.iqjava.log4j; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class ExampleLog4j { static final Logger logger = Logger.getLogger(ExampleLog4j.class); public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); logger.debug("Here goes the debug message"); logger.error("Here goes the error message"); logger.fatal("Here goes the fatal message"); logger.info("Here goes the info message"); logger.warn("Here goes the warn message"); } }


To make things simpler for you, here is a snapshot from my Eclipse Galileo project:


The log4j levels follow the following order.
DEBUG
INFO
WARN
ERROR
FATAL

As the code level mentioned in .properties file is ERROR, it displays ERROR and FATAL messages only in result displayed of the code. If the code level would have been DEBUG then, all the messages would have been displayed on the console.

The result of the code looks like as given below:

0 [main] ERROR com.iqjava.log4j.ExampleLog4j - Here goes the error message 2 [main] FATAL com.iqjava.log4j.ExampleLog4j - Here goes the fatal message
Continue reading...

Wednesday, September 23, 2009

Velocity With XML

In this post, a code snippet describing a basic integration of XML with Velocity framework. Please ensure all runtime jar files associated with Velocity and Xerces XML parser are in your build path.

The following files are part of this code snippet;

1.XMLVelocityExample.java
2.xml.vm
3.book.xml

Here goes the Java code i.e. XMLVelocityExample.java:



import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.jdom.Document; import org.jdom.input.SAXBuilder; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.Writer; public class XMLVelocityExample { public XMLVelocityExample(String templateFile) { Writer writer = null; try { Velocity.init(); SAXBuilder builder; Document root = null; try { builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); root = builder.build("book.xml"); } catch (Exception exception) { exception.printStackTrace(); } VelocityContext context = new VelocityContext(); context.put("root", root); Template template = Velocity.getTemplate(templateFile); writer = new BufferedWriter(new OutputStreamWriter(System.out)); template.merge(context, writer); } catch (Exception ex) { ex.printStackTrace(); } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } public static void main(String[] args) { XMLVelocityExample test = new XMLVelocityExample("xml.vm"); } }


xml.vm looks like:

#macro ( recursive $xml $indent ) #if( $xml.getChildren().size() > 0 ) $indent <$xml.getName()> #foreach ($child in $xml.getChildren() ) #recursive( $child "$indent " ) #end $indent </$xml.getName()> #else $indent <$xml.getName()> $indent $xml.getTextTrim() $indent </$xml.getName()> #end #end #set($i = " ") Here goes document tree with a recursive Velocity macro : #recursive( $root.getRootElement() $i ) Now accessing data directly : email : $root.getRootElement().getChild("properties").getChild("author").getChild("email").getText() last name : $root.getRootElement().getChild("properties").getChild("author").getChild("name").getChild("fullname").getText()


book.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?> <document> <properties> <author> <email>sunnyg@sunnyg.com</email> <name> <lastname> Gavaskar </lastname> <first> Sunil </first> <fullname>Sunil Gavaskar</fullname> </name> </author> <title> Sunny Days </title> </properties> <body> Sunny within a body. </body> </document>


This is how output looks like:
Here goes document tree with a recursive Velocity macro : <document> <properties> <author> <email> sunnyg@sunnyg.com </email> <name> <lastname> Gavaskar </lastname> <first> Sunil </first> <fullname> Sunil Gavaskar </fullname> </name> </author> <title> Sunny Days </title> </properties> <body> Sunny within a body. </body> </document> Now accessing data directly : email : sunnyg@sunnyg.com last name : Sunil Gavaskar
Continue reading...

Thursday, September 17, 2009

EMailing Through Velocity Framework

Velocity Framework helps in creating a pre-formatted template based email response mechanism. The code snippet in this post elaborates how one can use this feature from Velocity framework.

While running this application, ensure you have all required Velocity framework related library classes/jars in you project build path.

Here the code is distributed in following java files:

1.EMailer.java
2.EMailClient.java
3.Customer.java
4.Order.java

Template file:
5.email.vm

Here goes:

1. EMailer.java
import java.io.StringWriter; import java.util.HashMap; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; public class Emailer { /** * Field description * * @since 1.0 */ VelocityEngine engine = new VelocityEngine(); /** * Constructor description. * * @throws Exception Description */ public Emailer() throws Exception { configure(engine); } /** * "Sends" (actually writes to System.out for demonstration purposes) a * receipt e-mail for the specified order. * * @param order Description */ public void sendReceipt(Order order) throws Exception { Template template = engine.getTemplate("email.vm"); VelocityContext context = createContext(); context.put("order", order); StringWriter writer = new StringWriter(); template.merge(context, writer); writer.close(); System.out.println("To: " + order.getCustomer().getEmail()); System.out.println("Subject: " + context.get("subject")); System.out.println(writer.getBuffer()); } /** * Configures the engine to use classpath to find templates * * @param engine Description */ private void configure(VelocityEngine engine) throws Exception { Properties props = new Properties(); props.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); props.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName()); engine.init(props); } /** * Creates a Velocity context and adds a formatter tool * and store information. */ private VelocityContext createContext() { VelocityContext context = new VelocityContext(); context.put("formatter", new Formatter()); HashMap store = new HashMap(); store.put("name", "Amazon.com Bookstore"); store.put("url", "http://amazon.comm"); context.put("store", store); return context; } }



2.EMailClient.java

import java.util.ArrayList; public class EmailClient { /** * Example usage of Emailer functionality * * @param args Description */ public static void main(String[] args) throws Exception { Emailer emailer = new Emailer(); ArrayList lineItems = new ArrayList(); lineItems.add(new Item("Thinking in Java", 24.05f)); lineItems.add(new Item("Core Java Volume I", 34.30f)); Customer customer = new Customer("John", "Brown", "jb@gmail.com"); emailer.sendReceipt(new Order(customer, lineItems)); } }


3.Customer.java

public class Customer { private String firstName; private String lastName; private String email; /** * Constructor */ public Customer(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public String getId() { return "" + firstName.charAt(0) + lastName.charAt(0); } }


4. Order.java
import java.util.Date; import java.util.Iterator; import java.util.List; public class Order { private Customer customer; private List lineItems; private String orderNumber; public Order(Customer customer, List lineItems) { this.customer = customer; this.lineItems = lineItems; orderNumber = customer.getId() + "-" + new Date().getTime(); } public Customer getCustomer() { return customer; } public List getLineItems() { return lineItems; } public String getOrderNumber() { return orderNumber; } public float total() { float total = 0; for (Iterator iterator = lineItems.iterator(); iterator.hasNext();) { Item item = (Item)iterator.next(); total += item.getCost(); } return total; } }


5. email.vm file

#set ($customer = ${order.customer}) #macro(currency $amount)${formatter.currency($amount)}#end #macro(pad $string)${formatter.pad($string, 30)}#end #macro(description $item)#pad($item.description)#end ${customer.firstName}, Thank you for your purchase. Your order number is ${order.orderNumber}. #pad("Description") Cost #foreach ($item in ${order.lineItems}) #description($item) #currency(${item.cost}) #end #pad("Total") #currency($order.total()) Visit us again at ${store.url}! #set ($subject="${store.name} receipt")


This is how the result looks like:

To: jb@gmail.com Subject: Amazon.com Bookstore receipt John, Thank you for your purchase. Your order number is JB-1253195547000. Description Cost Thinking in Java $24.05 Core Java Volume I $34.30 Total $58.35 Visit us again at http://amazon.comm!
Continue reading...

Saturday, March 29, 2008

Some commonly used validations like EMail,Phone Number,SSN,Numeric values through Regular Expressions

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionExample {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Validating Email:"
+ isEmailValid("abc@xysss.comccccc"));
System.out.println("Validating Phone Number:"
+ isPhoneNumberValid("1234567798"));
System.out.println("Validating SSN:"
+ isSSNValid("23456-werfdf"));
System.out.println("Validating Numeric Values:"
+ isNumeric("-1234"));
}

public static boolean isEmailValid(String aEmail) {
boolean isValid = false;

/*
* Examples:The following email addresses will pass validation
* asdf@tttdd.com xyzzz@tyyy.in zxg.asd@tx.govt
*/

String emailExpression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = aEmail;

Pattern pattern = Pattern.compile(emailExpression,
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}

/**
* isPhoneNumberValid: Validate phone number using Java reg ex. This method
* checks if the input string is a valid phone number.
*
* @param aPhoneNumber
*            String. Phone number to validate
* @return boolean: true if phone number is valid, false otherwise.
*/

public static boolean isPhoneNumberValid(String aPhoneNumber) {
boolean isValid = false;

/*
* Examples: Matches following phone numbers: (123)456-7890,
* 123-456-7890, 1234567890, (123)-456-7890
*
*/

String phoneNumberExpression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
CharSequence inputStr = aPhoneNumber;
Pattern pattern = Pattern.compile(phoneNumberExpression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}

/**
* isSSNValid: Validate Social Security number (SSN) using Java reg ex. This
* method checks if the input string is a valid SSN.
*
* @param email
*            String. Social Security number to validate
* @return boolean: true if social security number is valid, false
*         otherwise.
*/

public static boolean isSSNValid(String aSSN) {
boolean isValid = false;

/*
* SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx: Examples:
* 879-89-8989; 869878789 etc.
*/

String ssnExpression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
CharSequence inputStr = aSSN;
Pattern pattern = Pattern.compile(ssnExpression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}

/**
* isNumeric: Validate a number using Java regex. This method checks if the
* input string contains all numeric characters.
*
* @param email
*            String. Number to validate
* @return boolean: true if the input is all numeric, false otherwise.
*/

public static boolean isNumeric(String aNumber) {
boolean isValid = false;

/*
* Number: A numeric value will have following format:
*
* ^[-+]? : Starts with an optional “+” or “-” sign. [0-9]* : May have
* one or more digits. \\.? : May contain an optional “.” (decimal
* point) character. [0-9]+$ : ends with numeric digit.
*
*/

String numericExpression = "^[-+]?[0-9]*\\.?[0-9]+$";
CharSequence inputStr = aNumber;
Pattern pattern = Pattern.compile(numericExpression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}

}

Continue reading...

Wednesday, March 19, 2008

Sending EMail To GMail SMTP Server Using Java Mail APIs


import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
* This application will require Java Mail API and which can be downloaded from
* http://java.sun.com/products/javamail/downloads/index.html JavaBeansTM
* Activation Framework extension or JAF (javax.activation) can be downloaded
* from
* http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html.
*
* @author pundeerd
*
*
*/
public class MailingApplication {

/**
* @param args
*/
public static void main(String[] args) {

// recepients
String[] to = { "abc@gmail.com" };
String subject = "Test Email";
String message = "Hello there";
// sender
String from = "xyz@gmail.com";
try {
postMail(to, subject, message, from);
} catch (MessagingException e) {

e.printStackTrace();
}

}

private static void postMail(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = false;
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// Set the host smtp address
Properties properties = new Properties();
properties.put("mail.smtp.user", "xyz@gmail.com");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtps.auth", "true ");
properties.put("mail.smtp.debug", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");

// create some properties and get the default Session

Session session = Session.getDefaultInstance(properties, null);

session.setDebug(true);
session.setDebug(debug);

// create a message
MimeMessage msg = new MimeMessage(session);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < tr =" session.getTransport(">
Continue reading...

Tuesday, March 18, 2008

Write Into An Excel File Using Java

In order to write content to an MS Excel sheet you are required to download JExcel APIs from here.

package example;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class JExcelExample {
int mCount = 0;

public static void main(String[] args) {
try {
boolean isOutputFolder = false;
JExcelExample jexcel = new JExcelExample();
Properties prop = jexcel.loadProperties();
String sheets = prop.getProperty("org.sheets");
File directory = new File(prop.getProperty("output.folder"));
if (!directory.exists()) {
isOutputFolder = directory.mkdir();
} else {
isOutputFolder = true;
}

if (!isOutputFolder) {
System.out.println("Please provide output folder name");
System.exit(0);
}

String filename = prop.getProperty("output.filename");
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(new File(
directory.getAbsolutePath() + "\\" + filename), ws);
int count = Integer.parseInt(sheets);
for (int i = 1; i <= count; i++) {
WritableSheet sheet = workbook.createSheet(prop
.getProperty("org.sheet[" + i + "]"), i);
writeDataSheet(sheet);

}

workbook.write();
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private static void writeDataSheet(WritableSheet aSheet)
throws WriteException {
JExcelExample jExcelExample = new JExcelExample();
Properties properties = jExcelExample.loadProperties();
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.BOLD);
// WritableFont wf2 = new WritableFont(WritableFont.ARIAL, 10,
// WritableFont.NO_BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
cf.setBackground(Colour.ORANGE);
// WritableCellFormat cf2 = new WritableCellFormat(wf2);
String columnValue = properties.getProperty(aSheet.getName()
+ ".coulumn");
int columns = Integer.parseInt(columnValue);

for (int j = 1; j < columns + 1; j++) {
String coulmnValue = properties.getProperty(aSheet.getName()
+ ".coulumn.value[" + j + "]");
aSheet.addCell(new Label(j - 1, 0, coulmnValue, cf));
}

}

/**
*
* @return
*/

private Properties loadProperties() {
Properties prop = new Properties();

try {
InputStream is = JExcelExample.class.getClassLoader()
.getResourceAsStream("excel.properties");
prop.load(is);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return prop;
}

}


The content of excel.properties file looks like as given below:

org.sheets=2

org.sheet[1]=Employee
org.sheet[2]=Department


Employee.coulumn=7
Department.coulumn=12

#Columns of Employee sheet
Employee.coulumn.value[1]=First Name
Employee.coulumn.value[2]=Last Name
Employee.coulumn.value[3]=Address 1
Employee.coulumn.value[4]=Address 2
Employee.coulumn.value[5]=City
Employee.coulumn.value[6]=State
Employee.coulumn.value[7]=Contact Number

#Columns of Department sheet
Department.coulumn.value[1]=Marketing and Sales
Department.coulumn.value[2]=HR
Department.coulumn.value[3]=Finance
Department.coulumn.value[4]=IT
Department.coulumn.value[5]=Procurement and Inventory
Department.coulumn.value[6]=Legal and Taxation
Department.coulumn.value[7]=Risk Management Office
Department.coulumn.value[8]=Adminstration
Department.coulumn.value[9]=Security
Department.coulumn.value[10]=Logistics
Department.coulumn.value[11]=Communication
Department.coulumn.value[12]=Knowledge Management

#Output XL Sheet path
output.folder=c:\\TestXL
output.filename=output.xls
Continue reading...

Get Locale Specific Date


import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;


public class LocaleDate {

/**
* @param args
*/
public static void main(String[] args) {
Locale americanLocale = new Locale("en", "US" );
Locale germanLocale = new Locale("de", "DE");

DateFormat americanFormat =
DateFormat.getDateInstance(DateFormat.SHORT, americanLocale);
DateFormat germanFormat =
DateFormat.getDateInstance(DateFormat.SHORT, germanLocale);

Date date = new Date();

System.out.println(americanFormat.format(date));
System.out.println(germanFormat.format(date));

}

}

Continue reading...

Thursday, July 26, 2007

Code Snippets:XML Parsing using SAX

This code snippet shows parsing of an XML document using SAX parser.

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadXML {

public static void main(String argv[]) {
try {

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("employee.xml"));

doc.getDocumentElement().normalize();
System.out.println("Root element of the document is "
+ doc.getDocumentElement().getNodeName());

NodeList listOfEmployees = doc.getElementsByTagName("employee");
int totalEmployees = listOfEmployees.getLength();
System.out.println("Total no of employees : " + totalEmployees);

for (int i = 0; i < listOfEmployees.getLength(); i++)
{

Node firstEmpNode = listOfEmployees.item(i);
if (firstEmpNode.getNodeType() == Node.ELEMENT_NODE)
{

Element firstEmpElement = (Element) firstEmpNode;

// NodeList of first name
NodeList firstNameList = firstEmpElement
.getElementsByTagName("first");
Element firstNameElement = (Element) firstNameList.item(0);

NodeList txtFirstNameList = firstNameElement
.getChildNodes();
System.out.println("First Name : "
+ ((Node) txtFirstNameList.item(0)).getNodeValue()
.trim());

// NodeList of last name
NodeList lastNameList = firstEmpElement
.getElementsByTagName("last");
Element lastNameElement = (Element) lastNameList.item(0);

NodeList txtLastNameList = lastNameElement.getChildNodes();
System.out.println("Last Name : "
+ ((Node) txtLastNameList.item(0)).getNodeValue()
.trim());

// NodeList of id
NodeList idList = firstEmpElement
.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);

NodeList txtIdList = idElement.getChildNodes();
System.out.println("Id : "
+ ((Node) txtIdList.item(0)).getNodeValue().trim());

}

}

} catch (SAXParseException saxParseException) {
saxParseException.printStackTrace();
} catch (SAXException saxException) {
saxException.printStackTrace();

} catch (Throwable throwable) {
throwable.printStackTrace();
}

}// end of main

}



Input XML file, 'employee.xml':

<employees><employee>
<first>Tom</first>
<last>Cruise</last>
<id>MI24</id>
</employee>
<employee>
<first>Clint</first>
<last>Eastwood</last>
<id>XY01</id>
</employee>
<employee>
<first>Sean</first>
<last>Connery</last>
<id>JB07</id>
</employee>
</employees>



And here is the output of executing this code:

Root element of the document is employees
Total no of employees : 3
First Name : Tom
Last Name : Cruise
Id : MI24
First Name : Clint
Last Name : Eastwood
Id : XY01
First Name : Sean
Last Name : Connery
Id : JB07

Continue reading...

Monday, July 16, 2007

Code Snippets:File Operations

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileOperation {

/**
* @param args
*/
public static void main(String[] args) {
FileOperation fio = new FileOperation();
//Creating a source file
File sourceFile=new File("test.txt");
//Creating a destination file
File destinationFile=new File("testDest.txt");

// Writing to a file
fio.writeFile("test.txt", "Writing inside files is fun.");
// Reading from a file
fio.readFile("test.txt");
// Copy from a source file to a destination file
fio.copyFile(sourceFile, destinationFile);

}

// Read from a file
void readFile(String fileName) {
BufferedReader bufferedReader;
String line;

try {
bufferedReader = new BufferedReader(new FileReader(fileName));

while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading file");
}

}

// Write to a file
void writeFile(String fileName, String aText) {
BufferedWriter bufferedWriter;

try {
// FileWriter(fileName,true) constructor allows to append
// the data at the end of the file
bufferedWriter = new BufferedWriter(new FileWriter(fileName, true));
bufferedWriter.append(aText);
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error writing to file");
}
}

// copy from source file to destination file
void copyFile(File fileSource, File fileDestination) {
// Declare variables
InputStream inputStream = null;
OutputStream outputStream = null;

try {
// Declare variables
int nLen = 0;
inputStream = new FileInputStream(fileSource);
outputStream = new FileOutputStream(fileDestination);

// Transfer bytes from in to out
byte[] bBuffer = new byte[1024];
while ((nLen = inputStream.read(bBuffer)) > 0) {
outputStream.write(bBuffer, 0, nLen);
}

// Flush
outputStream.flush();
} catch (IOException e) {
System.out.println("Error while copying file");
}

finally {
// Close streams
try {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
} catch (IOException eError) {
}
}

}
}

Continue reading...

Thursday, July 5, 2007

Code Snippets:Experimenting With java.util.Date

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ExperimentingWithDates {

public static void daysInMonth() {
Calendar c1 = Calendar.getInstance(); // new GregorianCalendar();
c1.set(2096, 2, 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
daysInMonths[1] += ExperimentingWithDates.isLeapYear(year) ? 1 : 0;
String st = "";
if (month == 1) {
st = "st";
} else if (month == 2) {
st = "nd";
} else if (month == 3) {
st = "rd";
} else {

st = "th";
}
System.out.println("Days in " + month + st + " month for year " + year
+ " are " + daysInMonths[c1.get(Calendar.MONTH) - 1]);
System.out.println();
System.out.println();
}

public static boolean isLeapYear(int year) {
boolean value = false;
if (year % 100 == 0) {
if (year % 400 == 0) {

value = true;
}
} else if (year % 4 == 0) {
value = true;
} else {
value = false;
}
return value;
}

public static void main(String args[]) {

String DATE_FORMAT = "dd-MM-yyyy"; // Refer Java DOCS for formats
DateFormat df = new SimpleDateFormat("EEEE");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
DATE_FORMAT);
Calendar calendar = Calendar.getInstance();
Calendar otherCalendar = Calendar.getInstance();
Date date = new Date();
String day = df.format(date);

System.out.println("Today's date in Calendar Format : " + calendar);
System.out.println("Today is " + day);
System.out.println("calendar.getTime() : " + calendar.getTime());
System.out.println("calendar.get(Calendar.YEAR): "
+ calendar.get(Calendar.YEAR));
System.out.println("Today's date in Date Format : " + date);

calendar.set(1996, 0, 15); // (year,month,date)
otherCalendar.set(1996, 0, 16);
System.out.println("######");
System.out.print("Days Between " + calendar.getTime() + "\t"
+ otherCalendar.getTime() + " is  ");
System.out.println((otherCalendar.getTime().getTime() - calendar
.getTime().getTime())
/ (24 * 3600 * 1000));
if (calendar.before(otherCalendar)) {

System.out.println("Date " + sdf.format(calendar.getTime())
+ " is before " + sdf.format(otherCalendar.getTime()));
} else if (calendar.after(otherCalendar)) {

System.out.println("Date " + sdf.format(calendar.getTime())
+ " is after " + sdf.format(otherCalendar.getTime()));
}

System.out.println("######");
System.out.println("calendar.set(1999,0 ,15) : " + calendar.getTime());
// adding 20 days to Jan 20th 1999.
calendar.add(Calendar.DATE, 20);
System.out.println("Date + 20 days is : "
+ sdf.format(calendar.getTime()));

// roll down, substracts 1 month
calendar.roll(Calendar.MONTH, false);
System.out.println("Date is rolled down by 1 month : "
+ sdf.format(calendar.getTime()));
System.out.println("Reset the date back to Jan 15, 1996");
calendar.set(1996, 0, 15);
System.out.println("Date is : " + sdf.format(calendar.getTime()));
calendar.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : "
+ sdf.format(calendar.getTime()));
System.out.println();
System.out.println();

System.out.println("######");

//shows number of days in a month of a year
daysInMonth();


}

}
Continue reading...

Wednesday, June 20, 2007

Code Snippets: Using java.lang.reflect.* APIs

import java.lang.reflect.*;

public class ReflectionExample {

    public static void main(String args[])
            throws 
            ClassNotFoundException, InstantiationException,
            IllegalAccessException, NoSuchMethodException, 
            InvocationTargetException

    {
        ClassLoader j = ClassLoader.getSystemClassLoader();
        Class someClass = j.loadClass("GlobalVillage");
        Object instanceOfSomething =  someClass.newInstance();

        // the second parameter specifies the type of the argument(s) passed to method
        Method aMethod = someClass.getMethod("showMessage", new Class[]{String.class});

        //Here value of the argument of the method is provided
        Object returnValue = aMethod.invoke(instanceOfSomething, "The whole world is like a family.");

        System.out.println("Show message says : " + returnValue); 

    }

}

class GlobalVillage {
    public String showMessage(String strMessage) {
        
        return strMessage; // isn't this true??
    }
}


Continue reading...

Code Snippets: Using java.lang.Comparable Interface

import java.util.Arrays;

class Employee implements Comparable {

String empName;

String empCode;

int totalMarks;

double totalSalary;

/**
* @return
*/
public String getName() {
return empName;
}

/**
* @return
*/
public String getEmpCode() {
return empCode;
}

/**
* @param strEmpName
*/
public void setName(String strEmpName) {
empName = strEmpName;
}

/**
* @param strEmpCode
*/
public void setEmpCode(String strEmpCode) {
empCode = strEmpCode;
}

public double getTotalSalary() {
return totalSalary;
}

public void setTotalSalary(double totalSalary) {
this.totalSalary = totalSalary;
}

// sorting in desecending order of salary
public int compareTo(Object o) {

Employee employee = (Employee) o;

int comp = 0;

if (this.getTotalSalary() < employee.getTotalSalary()) {
comp = -1;
} else if (this.getTotalSalary() > employee.getTotalSalary()) {
comp = 1;
}
return comp;
}

}

//Sorts salaries of specified employess in ascending order

public class SortData {

public static void main(String[] args) {

Employee[] employee = new Employee[3];

employee[0] = new Employee();
employee[0].setName("John Adams");
employee[0].setEmpCode("3");
employee[0].setTotalSalary(2100.78);

employee[1] = new Employee();
employee[1].setName("Gregory Peck");
employee[1].setEmpCode("2");
employee[1].setTotalSalary(1234.45);

employee[2] = new Employee();
employee[2].setName("John Travolta");
employee[2].setEmpCode("1");
employee[2].setTotalSalary( 1533.87);

System.out.println("Before Comparator");
for (int i = 0; i < employee.length; i++) {
System.out.println("Rank:" + (i + 1) + "   " + employee[i].getName()
+ " Total Salary: " + employee[i].getTotalSalary());
}

Arrays.sort(employee);

System.out.println("After Comparator");
for (int i = 0; i <  employee.length; i++) {
System.out.println("Rank:" + (i + 1) + "   " + employee[i].getName()
+ " Total Salary: " + employee[i].getTotalSalary());
}
}
} 
Continue reading...

Code Snippets: Thread Interruption

Explain following code snippet:
class ThreadInterrupted extends Thread {
public void run() // called when start method executes.
{
System.out.println("Inside run");

try {
synchronized (this) {
System.out.println("Before calling wait");
wait();
System.out.println("wait is called");
}
} catch (InterruptedException ie) {
System.out.println("value of interrupted():"+interrupted());
System.out.println("Here goes printStackTrace");
ie.printStackTrace();

}
}

public static void main(String[] args) {
ThreadInterrupted threadInterrupted = new ThreadInterrupted();
threadInterrupted.start(); // control goes to run method.
System.out.println ("Before calling interrupt()");
threadInterrupted.interrupt();
}
}

Once you execute this snippet of code the output shown at console looks something like:

Before calling interrupt() Inside run Before calling wait value of interrupted():false Here goes printStackTrace java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Unknown Source) at ThreadInterrupted.run (ThreadInterrupted.java:9)

Explaination:
Immediately after start() method is called thread is interrupted.When execution goes inside run() method where a synchornised block of code exists it mean only a single instance of this class can access this piece of code which calls wait() method.The current object of current class invokes interrupt() methos which in turn cause InterruptedException.

Continue reading...

Tuesday, June 19, 2007

How will you get an IP address of a machine from its hostname?

The following code snippet gives you the IP address on the basis of Hostname:

InetAddress inetAddress = InetAddress.getByName("www.interviewjava.blogspot.com");
System.out.println ("IP  Address: " + inetAddress.getHostAddress());
Continue reading...
 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker