Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

In this post we will learn different types of Android Layout and some basics of an Android App.
0
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
2
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the basics of OOAD by referring the real time objects.
0
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different display functions to keep the overall setup running more care and control.
However, there is always plenty of room for improvement when getting any kind of Java process running right. There are many things that can be done to make it easier for Java functions to be run the right way.
 
Don’t Create Unnecessary Objects

First, it is important to ensure that the objects being created through Java are absolutely functional to the success of a website. A website must be designed with an organization that is doesn’t include anything unnecessary. Unnecessary objects can make it harder for a website to operate and load up. Keeping and unnecessary items out will help keep the coding setup shorter and therefore easier to load.

Avoid Wrapper Classes

Wrapper classes can store information on everything within a site and may be too complicated. It can take a long time to load up some of these classes. A primitive class may be used instead as this focuses on values above all else.

Avoid Null Collections

Some arrays, collections and other features may end up being empty. You have to return them as being empty instead of being null. This is to keep the testing process from being hurt by a slow setup that is far…
1
Introduction
This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how to add it to a test suite, then running and debugging it.

This article doesn’t aspire to be The Way To Do Automation and it doesn’t go into deep details on processes or tools, but if you read it you should come away with a reasonably clear picture of one way to efficiently and effectively develop and execute automation tests for a website. This process helps us achieve our test automation goals.

Test Design Approach
Experts Exchange website consists of a large set of web pages. There are groups of pages with the same format. For example, all the pages that display a question have the same layout. We refer to this as the view question layout. Likewise, we refer to the view article layout and the view video layout for the pages where articles and videos are displayed.

To test our site EE QA uses something called the Page Object model. Basically, this is an encapsulation of a web page into a class. For example, we have ViewQuestion, ViewArticle and ViewVideo classes. Our test cases for the view question layout call ViewQuestion methods, rather than have each test try to directly interact with items (buttons, text boxes, etc) on the page. The page’s attributes and actions are encapsulated in…
4
 
LVL 66

Expert Comment

by:Jim Horn
Comment Utility
Nicely illustrated.  Voted Yes.
0
Introduction
This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by Experts Exchange QA Team. We develop our automated test cases in a Windows environment so that’s the focus here.

Java and Eclipse Installation and Configuration
First we install Java and Eclipse. We use Installing Eclipse video as our guide. You should be able to install and configure them after watching this video. More java help can be found here.

TestNG Installation and Configuration
Installation and configuration of TestNG is fairly simple. Follow the steps for Eclipse plug-in here. Here’s a snapshot of part of the installation process. The installation wizard does a good job of walking you through the process.

EEQA_2_NG.png
Installation of the Eclipse plug-in makes it possible to run TestNG suites while in Eclipse, but the TestNG classes are actually included in the selenium WebDriver jar file. You’ll see in EE QA: Developing and Running Automated Tests For Our Website how we use TestNG features in our automation.

Selenium WebDriver Installation and Configuration
We use the standalone server in our environment so all we do is get it from the download page.
EEQA_2_WD.pngAfter it is downloaded we add it to our Eclipse build path by right clicking on the project, then going to Build Path -> Configure Build Path
EEQA_2_BP.png
2
Introduction
This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to achieve those goals.

The second article covers installation and configuration of these tools. It is aptly titled EE QA: Install and Configure Selenium, Java, Eclipse, and TestNG. We work in a Windows environment so the article is written from that perspective.

The third article, EE QA: Developing and Running Automated Tests For Our Website, covers our approach to test case design and implementation, as well as our runtime environment. It contains some good design and implementation practices.

Our Test Automation Goals
In order to continually improve our member’s experience, our engineering teams focus on quickly delivering high quality, high value enhancements to our web site. To facilitate these activities we use the Agile Development process. In Agile, testing is an ongoing activity of each sprint. Within a sprint our QA folks manually test new features and also write new automated test cases …
6
 
LVL 16

Expert Comment

by:Kyle Santos
Comment Utility
Great job, Marlon!
0
 
LVL 7

Expert Comment

