Wednesday, January 23, 2013

Element (center) is obsolete. Its use is discouraged in HTML5 documents


In latest version of HTML (HTML 5.0), CENTER tag is deprecated. So instead of using Tag <center>..</center>, you can use text-align:center. 'text-align' property doesn't actually aligns the division, it aligns the text content within the division.

Inline -

<div style="text-align:center">your content...</div>

Css -

.center {
  text-align:center
}

<div class="center">your content...</div>

SAXException - Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting *.0//EN

In my previous article I have shown you a simple hello world DWR example however while trying to implement it in an application I faced below exception.


SEVERE: DwrServlet.init() failed
org.xml.sax.SAXException: Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN arg1=http://directwebremoting.org/schema/dwr30.dtd
at org.directwebremoting.impl.DTDEntityResolver.resolveEntity(DTDEntityResolver.java:59)
at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1190)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1089)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1002)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at org.directwebremoting.impl.DwrXmlConfigurator.setInputStream(DwrXmlConfigurator.java:132)
at org.directwebremoting.impl.DwrXmlConfigurator.setServletResourceName(DwrXmlConfigurator.java:87)
at org.directwebremoting.impl.ContainerUtil.configureFromDefaultDwrXml(ContainerUtil.java:263)
at org.directwebremoting.impl.ContainerUtil.configureContainerFully(ContainerUtil.java:421)
at org.directwebremoting.servlet.DwrServlet.init(DwrServlet.java:79)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:791)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:127)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Jan 16, 2013 2:05:46 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet dwr-invoker
org.xml.sax.SAXException: Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN arg1=http://directwebremoting.org/schema/dwr30.dtd
at org.directwebremoting.impl.DTDEntityResolver.resolveEntity(DTDEntityResolver.java:59)
at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1190)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1089)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1002)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at org.directwebremoting.impl.DwrXmlConfigurator.setInputStream(DwrXmlConfigurator.java:132)
at org.directwebremoting.impl.DwrXmlConfigurator.setServletResourceName(DwrXmlConfigurator.java:87)
at org.directwebremoting.impl.ContainerUtil.configureFromDefaultDwrXml(ContainerUtil.java:263)
at org.directwebremoting.impl.ContainerUtil.configureContainerFully(ContainerUtil.java:421)
at org.directwebremoting.servlet.DwrServlet.init(DwrServlet.java:79)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:791)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:127)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Jan 16, 2013 2:09:33 AM org.apache.catalina.startup.HostConfig checkResources


JavaScript - onscroll function not working


Today I faced a weird issue, when I add below DOCTYPE in HTML or JSP file onscroll function stops working

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

Also I saw that, document.body.scrollTop is always coming as 0 and document.body.scrollHeight & document.body.clientHeight are always same no matter where my scroll bar is.

I didn't get much time to do research on it however to resolve this I modified DOCTYPE as shown below. If you need quick fix please add below DOCTYPE in your HTML or JSP file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

If I find more info on it, I will update the post.

Tomcat - If a JSP change does not reflect on your browser


If you face an issue in which you’re JSP changes does not reflect on your browser even after restart of your tomcat server, there could be two possible reasons -

1. Cache - This happens mostly with Internet explorer. IE does caching of JavaScript/CSS and even images in browser, hence even if u make changes to your JSP file it does not reflect on the browser. IE simply displays data from browsers cache instead of getting new data from server. To resolve this you need to clear cache of the browser and perhaps close the browser and reopen it.

2. Tomcat - The work directory is where Tomcat writes any files that it needs during runtime, such as the generated servlet code for JSPs.

Example - C:\apache-tomcat-7.0.11\work\Catalina\localhost

Even if you deployed latest code in your webapp directory changes does not reflect on your browser, the possible reason could be tomcat not able to write changes in work directory. To resolve this you can go to above directory and delete those temp files.

Myths about Instagram that Hurt Profiles


There are several debates on whether buying likes on Instagram is a solid practice for a business to be diving into. There are several companies who are on the fence about whether this is something in which they should consider or not. Many businesses maintain this is just another route in which they can use in order to increase their business and is just like any other marketing tool in which the business could utilize. While other businesses believe this is cheating in one way. The idea to Get Instagram Likes is not something in which a business should be afraid of doing, as they are going to find this gives them the jump on the competition. However, they are going to find it ideal to buy these from a company they are sure is going to give them legitimate likes, such as Get Instagram Followers. The idea of whether buying likes is just another myth and truth which has become confused for those who are utilizing Instagram, and it is important that people know the truth when it comes to these myths out there.

Myth 1: Poor Pictures is Okay

There are several people who believe picture quality is not a contributing factor to whether Instagram is going to work for them or not. They could not be more wrong, as they are going to find this to be something which can greatly affect whether they are having success with this social media application or not. The person who utilizes Instagram will want to ensure their pictures are of the highest quality for success.