by:Yashwant Vishwakarma
Comment Utility
Nice information Marlon
Voted "Good Article" :)
0
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation, easy programming and fast execution.
6
 

Expert Comment

by:Chad B
Comment Utility
Good article but needs proof reading and cleaning up.  For example, there is more than one place that says the opposite of what is intended (e.g. "Like Java and C++, go is not object-oriented...").
0
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collection framework built into the Oracle JDK. It allows Java administrators and developers to gather detailed low level information about how the Java Virtual Machine (JVM) and the Java application are behaving. Java Mission Control is an advanced set of tools that enables efficient and detailed analysis of the extensive of data collected by Java Flight Recorder. The tool chain enables developers and administrators to collect and analyze data from Java applications running locally or deployed in production environments.

The Java Flight Recorder does not trace every function call that gets executed. Instead, it "samples" the application at regular intervals, collecting stack trace information about each thread being executed. So if you're looking for how many times a certain function is being called, or how much total time is spent executing a certain method, you're not going to find that kind of information. However, by analyzing the samples taken, you can still determine where your application is spending most of its time.

We'll assume, at this point, that Java 8 and Eclipse are already installed. If they are not, they can be found at the following locations:
2
Optimize your web performance
LVL 1
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
5
Java provides two main ways to perform string concatenation and one of them could cause you some trouble. The first one most of us encounter is the + operator, where doing something like String value = "Hello " + "world"; results in a string with the value "Hello world". Most of the time, developers don't immediately learn that the + operator is just syntactic sugar that the compiler turns into StringBuilder operations, that being the other main way one can concatenate strings in Java.

This article uses examples from the Java source code in (ConcatenationDemo.java). It also uses some of the same bytecode-reading techniques I used in my previous article.

Just about every time the compiler encounters a + operator that has String objects or literals as its arguments, it translates that code into a three-step sequence of operations:
 
  1. Create a new StringBuilder instance, passing the first argument to its constructor.
  2. Call StringBuilder.append() and pass the second argument.
  3. Call StringBuilder.toString().

The compiler does optimize this operation, when it can, though. For example, if a line of code is creating a String value by concatenating several literals or constants together, the compiler will concatenate those values itself and place the resulting value in the compiled class:
 
   public String concatenationDemo1()
   {
      String value = "literal1" + " " + "literal2" + " " + STRING_CONSTANT;
      
      return value;
   }

Open in new window

The value that ends up in the compiled bytecode is "literal1 literal2 constant"
1
Before I proceed, I should point out that I've always heard and used the term "line terminator" to refer to the characters that signify the end of a line of text, but the Java API documentation uses "line separator," so I've used that here, for consistency.

If you've ever run the same Java code on a Windows-based machine and a Unix- or Linux-based machine, you've probably noticed that lines of text don't always end the same way. Windows uses two characters: a carriage return (CR) and a line feed (LF). (Java uses '\r' and '\n' to represent these characters, respectively.) A good chunk of the rest of the world gets by with just an LF character ('\n'). Java does a pretty decent job of insulating developers from this distinction by having BufferedWriter.newLine() use whatever line separator is appropriate for the current operating system. (System.out.println(), by the way, typically is a call to PrintStream.println(), which calls BufferedWriter.newLine() behind the scenes.)

What if you need to override that behavior, though?

A few years ago, we at Experts Exchange ran into an issue with an internal tool where some of our machines were using Windows-style line separators and others were using the Unix-style. We needed a way to keep things consistent across platforms and had a few options open to us:
 
  • We could have overridden the line separator behavior for the entire JVM by specifying a value for the line.separator
1
This article uses examples from the Java source code in (BytecodeDemo.java) and its decompiled bytecode in (BytecodeDemo-decompiled.txt).

In my previous article, I wrote that, "Code that works well is good code." When I say, "works well," I mean both "works correctly" and "works efficiently." We've all pored over bits of code, trying to root out inefficiencies. One of the ways we can examine Java code is by decompiling it, using the javap command from the JDK. (If you're not familiar with how to read bytecode, please see an article like this one for a primer: Java Bytecode Fundamentals)

For example, download BytecodeDemo.java, build it, then run this command:
 
javap -c BytecodeDemo.class

Open in new window


You should see a list of the methods in the BytecodeDemo class, along with the bytecode that the Java VM would execute in order to run those methods. The bytecode definitely shows a few things that could be called "inefficiencies," but it might not be the best idea to "fix" them.

First, look at the bytecode for the computeValueAndDoNothing() method. It calls the computeString() method, but does not use the value it returns. That value is still on the JVM stack, though, so the method has to do that pop operation to get rid of it.

Seems like the computeValueAndDoNothing() method would be more efficient if it didn't have to pop that value, right? The only way to pull that off would be if the computeString() didn't return a value in the first place. We can't do that, though; that method is used in other places—places that do
3
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
Useful and interesting article, thanks for it. Well written.
My concern is that precisely because you say "It's entirely possible that the JIT compiler will look at the computeValueAndUseItLater() method and figure out . . . ", that we are really no wiser as to what the effect of one's subjective attempts at code streamlining might be. It seems that the conjecture about what the JIT does is somewhat akin to belief in God - you have nothing to lose and much to possibly gain, just by saying "yes". But no real proof in the end that you can take to the bank.
0
 
LVL 14

Author Comment

by:CPColin
Comment Utility
Hence the message I lay out in my conclusion: gather the proof first, then optimize the part of the code that's having a problem.
0
If you write a lot of code, either professionally or as a hobby, it's almost inevitable that somebody else will read your code at some point. I spend a lot of time reading code in the Java runtime library, in third-party libraries, and in old projects I've worked on. I tend to notice patterns of code that could be just a little bit better, even in code I've written. It occurred to me that, when reading some code, these patterns can taint my perception of the quality of the overall product. When evaluating a third-party library, I might pass it up, if a large portion of it is written in a less-than-pleasing way.

When you apply for a job that requires a sample of your work, your potential employer could pass you up, for the same reason.

Code that works well is good code. Code that looks nice is even better. Here are some patterns that come up a lot, with some suggestions for how to improve them.
 

Iterating over a map


This pattern comes up a lot, when iterating over an instance of Map:
 
Map<K, V> map;

for (K key : map.keySet())
{
   doSomethingWithKey(key);
   doSomethingWithValue(map.get(key));
}

Open in new window


Here's the problem, though: this code is calling Map.get() for each key. This code should be iterating over the entries in the map, not the keys. Fortunately, Map.entrySet() gives us exactly what we need:
 
Map<K, V> map;

for (Map.Entry<K, V> entry : map.entrySet())
{
   doSomethingWithKey(entry.getKey());
   doSomethingWithValue(entry.getValue());
}

Open in new window


This lets us skip doing the extra map lookups.
 

Initializing variables too soon


Sometimes, code will initialize a variable to a value, then immediately set it to a different value:
 
Object value = DEFAULT;

if (condition)
   value = new Object();

Open in new window


It's a minor point, but that code could be written like this, instead:
 

Open in new window

4
 
LVL 38

Expert Comment

by:lherrou
Comment Utility
But given that the article is essentially about practicing best coding practices... is a trick that works well, but is still a trick a best practice?
0
 
LVL 14

Author Comment