Myth 2: Interacting is not needed

Since most people view Instagram as a social media application in which people simply post pictures to, they do not believe interaction among the users is necessary. However, the person who believes this could not be more wrong. They are going to find there is nothing worse than not interacting. Interacting on Instagram means liking other photos and following people. This interaction can directly affect the success a business has with Instagram and should always be considered as one of the things in which a person should be doing.

Tuesday, January 22, 2013

Linux - Commands for Grep or Search recursively


Below are the commands for -

Grep for a particular text recursively

find ./ -name "*" | xargs grep "text" {} 2>/dev/null

Search for a particular file recursively

find ./ -name "*.properties" 2>/dev/null

Load PROPERTIES file in PHP like JAVA


A property file is basically consist of a data in key/value pair. In PHP is bit different than java. In java we used to create a .properties file and load using below code

Properties prop = new Properties();
prop.load(new FileInputStream("sample.properties"));

Now we will see equivalent code in PHP. In PHP instead of .properties it's .ini file and it is loaded using parse_ini_file() method. Please see the self explanatory code below

myProperties.ini

; This is a property file
; Comments start with ';', as in php.ini

id = 001
name = Alex
state = NY

loadProperties.php


<?php
$ini_array = parse_ini_file("myProperties.ini");
echo "Printing the array<br/>";
print_r($ini_array);

echo "<br/>";
echo "Get values by name";
echo "<br/>id = ".$ini_array['id'];
echo "<br/>name = ".$ini_array['name'];
echo "<br/>state = ".$ini_array['state'];
?>

PHP - read and write text file


Below are the sample codes to read and write text file using PHP

Read content of a file

<?php
//file name
$filename = "textFile.txt";

//open the file with Read only Mode. Starts at the beginning of the file.
$file = fopen($filename, "r");

//all content the file
$contents = fread($file, filesize($filename));

//close the file
fclose($file);

//print the content
echo $contents;
?>


Read content of a file line by line

<?php
//file name
$filename = "textFile.txt";

//open the file with Read only Mode. Starts at the beginning of the file.
$file = fopen($filename, "r");

//loop the file until the end is reached
while(!feof($file))
{
echo fgets($file)."<br>";
}

//close the file
fclose($file);
?>


Monday, January 21, 2013

500 Internal Server Error / hide .php extension using .htaccess


In my first php project I was required to hide .php extension from the URL. For example if the URL is 'http://localhost/Test/request.jsp' it should display 'http://localhost/Test/request' in browser. I found many links which were showing how to achieve that using .htaccess file however it was not clear where to place that file, under root directory OR under the website directory. I tried both the locations but as soon as i add anything in the file .htaccess it used to give below error.

Error:



Sunday, January 20, 2013

How Ethical Hacking Helps Progress




Before the role was that of a penetration tester. Such a person had to be of nerdy or furtive
character and would have the ability to test out computer networks in order to find out
security flaws on them. Such a role is getting a makeover along with a change in name. The
name change has been to that of ethical hacker which also explains the rise in such a role
or job among computer graduates these days. The name change is not the reason alone
for the rise of popularity but also due to the job being challenging and fascinating. Again,
such a job role is becoming increasingly in demand as systems and networks are being built
in impenetrable ways only to find that one had to find a way to get in after the doors have
been closed.

Cyber Space Offers Challenges

The cyber space is becoming the preferred place for most criminals these days and even
governments are waging wars of industrial espionage through cyber space. Hence, big
or small businesses are hiring experts who will help to protect their interests online.
Computer graduates are becoming the preferred choice as there is a lot of learning involved
in performing such a role and usually graduates who are hungry for challenges are up to
such roles. There have also emerged courses in universities that are dedicated to such a
discipline showing the lucrativeness of such a career choice in the industry today.

Wednesday, January 16, 2013

Open Popup div with disabled background using Javascript


Let's see a simple HTML code for Popup div with disabled background. On clicking a particular link it will open a popup div with desire information, it can also be used as popup window. Below example shows following features -

  1. Onclick opens a popup div with disabled background
  2. Close popup div using escape button
  3. Opens popup div exactly at the center of the screen
  4. Opacity can be controlled within 

Below is the tested code, directly you can save it and see the output.

Tuesday, January 15, 2013

Javascript example - Set cookies and Remove cookies


A cookie is a variable that is stored on the users browser and depends on browser's configuration. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a server and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie can be retrieved by the website to notify the user's previous activity like clicking particular buttons, logging in, or a record of which pages were visited.

Example - The first time a user visits to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time when the user visits at your page, he or she could get a welcome message like "Welcome Alex!" The name is retrieved from the stored cookie. In the below example we will see how to set cookie and remove cookie.

Below is the tested code, you can directly save it and see the output.

Friday, January 11, 2013