by:CPColin
Comment Utility
It's not really a trick; Doug's version is just a single-line version of the example code I suggested. If my code did some complex computations in each branch of the conditional before initializing the variable, we wouldn't be able to condense it down to one line. As it is, though, both my version and Doug's version are perfectly valid ways of performing the same operation. (I'd even bet that the bytecode came out the same.)
0
I was doing some work for a client, and they were having an issue with an application that uses Java. As it turns out, they can't install or remove the version of Java that is on the laptop.

I try to install/remove and I get:

Java 7 Update 45
The feature you are trying to use cannot be found.
Use source ( in the box there is a 1)

I click OK and it gives me

The path 1 cannot be found try to find the installation package "jre1.7.0._17-c.msi in a folder.

I cancel out.

It gives me:
Error 1714 The older version of Java cannot be removed.

I search the web for all different solutions, about 5 hours worth and nothing.
Deleting any Java related folders/files in windows
Making sure I removed anything related to java from the registry.

Nothing worked, same result... Ready to format the machine and reload EVERYTHING...

Then I tried the following:

Open regedit
Use the find option in the edit menu
I put the version of java that it was looking for when I was trying to load or unload, in the find field. In my case it was

 jre1.7.0._17-c

Clicked find

Boom!

There it was, a registry key that had my version in it, on closer inspection there were other references inside the key to the source being "1" just like the error message I got above.

I knew this was it.

I backed up the key.

Deleted this key and the parent key above it which also had some additional java info in it.

Rebooted the machine and PRESTO!

I was able to load both the…
0
When compiling a Java source file using javac from JDK 7 the generated class file format is incompatible with previous JRE versions including version 6.

Therefore when trying to run the class file using Java 6 the following cryptic exception is thrown by Java:
Exception in thread "main" java.lang.UnsupportedClassVersionError: HelloWorld: Unsupported major.minor version 51.0

Class version 51.0 is the version of class file generated by javac 7 while Java 6 expects class file format 50.0 or lower.

To solve the problem you need to tell javac 7 to create a class format compatible with previous versions of Java.

With previous versions of java adding the -target flag solved the problem:
javac -target 1.6 HelloWorld.java

However as of Javac 7 this command emits the following error:
javac: target release 1.6 conflicts with default source release 1.7

Adding the -source flag fixes this problem but generates a warning:
javac -source 1.6 -target 1.6 HelloWorld.java
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning


javac is warning us that we are compiling Java source code according to Java 6 source format but linking it with the Java runtime libraries of Java 7.

This works but may lead to subtle runtime bugs.

To fix the warning:
1. Install a Java 6  JRE.
2. Add the -bootclasspath flag to point to the Java 6 rt.jar from the javac 7 command line:
javac -bootclasspath <JRE 1.6
1
 
LVL 5

Expert Comment

by:Plk_In_EE
Comment Utility
very good. thanks
0
Introduction
Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java Virtual Machine) can recognize the symbols exported by the native program. It defines how functions are to be named. Also it defines how to pass different types of data variable between the native code and Java code.

We had to implement RFID in one of our Java application. According to the application demand we choose to use network based RFID scanners. The manufacturer of the scanner supplied us with C++ SDK along with the scanner. Since the SDK is for C++ we wrote a JNI to integrate it with our application.

The Setback
The JNI is written with four functions, Connect_Scanner, Read_RFID, Clear_Buff and Disconnect_Scanner.

Connect_Scanner: This is to connect to the scanner and expects the IP address and Port number from the Java code. On success or failure of the connection this function returns a status code accordingly.

Read_RFID: On a successful connection the Java code spawns a new thread and calls this function in a continuous loop. Internally the C++ code calls a API function provided by the SDK. One of the parameter of the function was a type struct array. When the API function returns the struct array contains all the RFIDs scanned.

Clear_Buff: So that the same RFID is …
0
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application.

For the purposes of this article, I will be using NetBeans 6.9. If you want to follow along with this tutorial, open NetBeans and create a new "Java Application" called something like "ExcelCreator".
If you don't have NetBeans you can get it here: http://netbeans.org/downloads/index.html. Make sure you get the Java bundle:
NetBeans Java Bundle
What we're going to do is create a simple Java Application to create a spreadsheet. We're going to have a text box, an "Add" button, a JList, and an "Export to Excel" button. When the "Add" button is pressed, the inputted text will be added to the JList. When the "Export to Excel" button is pressed, the application with take the values in the JList and create an Excel Spreadsheet with those values in the "B" column and a counter variable in the "A" column. For example sake, we'll also center the values in the cells. So if there are the following 5 values in the JList ('item a', 'item b', 'item c', 'item d', 'item e') the Excel Spreadsheet will look like this:
Example Spreadsheet
Once you have created a new "Java Application", create a new JFrame Form called "GUI" in the <default package> under "Source Packages". Add the text box, JList, and two buttons to you form to make it look like this:
GUI Example
Be sure …
6
On Demand Webinar - Networking for the Cloud Era
LVL 9
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench.


Introduction

While learning Java can be done with a simple text editor like gedit or notepad, occasionally the use of an Integrated Development Environment (IDE) is desired.  Eclipse is one such IDE that is used by a fair amount of developers given it is open source, providing a free tool, coupled with the fact that it has origins from IBM's commercial package, WebSphere Studio Application Developer, which adds power amplified by the community additions since its inception.

With all that said, the premise of this article is that we have an existing Java project that must now be developed further within Eclipse.  Therefore, to get the most benefit, Eclipse (screen shots and instructions shown from version 3.5.x or "Galileo") should be installed as well as a JDK.  We will also need a simple project to work with, but we will create one shortly.


Simple Project

1. Create a folder in a temporary directory of your choice and name it "TestProject".  
2. Open the TestProject folder and create a sub directory called "src".
3. Open the newly created src directory and create a sub directory called "testpackage".
4. Open the testpackage folder and create a text file named "TestClass.java" with the following content:
package testpackage;

public class TestClass {
	
}

Open in new window


6
 
LVL 60

Author Comment

by:Kevin Cross
Comment Utility
Glad to hear it.  Thank you for reading and, further, taking the time to post nice words and vote!
It makes it worthwhile to know something I have written was helpful to others.

Kevin
0
 
LVL 7

Expert Comment

by:gudii9
Comment Utility
why we need to select ' java project from ant build option'. I usually import directly 'import from

file-->import-->existing project into workspace--> select one of two radio buttons like 'select root directory' or 'select archive file'
0
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed.

------------------------- Start

The idea here is to target your cell phones with
the correct certificate. Some phones have VeriSign Class 3,
some have just VeriSign....,

The point is just because it says VeriSign, doesn't mean your
VeriSign Class 3 certificate that accompanies your J2ME application
will work.




A .csr file is an ASCII file
csr = Certificate Signing Request

A .ks file is a binary file
ks = keystore

You can use the JAVA JDK keytool or the JAVA ME 3.0 tool mekeytool



1. Create a keystore

To generate a public/private key pair, enter the following command,
specifying a name for your keystore and an alias as well

keytool -genkey -keyalg rsa -keystore XXXX.ks -alias <alias_name>

Answer all of the questions, write them down or take a snapshot.

You will use the XXXX.ks file later when VeriSign sends back your
Class 3 CSR



2. Generate a Certificate Signing Request

keytool –certreq –file certreq.csr –keystore XXXX.ks -alias <alias_name>

File certreq.csr looks something like this:
-----BEGIN NEW CERTIFICATE REQUEST-----
MIIBtzCCASACAQAwdzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFzAVBgNVBAcT
............
............
............
-----END NEW CERTIFICATE REQUEST-----

3. Fill out the enrollment form with VeriSign

Paste the contents of the CSR file …
0
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula with the ease of syntax and simplicity of C. However, with the rise of internet and lack of support of cross platform applications, the world would see another revolution in the world of programming.

Java was conceived by James Gosling, Patrick Naughton and others at Sun Microsystems, Inc. in 1991. Initially called Oak, this language was renamed Java in 1995. Java saw additional inputs from many people through its journey including some well known computer visionaries like Bill Joy (of C Shell and the VI Editor fame)

What made Java special was that most of the languages then were compiled natively. Hence, software on one platform did not run on any other platform. This made developing of software difficult for developers as separate version of the same application had to be written for different platforms. This problem caught Gosling's imagination and he began work on a portable, platform independent language.

About the same time, the second factor that played an important role in emergence of Java was rising. The WWW. Back then, the personal computer world had been divided into three parts: the Windows, the UNIX based, the Macintosh. Most programmers created applications for just one of the three entities. Thus the …
3
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues understanding some of the code that is written nowadays.  And one of the new features of Java 7 seems to be adding even more to the confusion.