Java program to ping an IP address

Below is the Java program to ping an IP address.


Also note that you can use below syntax to check if remote IP address is is reachable or not.

String ip = "google.com";
InetAddress address = InetAddress.getByName(ip);
boolean chkConnection = address.isReachable(1000);

Javascript - Unterminated string constant


If you receive below error, check at the specified line. As the error suggest, most probably you have added a line break or some incorrect syntax. To resolve the error just remove the line break or check for proper syntax and the error would go off.

Message: Unterminated string constant
Line: 443

 If you are using Linux, check for line break using below command in vi editor. It will show you symbol '$' at the end of each line. Just remove the line break at the specified line.

 :se list

As the error suggest 'Unterminated string constant', mostly it may occur due to some incorrect syntax.

Thursday, January 10, 2013

Java - To Know which Jar file is referring for a particular class



Many times it happens that multiple JAR files are referring to a particular class and such ambiguity may cause problem in our application. Lets a simple program which can help to detect which jar file is referring for a specific class.

I have added the code in a java program however you can add it in your JSP or a Servlet as per your requirement.


Java program to read a text file

Below java program can be used to read a text (.txt) file or any other text based file like .xml, .properties etc


Java function to reverse a String

Please see below, a simple java function to reverse a String. You can use it to check for palindrome as well.

Simple java program to send Mail using JavaMail API

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. to know more, click here.

For below program to run, please add mail.jar in your application's classpath. Download mail.jar.


Wednesday, January 9, 2013

QuickBooks and eCommerce – Integrated Systems


Technology is allowing more individuals to access the freedom of working for themselves than ever before and eCommerce solutions are one of the key factors in this brave new world.  As more High Street stores bite the dust each week, the rise of eCommerce appears to be getting faster.  Despite the fact that Christmas is just around the corner, the media continue to report on the closure, job losses and move online of more famous, High Street brands.  For those already successfully operating online the continued dominance of eCommerce is great news.  For those setting up online for the first time there are a number of factors to consider and significant one is often a question of systems integration with eCommerce platforms. Accounting systems, in particular, can be important when migrating to the world of eCommerce and an eCommerce site that doesn't integrate well, or at all with, your existing accounting systems can be a time consuming problem.  One widely used accounting package is provided by Intuit; QuickBooks Online Accounting software is popular with small and medium businesses as it has been designed and specifically built with their needs in mind.

Types of Integration

Intuit have become a leading provider for small businesses because they understand the needs of these firms and the rapidly changing landscape in which they operate.  They have developed their systems with these rapid changes in mind and, as a result, are a leading provider in the online accounting field.  Cloud provision of software is likely to become the only provision in the not too distant future, and it offers huge advantages to small firms, most notably in the time saving and flexibility areas of life.  For those moving into eCommerce, the good news is that QuickBooks products are widespread enough for many eCommerce providers to take note and make their system easily to integrate.  When it comes to integrating software such as QuickBooks online accounting software, there are two main approaches; firstly to choose a provider that allows easy integration and secondly to employ software that can provide a ‘bridge’ between the two systems, creating an integrated solution.

Tuesday, January 8, 2013

How to Use Cloud Computing for a Business and Home?


Cloud computing offers many benefits in both home and office settings. Cloud services provide
a secure way of storing large amounts of data. Information can be shared between individuals or
companies and the networks can be made either public or private depending on the nature of the
information stored. Cloud servers offer a variety of packages to meet the needs of families and
businesses of various sizes.

While many families do not need the vast amounts of storage cloud computing offers, the
security it provides can protect important medical documents and insurance information.
Businesses, on the other hand, need the capability for ever increasing amounts of storage as well
as proven security features that protect their confidential information. Family and business have
various needs that can be met using cloud computing services tailored specifically for them.

Getting started is as easy as contacting a cloud service. Many offer trial periods so customers can
create a service and after a specific amount of time (normally 30 to 90 days) can decide whether
or not they want to sign on for a long term contract. If they do not like the service, they retrieve
their information and move on to the next company. If they do choose to continue with the cloud
service, they agree to a specific time period. They fine tune the package they have created and
agree to pay by the month, semi-annually or annually, depending on their needs.

JavaScript - How to get random numbers and random alpha-numeric numbers?


In this article we will see how to generate random numbers and alpha-numeric numbers in JavaScript  We will use JavaScript Math.random function to generate random numbers.

Math.random function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Please see the below function.


1. Get random numbers

//get random numbers
function getRandomNumber() {
var max = 10;
var randomnumber = Math.floor(Math.random()*max)
return randomnumber;
}

2. Get random numbers between minimum and maximum range

//get random numbers between minimum and maximum range
function getRandomNumber() {
var min = 10;
var max = 20;
var randomnumber = Math.floor((Math.random()*(max - min + 1))+min);
return randomnumber;
}