Java 5: Generics


When Sun announced their plans to include the Generics in Java 5, a lot of the developers were not exactly happy, even though they were not a foreign concept for most of the people that had started with other languages before the creation of Java. This change added a lot of complexity to the language.  But they were part of the evolution of Java, so most developers accepted them, and found good usage for them (is there anyone missing the casting or conversion that was needed every time when an object had to be retrieved from a collection?).  But, at the same time, expressions like
<T extends Object & Comparable<? super T>> T Collections.max(Collection<? extends T>) { ... }

Open in new window


prove that even if Generics are generally a great idea and can be quite useful, they also open the door for a lot of issues. And that's not even close to the most complicated expressions that can be done. Most of the experienced Java developers can understand this line but that does not make it readable or easy to understand.

Java 6: The calm times


After the …
13
 
LVL 20

Author Comment

by:Venabili
Comment Utility
Actually they did Generics badly (or better to say - they left way too many options open very fast)... and as it looks like won't clean them. Yes, there are great things there that I love but thefull thing just leads to confusions...

Hopefully the Closures (yes, these ones plus some additions although almost all of them were removed from the initial versions - they had been discussed for way too many years and I really do not see a reason to have them in Java - I know the concept, I use it in other languages but in Java? ) will be a bit better implemented. But not holding my breath really.

I believe that C++ is also at the same stage as Java - they are working on a proposal for integrating these into the language. I do not think that they had closed the syntax either so let's see which language will make them stranger? :)
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
Yeah, C++03 is still in the ratification stage. It's possible -- but unlikely -- these things may get dropped still. They dropped support for "concepts" at the last moment, which was a huge disappointment to people like me who do a lot of meta-template programming.

Anyway, thanks for your thoughts and feedback Venabili, it's a hugely interesting article and I enjoyed reading it.
0
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects.

Interface Comparable is used to allow objects of a class that implements the interface to be compared to one another. The interface contains one method, compareTo, that compares the object that calls the method to the object passed as an argument to the method.

For example, when using Collections.sort(List) with a List containing objects of a user-defined class A, then this class must implement the Comparable interface's method compareTo() to specify which property of the object will be used for comparisons/sorting.

Otherwise, a ClassCastException will be thrown because Java tries to cast the objects to a Comparable.
 
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)

Open in new window


Note: The pre-defined classes like String, Integer, etc. already implement the interface Comparable, so any list containing objects of these classes do not throw a ClassCastException.

For comparing objects of a user-defined class, which does not implement Comparable and which you cannot edit (e.g., because you do not have source code or its a class file in a jar library), we can use a custom class implementing the interface Comparator that similar to Comparable has one method, compare, that takes both the object being compared and the object being compared to as arguments.

Java API reference:

Open in new window

4
Java has always been considered a multi-platform language - you write your code once and then you use it on almost any Operating System. Unfortunately for most Java developers, this is often taken quite literally from anyone that had no knowledge of the language, including some managers and system admins.

If you had ever seen any Java code that deals with files and directories, you already know that if the programmer is not careful, the otherwise multi-platform code will simply fail when the OS is changed. But what happens if you are careful (you use File.separator instead of hardcoded "/" and "\\", you don't presume that every file path will have a ":" in it and so on)? You should not worry that moving the code from Windows to Unix will break it, right?

Well, that's where the bad news start - technically your code might work (if the Unix admins make sure that all the input files have correct ownership and permissions) but it may turn out that the next application that should use your output files as input or the user that tries to download them via FTP cannot even read them while the same application and/or user on Windows had never had these issues. The reason for this is the different ways in which the file permissions and ownership work in Unix. The obvious solution is just to make sure that your code is properly setting the permissions if it is run in a Unix environment, so you open the java.io.File documentation to search for some methods to accomplish …
9
 

Expert Comment

by:yodmeenakshi
Comment Utility
Nice one. very helpful.
0
 

Expert Comment

by:KanJark
Comment Utility
Thanks. That is very helpful
0

Java

98K

Solutions

32K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.