Monday, January 7, 2013

Java - Various ways to iterate a Map (Hashtable, HashMap, TreeMap, LinkedHashMap)


A Map is collection that maps keys to values. A map cannot contain duplicate keys, each key can map to at most one value. Map comes with 4 different version - Hashtable, HashMap, TreeMap, LinkedHashMap.

Hashtable - Key methods of Hashtable are synchronized. Hashtable doesn't allow a null key or null values.

HashMap - HashMap allows one null key and multiple null values in a collection.

TreeMap - TreeMap is a sorted Map.

LinkedHashMap - LinkedHashMap maintains insertion order.

Below are the methods in which you can iterate a Map.

1. Iterator - Using Iterator you can iterate HashMap, TreeMap, LinkedHashMap.

2. Enumeration - Using Enumeration you can iterate Hashtable.

3. Also you can iterate values of a Map using values() and elements() method.

Java - Various ways to iterate a Set


A Set is a collection that contains no duplicate elements. Below are the methods in which you can iterate a Set

1. For each loop (introduced from Java 5)
2. Array and While loop (here you can use for loop as well)
3. Using Iterator

Please see the below code.

Different type of ways to iterate a List in java


As List is dynamically growable array. Below are the methods in which you can iterate a List

1. Basic for loop
2. For each loop (introduced from Java 5)
3. While loop
4. Using Iterator
5. Using ListIterator (Unlike Iterator which traverse list in forward direction, ListIterator is used to traverse the list in either direction)

Please see the below code.

Saturday, January 5, 2013

Firefox 18 Beta Boasts Faster JavaScript


The latest incarnation of Firefox features faster JavaScript and even has Mac users excited.
Firefox 18 beta rings in 2013 with a slew of new features, but what most people are interested in
is the lightning-fast JavaScript.

The just in time (JIT) compiler has been nicknamed IonMonkey, in keeping with the tradition
of monkey monikers such as JaegerMonkey of Firefox past. IonMonkey was introduced in
September 2012, but it’s just beginning to pick up steam.

IonMonkey has the ability to allow for complex JavaScript at a much faster speed than previously
thought possible. Whether you work in workers’ comp or programming for a federal agency,
this might make your daily life easier. There are a few things to consider, but it’s estimated that
IonMonkey can improve performance up to 26 percent. And when your performance is upped
more than one quarter, that’s cause for celebration.

Thursday, January 3, 2013

Spring - How to inject List or Map using bean?

In this example we will see how to How to inject List or Map using Spring bean. For complete setup using eclipse you can refer my previous article, Spring Hello World Example.

About the example - We have a class Country.java with two instance variables city as Map and president as List. We will set those values using Spring bean with the help of Spring configuration file  applicationContext.xml. Please see the self explanatory codes below

Country.java.


Serialization in Java


Serialization is used to save the object and all of its instance variables (except transient) in an external file mostly with .ser extension. With the help of Serialization you can reconstruct the same object latter.

The Serialization is done with the help of below two methods

// serialize objects and write them to a stream
ObjectOutputStream.writeObject() 

// read the stream and deserialize objects
ObjectInputStream.readObject()

About the example - We have a Dog class, which we will be Serializing. Note that Class which to be serialize must implements the Serializable interface. Serializable is a marker interface, it has no methods to implement. In SerializeDog.java we will create a Dog object d1 serialize it and write it to a dog.ser file and latter we will deserialize the object.

Please see the java codes below



Wednesday, January 2, 2013

Java 5 - Using Static Imports


Static Imports concept was introduced with Java 5, the static import statement just provides greater keystroke-reduction capabilities. Static imports can be used when you want to use a class's static members. You can use this feature on classes available in the API and on your own classes.

Rules associated with Static import


  • Correct syntax is import static, you can't say static import.
  • Check for ambiguously named static members. For example if you do a static import for both the Integer class and the Long class, referring to MAX_VALUE will cause a compiler error, since both Integer and Long have a MAX_VALUE constant, and Java won't know which MAX_VALUE you're referring to.
  • You can do a static import on static object references, constants (static and final), and static methods.


For example - 

Before static imports:

public class TestStatic {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}

After static imports:

import static java.lang.System.out;
import static java.lang.Integer.*;

public class TestStaticImport {
public static void main(String[] args) {
out.println(MAX_VALUE); 
out.println(toHexString(42)); 
}
}

Both of the above classes produces same output.

Java - Source File Declaration Rules


Below are the rules associated with declaring classes, import statements, and package statements in a java source file.


  • There can be one and only one public class per source code file and can have more than one nonpublic class.
  • If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class HelloWorld { } must be in a source code file named HelloWorld.java. Files with no public classes can have a name that does not match any of the classes in the file.
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  • import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • Comments can appear at the beginning or end of any line in the source code file, they are independent of any of the rules discussed above.