Monday, February 6, 2012

Understand The Java Classpath

This article is about a small simple collection of batch files which can be used to test the behavior of the javac compiler and java class launcher for different classpath scenarios. The system is called ClasspathTester. Download instructions are included at the end of this article.

When you are in the middle of trying to debug a java build it is a bad time to try to boil everything down to a simple test case, so basically the intent of my test collection is to do this for you ahead of time. If you can't find the precise test you need, it is easy to modify the existing tests or create a new test to suit your needs.

How ClasspathTester Works

As previously stated, I did everything with batch files, because I wanted the tests to be as uncomplicated, portable (within the Windows environment), and simple as possible. There are a few helper batch files to do things like create formatted output and build a directory structure, but otherwise nearly all of the work is done in the RunAllTests.bat file.

What RunAllTests.bat consists of is tests and sub-tests. If you haven't downloaded it yet, I suggest you download it and take a look. Each test consists of some sort of a setup. Setup normally involves the following:

1. Test environment is cleaned up of old directories, files, and classpath.

2. New directory structure is created, new files are created and placed in correct directories, and the classpath is set if necessary.

After setup, the tests are run. This consists of running either the javac.exe compiler, the java.exe launcher, or both. That's all there is to it.

A Simple Example

To understand what ClasspathTester, does, open the RunAllTests.bat file in your text editor and look at TEST1. Each test is a collection of sub-tests which are loosely grouped around some kind of a central testing theme, and TEST1 is one of the simplest.

So what happens in Test1? First it calls banner.bat to add a header to the results file. Then it creates the Hello.java and MyLibClass.java files, by copying them from their corresponding avaj files (the reason for using avaj files is discussed later in this article). Now everything is set up to run some subtests.

TEST1A is very simple. According to its description, " The Hello.java file is located in the current directory, and the Hello.class file will be written to the current directory and run from the current directory". As you can imagine, TEST1A operates flawlessly.

TEST1B and TEST1C are designed to show different ways that using java.exe to launch the Hello.class file can fail. In TEST1B the classpath is been set to an empty directory. In TEST1C the file Hello.class is erased. Interestingly, these two tests fail in exactly the same way.

Note that all tests results are stored in the results.log file.

How the Tests are Kept Safe

By "safe" I mean safe to your computer, safe to your other data. Since the tests involve batch files that are creating and destroying files and directories, care must be taken to avoid accidentally destroying or writing over other unrelated files. This is accomplished in the cleanup.bat file by avoiding the use of statements like "erase /S *.*" or "rmdir /S *". Instead, all erasures are kept fairly specific.

In fact, the cleanup.bat file consists of the following statements:

set classpath=

rmdir /S /Q aq

rmdir /S /Q EmptyDirectory

erase Hello*.java

erase Hello*.class

erase MyLibClass*.java

erase MyLibClass*.class

This ensures that there will be no tragic accidental loss of unrelated data.

Why Use .avaj Suffix Files

Part of the operation of ClasspathTester involves completely wiping the base directory clean of all .java files, .class files, and subdirectories; therefore, all the suffix of all permanent java files is mangled to avaj. For any test, the appropriate avaj files are copied to java files. The available files are:

Hello.avaj

Hello1.avaj

Hello2.avaj

MyLibClass.avaj

MyLibClass1.avaj

MyLibClass2.avaj

Download Information

You can find and download a zipped copy of the ClasspathTester can be on my Article Support Page

Summary

ClasspathTester is simple, portable, unobtrusive, customizable and solves an annoying development problem, the need to quickly test special classpath situations with javac.exe, java.exe, or both.

Article Source: http://EzineArticles.com/505451

Monday, January 23, 2012

Difference Between Java and WordPress

ava and WordPress are very much different, this is an attempt to compare and see where they intersect each other.

Java

Java is an enterprise Language, what it means it is used to build enterprise applications, what do we mean by that?

· A variety of clients can interact with applications like browsers, smart tablets, B2B applications, .NET and other language apps.

· High Security to support the standards.

· Highly Scalable to support the growing traffic.

· Performance - Begin compile time performance is high.

· E.g applications are Gaming, ECommerce websites, Billing, Retail, CRM and tons of others

Earn Cash by using your WordPress


Java can be used to create blogging CMS like WordPress. There are CMS's like alfresco, Plone, JRoller whodo to attempt to that, but none has been able so popular as WordPress.

WordPress

Very specialized CMS/blogging engine build on top of PHP.

· It is very easy to learn software, compare it to learning MS Word.

· You don't need to know PHP/programming to be WordPress website developer.

· It has a themes concept, which allows a developer to configure website pages with easy.

· Supports thousands of plugins, almost easy to find any kind of functionality a website needs.

· Installs on Apache Server with PHP engine.

· Many hosting sites support 1 click install.

· Uses MySQL as the backend engine.

As you see, WordPress and Java cannot be compared as one is a language where another is a software built on PHP language.


Buy Blog Posts and Reviews for your Website with Posts Genius

Had WordPress been written in Java

As a Java Developer, I do wish WordPress was built on Java, it would have given

1. Java applications a web flair, we would have to see all together new set of applications /widgets/ plugins.

2. Designers would have not been scared of the language at all.

3. Applications could have used the WordPress database, which has a very simple schema.

WordPress And Java Together

Resin Quercus

Resin is a Java Application server, but with a twist, it has a Quercus engine which allow PHP applications to installed as Java applications.

What does this mean, if a WordPress can be installed on Resin will run as a Java application and also take advantage of libraries like Spring, Hibernate,SOA.

Also, will definitely perform way better as it will be compiled only once and not be interpreted with every request like it does now

To have this integration working has its own challenges but good news is there is a way.

Summary

While WordPress has it own niche, creating CMS websites with blog functionality, it is the DeFacto Platform.

But when it comes to creating highly scalable enterprise Applications Java is the DeFacto Platform.

Makarand Bhatamrekar is a enterprise Java RIA Career Coach. He has been coaching since 2007 on Java technologies to help trainees achieve their java career goals. http://careerInJava.com is a dedicated the effort to give all the resources needed to succeed.
To be informed of the latest update, do subscribe the Newsletter at http://www.careerInJava.com

WordPress is the easiest CMS out here, which allows to create your website with no knowledge of PHP. Makarand was able to develop coaching website on WordPress with no prior knowledge of the same, hence this post comparing the two.

Article Source: http://EzineArticles.com/6811651

utvecklare intranet

Wednesday, July 20, 2011

Why Java RDBMS?

It is a well known fact that Java as a programming language set off a new paradigm in the software industry. Suddenly, every software programmer worth his salt was amidst software jargons like 'Platform-Independence', 'Cross-Platform-Deployment' and 'The Java Virtual Machine'. In fact, it did not take long for Java to usurp the 'most sought after status' from many software languages, and become the most preferred tool for creating software; especially software for the web. As the recent trends in the industry show, Java is set to achieve an undeniable position as the most preferred software programming language for a long time to come. It is indeed Java's credit that many prominent vendors who tried to emulate the capacities of Java, failed miserably in the endeavor.

The importance of Java in the software scenario has led to another major trend. Software vendors are either rewriting their existing products in Java, or are creating new products exclusively or partially in Java. This has led many analysts to question the need to port already existing applications to Java. While the prospects of porting small or medium sized software to Java may not attract concern, it assumes significance when we consider porting existing databases that could be handling millions of sensitive blocks of information. Similarly, experts also have to decide between deploying reputed databases, and new databases that have been entirely developed in Java, in their organizations. Analysts have to answer many pertinent questions like: What are the advantages of a Java RDBMS that would compel my company to switch to it? Would it be cost effective to change to an RDBMS that has all the advantages of Java? Would the costs involved in porting millions of existing records justify the perceived performance and scalability features of the Java RDBMS? How secure would be the new RDBMS? What is the learning curve that has to be tackled by the staff who may be assigned to this database? In fact, there are a host of questions that a concerned technical head may ask himself before taking that all important decision to switch to a Java RDBMS. Let's try finding out some of the answers.

What are the advantages of a Java RDBMS?

OK, so we all know that Java is set to capture, or has already captured a sizeable chunk of the software market. However, how does that justify the use of a Java Database? After all, is not Java theoretically capable of integrating with any database? What advantages can be afforded by a Java RDBMS?

Well the answer is quite simple. Java RDBMS has, or supports, the much sought after qualities of Java, which is the most important reason to switch to it. Some of the Java RDBMS already available in the markets answers the immediate concerns of the Technical Lead in the most persuasive manner. For example, Daffodil DB, an RDBMS written in Java, considers the following as its core strengths:

Multiple Platform Portability

Small Size

Java Stored Procedures

Transparent to End User

Zero Administration Efforts

Some of these features are worth a second look.

One RDBMS, multiple avatars

Java RDBMS not only offers the advantages of Java, but also introduces new concepts that can revolutionize database programming techniques. For a start, the much famed portability of Java is the core strength of a Java RDBMS. Now, you don't have to buy different RDBMS for different platforms within the same enterprise. Other than the cost factors, the biggest advantage such an arrangement can give is that in-house code need not be redesigned for different platforms. By standardizing the database that is used, programs working across platforms can interact transparently and effectively. Project managers would vouch that portability, synchronization and customization effort for software running on different platforms are some of the most time consuming and tension filled activities in the office. Now all these activities can be easily implemented with the Java RDBMS in its rightful place.

Store and use those procedures with abandon

Security buffs within the enterprise would always throw a tantrum when dealing with stored procedures. Traditionally, the implementation of stored procedures had been the responsibility of the specific application vendor, and most of them could crash the whole database due to internal errors, rendering precious time and money waste. Java stored procedures with its inbuilt security features is the new fad of security administrators who are finding it powerful, fast, and very safe. Java does not implement Pointers, and so is a safe bet for developers to write secure code and procedures. In addition, with the JVM overlooking all the activities (the sandbox approach), there is no scope for external access that could jeopardize mission critical enterprise applications.

Transparent to End User

Java technologies have always been in the forefront to give us seamless transparent applications with inbuilt security features being given the utmost importance. In a Java RDBMS, database components can be embedded in applications, and they can perform complex tasks without user intervention. In addition, the user need not know the complexities of the database because the embedded database components will do all the work for him without him even knowing about it. This allows the user to concentrate on his tasks rather than configuring databases, which is an auxiliary requirement. In addition, other routine activities like starting the server and repetitive configuring of the database can also be avoided. Perhaps the biggest advantage that Java RDBMS offers is that the user need not weigh the pros and cons about choosing a database vendor. This is because Java RDBMS being extremely portable can seamlessly integrate with almost all platforms, and the embedded components will handle all the chores of integrating with different vendor software. Java RDBMS can also be seamlessly operated across multiple platforms without the need to configure the database for each and every operating system.

Zero Administration Efforts


Java RDBMS comes in with zero administration efforts, which means that once installed and configured, your clients need not change their settings to suit new changes that you make in your database. Java RDBMS also does away with, or considerably reduces, the role of the Database Administrator because of its self-managed features, and its extremely scalable mode of operation.

If you have not thought of it yet, it is a good time to think about Java RDBMS. The time is not far away when the databases industry will be greatly influenced by the power and functionality of Java RDBMS.


Article Source: http://EzineArticles.com/3103
Diamond Engagement Ring : Womens & Mens Diamond Watches & Diamond Jewelry Sale up to 82% Off: Diamond watches, diamonds, womens and mens diamond jewelry at NYCs #1 Diamond Jewelry Store.
Buy Digital Cameras Online : Digital Cameras have simplified the process of taking high quality pictures. Today, practically all cameras are digital which allow maximum photo taking efficiency. These cameras have built-in computers and all of them record images electronically.
Swarovski 5810 : original Swarovski Crystallized TM Elements Made in Austria, swarovski 2028 xilion rose, rhinestones, swaroski, svaroski, strass, swarovski strass, swarovski stones
weight loss supplements : Want no more diets. Looking for fast weight loss pills or diet pills? We are the most trusted diet pill review site. Visit #1 ranked diet pill now!
K2 Trophies and Awards : Trophies & Trophy: Looking for lowest price trophies, awards, medals or plaques? Visit K2 Trophies and Awards. We have the right trophy, plaque or award for any sport or occasion. FAST FREE shipping on orders over $200. High quality but cheap price.
Self managed super Bankstown : We have experienced Small Business Company Accountants across Liverpool, Moorebank, Ingleburn, Campbelltown, Bankstown, Wetherill and Fairfield having in depth understanding of each industry’s areas of risk and opportunity.
Travertine floor tiles Travertine Marble Kitchen Tiles - Marble Kitchen Tiles and Travertine Kitchen Tiles at great prices from StoneSuperStore. Visit today or call for expert advice on Kitchen Tiles.
masterbatchesREPIN is #1 Masterbatch Industry among various Masterbatch Manufacturers & supplier, providing services worldwide. Get Clariant Masterbatch and more from REPIN. welding projects TIG, MIG, STICK, Plasma Cutting, Welding Advice, Welding Forum, Tips, Tricks, Learn How To Weld for Professionals and Enthusiasts penny stocks Peter Leeds and his Team Use Leeds Analysis to Uncover the Absolute Best Penny Stock Picks and Top Penny Stock Picks. Visit Penny Stocks Now Wohl Associates At Wohl Associates We purchase an individual machine or a complete a line or even a complete facility, including real estate. Life Insurance Quote Lifebroker provides free life insurance & income protection quotes that allow you to compare 20 different life insurance companies in once place. We are the broker of choice across the United Kingdom for all your personal life, critical illness, disablement and income protection needs. fence panelsFence Stores is one of the South’s largest manufacturers and suppliers of Fencing, Fencing Panel, Fence Panels, Industrial Fencing and Garden Buildings such as Summerhouses, Sheds and Cabins serving Devon, Somerset, Hampshire and Dorset. Melbourne accommodation deals Melbourne accommodation deals, news and updates from City Edge accommodation Apartment and Hotels. We offer the best accommodation deals in Melbourne. Debbie Dogrul Associatesleading no VA real estate team in Virginia. The best Northern VA realtors to aid you in your Northern Virginia house for sale or purchase. Letting AgentLetting agents are individuals who deal with rental property on a landlord’s behalf in exchange for fees. They can provide a whole range of services depending on your requirements. Unlike many Lettings Agents there are no hidden fees when dealing Greenaway Residential Letting Agents and we only get paid when our clients get paid. Personal injury ProtectionLeading Law Firm & Attorney Brad Sinclair Represents Personal Injury, Car Accident & Motorcycle Accident Victims in Melbourne, Palm Bay, Cocoa Beach, Titusville, Rockledge, Merritt Island, Cape Canaveral, Cocoa and Brevard County. commercial plumber Wet Basement Repair Meet Wet Basement Waterproofing Expert can resolve home issue like Leaky Basement and many more. Visit www.dxbasementwaterproofing.com for Wet Basement Repair. window coverings new york marine paint protectionTRIBOS, the leading international supplier of protective paint coatings for the automotive, marine and aviation market has now gained a strong foothold in the Southeast Asia. Whistler Mountain Transportation Whistler Mountain Transportation specializes in providing luxurious, chauffeured transportation to Whistler Blackcomb from either Vancouver or Seattle. junk removal in San DiegoLooking for water heater removal in San Diego? We are a full-service water heater removal and hauling services based in San Diego. Call Junkeez for a free estimate today! hotels in Stellenbosch - Find the best accommodation in Stellenbosch and hotels in Stellenbosch with Majeka Guest House. Chicago limo serviceAny Time Limo Chicago Provide Top Quality Limo & Limousine Services in Chicago and Suburban Area at Reasonable Rates. To Book Limousine in Chicago Call Us (773) 353-8024) Or Visit Us! San Diego Advertising San Diego solar power will benefit home-owners who consume more electricity than average users. They pay high income taxes and they can benefit a lot from tax credits. San Diego Solar PanelThe Restaurants in San Diego are famous for serving the world’s best beer. The bars offer a glamorous as well as erotic atmosphere to their customers. charter bus service in San FranciscoWe provide charter bus service in San Francisco at affordable prices with complete client satisfaction. homes for sale in Santa Ana Search Luxury Homes for Sale in Orange County through homesalesinorangecounty.com. Our listing Updated daily with latest Listing on homes/houses for sale in Orange County. Contact us today! Vancouver airport limo serviceisGet special deal on booking of vancouver airport ground transportation to whistler with details of all cheap Vancouver Airport Limo Service by prime time limo services. washer dryer house lightingLED world is an online electrical wholesaler in Australia which offers led flood lights and led strip light at affordable prices. restaurant in Cape Town Whistler limousine service Limousine is considered as the most luxurious transportation among all and it is like a dream come true for anyone getting a chance to travel in it. Whether it is a wedding occasion or graduation prom or any corporate meeting, people expect to enjoy a luxurious ride and arrive in style. Time and Gems
lawyer philadelphiaL & M Law, LLC provides attorneys in Philadelphia who can handle trusts and estates law by taking out the uncertainty of estate planning. Universal life insurance House Cleaning Downingtown PA provide services of trash removal in Montgomery County atlantic city clubs asphalt paving burlington county nj Trophies New Jersey

Monday, January 24, 2011

BASIC CONCEPTS OF JAVA

Now that already we have seen large characteristics what Java can offer us, and before entering to bag in the generation of our first code Java, we are going to glance over the language Java in itself. The basic thing relative to the ones will result very that have know-how of C/C+ +. The programmers with experience in other languages procedurales will recognize most of the constructions. We expect that this chapter result not too intense, nevertheless, yes should been present, because more than one time we will resort to him as reference. In subsequent chapters we will deepen on aspects of the programming in Java by the ones that here we will pass on tiptoe and we will go presenting examples of code of each one of those aspects of the programming in Java.

If really it wants to dominate Java, is not sufficient to know the code. You should begin to think as a programmer, and in this new edition of his guide of best-seller, Java Concepts, programming Cay Horstmann guru shows him how. It brought up to date to integrate Java 6, Concepts of Java, fifth edition is an introduction to the techniques of fundamental programming and the abilities of design that are crucial to learn to plan. Basing on its many years of experience as expert programmer and professor, Horstmann shows the most important elements of the data processing, troubleshooting and the design of the program. Thanks to the formula tested Horstmann, you will be able to complete this book with a solid base in the concepts of programming and troubleshooting and to arrive quickly to the velocity to write program efficient and successful. You Can find the Best Java Knowledge Concepts here exclusive on javaequation.blogspot.com

Characteristics of the fifth new edition: * The focus "gradual Objects" conducts you to step oriented to objects thinking to step, the use of classes, the application of simple methods, until coming to design its own programs oriented to objects. * A strong emphasis in the development based on tests invites to consider the results as is written the code of programming so that a better design, that can be utilized more you program * unique Focus goes beyond the syntax of the language to be concentrate on concepts of data processing and troubleshooting, that encourage to think like a solucionador of problems * New and learning teaching tools in WileyPLUS -
including a corrector of unique allocation that will permit you to put to test your problems of programming in line before submitting them to a degree * Useful "the tests in trail" he introduces the techniques and tools step by step, what guarantees a teacher before passing to the following one * The graphics are themes developed gradually along the text, conveniently noticeable in different sections by color * The cover of updating is completely compatible with Java 5 and includes a discussion of the last characteristics of Java 6.

computer courses london : Ethames graduate school is a leader in computer courses London. This school of computing has the world's best faculty and teaching material.

SEO In Miami- How to Increase Your Site's Traffic Offers CD Duplication and CD Replication to Save Your Data iDEA Media Services’ duplication department can duplicate one CD at a time, or one thousand CD's on demand, so that you can have your finished product in your hands in just a few days. corporate website SEO Company NY Day Trading How to Make a Free Website Rocket Web Design has launched a new design program, making the process of making a free website easier than ever. Currently, Rocket is launching a new program so that customers can share this custom web design system with their families and friends. TheHeadsetShop.com Bournemouth Digital Agency :- Web Design Bournemouth- Gazelle Design is the leading Digital & Design Agency providing the best Web design & website design, SEO Services, Graphic design services in Bournemouth, Dorset, Poole SEO Company :- SEO India Profit By Search™ #1 SEO Company India. Outsourcing Seo Services India Can Improve Your Bottom Line, As SEO Consultants in India are Cheap and can produce much better results when compared to their foreign Counterparts...!! Web Design India :- No matter what your web development and design needs, Profit By Outsourcing India can help. Learn more about our web design and development services. Recruitment Process Outsourcing :- RPO Services @ Profit By RPO- India's #1 Recruitment Process Outsourcing (RPO) Firm. Hire Dedicated Recruiters from Profit By RPO @ $1500/Month, Enquire Now Investment Casting India :- R.K. Engineers is an Investment Casting Company in India offering Precision, Lost Wax Investment Casting Manufacturing Services in India. SEO Company NJ :- 1SEO.com is a premium SEO Company providing effective SEO services in Philadelphia PA and NJ. Call 877-311-7361 today and get proven results for your company.

My Aim Language Java

These annotations of the language Java are the hyphen structured of a course of Introduction to the Language Java. They are not a reference exahustiva of the language but they intend to provide a progressive approximation, leaving from it more elementary and introducing the concepts in an orderly fashion, being supported in the previous thing.

They are structured in the shape of brief lessons, that cover all the aspects of the language in a basic-medium level. Itself they are not assumed know-how of other programming languages, although obviously to be familiarized with concepts relating to the programming as variable, algorithms, objects, etc. facilitates a lot of the task. Nevertheless, the reference has been avoided deliberately or the comparison with other languages, especially with C/C + + that so present is in many texts of Java.

The first part of these annotations covers all the aspects of the language (Classes, Interfaces, inheritance, control of flow, types of data, etc.). The second part, at present in elaboration, treats matters of the API of Java, grouping them for themes (Entrance/Exit, Threads, applets, etc.).

Sunday, July 4, 2010

Access Control

When writing new classes, it’s a good idea to pay attention to the issue of access
control. Recall that making a member of a class public makes it accessible from anywhere, including from other classes. On the other hand, a private member can
only be used in the class where it is defined.
In the opinion of many programmers, almost all member variables should be declared
private. This gives you complete control over what can be done with the
variable. Even if the variable itself is private, you can allow other classes to find out
what its value is by providing a public accessor method that returns the value of
the variable. For example, if your class contains a private member variable, title,
of type String, you can provide a method
public String getTitle() { return title; }
that returns the value of title. By convention, the name of an accessor method for
a variable is obtained by capitalizing the name of variable and adding “get” in front
of the name. So, for the variable title, we get an accessor method named “get” +
“Title”, or getTitle(). Because of this naming convention, accessor methods are
more often referred to as getter methods. A getter method provides “read access” to
a variable.
You might also want to allow “write access” to a private variable. That is, you
might want to make it possible for other classes to specify a new value for the variable.
This is done with a setter method. (If you don’t like simple, Anglo-Saxon
words, you can use the fancier term mutator method.) The name of a setter method
should consist of “set” followed by a capitalized copy of the variable’s name, and it
should have a parameter with the same type as the variable. A setter method for the
variable title could be written
public void setTitle( String newTitle ) { title = newTitle; }
It is actually very common to provide both a getter and a setter method for a
private member variable. Since this allows other classes both to see and to change
the value of the variable, you might wonder why not just make the variable public?
The reason is that getters and setters are not restricted to simply reading and writing
the variable’s value. In fact, they can take any action at all. For example, a getter
method might keep track of the number of times that the variable has been accessed:
public String getTitle() {
titleAccessCount++; / / Increment member v a r i a b l e t i t leAc ces sCount .
return title;
}
and a setter method might check that the value that is being assigned to the variable
is legal:
public void setTitle( String newTitle ) {
if ( newTitle == null ) / / Don ’ t al low n u l l s t r i n g s as t i t l e s !
title = " ( Unt i t led ) "; / / Use an appropr iate d e f a u l t value instead .
else
title = newTitle; }
Even if you can’t think of any extra chores to do in a getter or setter method, you
might change your mind in the future when you redesign and improve your class. If
you’ve used a getter and setter from the beginning, you can make the modification
to your class without affecting any of the classes that use your class. The private
member variable is not part of the public interface of your class; only the public
getter and setter methods are. If you haven’t used get and set from the beginning,
you’ll have to contact everyone who uses your class and tell them, “Sorry guys, you’ll
have to track down every use that you’ve made of this variable and change your code.”

Class Members and Instance Members

A class definition is made of members or components. A class can define variables (or
fields) and methods. Variables and methods can be static or non-static i.e. they are
defined with or without the keyword static.
e.g.
static double lastStudentNumber; / / a s t a t i c member / v a r i a b l e / f i e l d
double studentNumber; / / a non−s t a t i c v a r i a b l e
static void printLastNumber() {...} / / a s t a t i c member /method
void printNumber() {...} / / a non−s t a t i c method
The non-static members of a class (variables and methods) are also known as
instance variables and methods while the non-static members are also known as class
variables and class methods. Each instance of a class (each object) gets its own copy of
all the instance variables defined in the class. When you create an instance of a class,
the system allocates enough memory for the object and all its instance variables.
In addition to instance variables, classes can declare class variables. A class variable
contains information that is shared by all instances (objects) of the class. If one
object changes the variable, it changes for all other objects of that type. e.g. A Student
number generator in a NewStudent class.
You can invoke a class method directly from the class, whereas you must invoke
instance methods on a particular instance. e.g. The methods in the Math class are
static and can be invoked without creating an instance of the Math class for e.g. we
can say Math.sqrt(x).
Consider a simple class whose job is to group together a few static member variables
for example a class could be used to store information about the person who is
using the program:
class UserData { static String name; static int age; }
In programs that use this class, there is one copy each of the variables UserData.name
and UserData.age. There can only be one “user,” since we only have memory space
to store data about one user. The class, UserData, and the variables it contains exist
as long as the program runs. Now, consider a similar class that includes non-static
variables:
class PlayerData { String name; int age; }
In this case, there is no such variable as PlayerData.name or PlayerData.age,
since name and age are not static members of PlayerData. There is nothing much in the class except the potential to create objects. But, it’s a lot of potential, since
it can be used to create any number of objects! Each object will have its own variables
called name and age. There can be many “players” because we can make new
objects to represent new players on demand. A program might use this class to store
information about multiple players in a game. Each player has a name and an age.
When a player joins the game, a new PlayerData object can be created to represent
that player. If a player leaves the game, the PlayerData object that represents that
player can be destroyed. A system of objects in the program is being used to dynamically
model what is happening in the game. You can’t do this with “static” variables!
An object that belongs to a class is said to be an instance of that class and the
variables that the object contains are called instance variables. The methods that
the object contains are called instance methods.
For example, if the PlayerData class, is used to create an object, then that object
is an instance of the PlayerData class, and name and age are instance variables in the
object. It is important to remember that the class of an object determines the types
of the instance variables; however, the actual data is contained inside the individual
objects, not the class. Thus, each object has its own set of data.
The source code for methods are defined in the class yet it’s better to think of the
instance methods as belonging to the object, not to the class. The non-static methods
in the class merely specify the instance methods that every object created from the
class will contain. For example a draw() method in two different objects do the same
thing in the sense that they both draw something. But there is a real difference
between the two methods—the things that they draw can be different. You might
say that the method definition in the class specifies what type of behavior the objects
will have, but the specific behavior can vary from object to object, depending on the
values of their instance variables.
The static and the non-static portions of a class are very different things and serve
very different purposes. Many classes contain only static members, or only non-static.
However, it is possible to mix static and non-static members in a single class. The
“static” definitions in the source code specify the things that are part of the class itself,
whereas the non-static definitions in the source code specify things that will become
part of every instance object that is created from the class. Static member variables
and static member methods in a class are sometimes called class variables and
class methods, since they belong to the class itself, rather than to instances of that
class.
So far, we’ve been talking mostly in generalities. Let’s now look at a specific
example to see how classes and objects work. Consider this extremely simplified
version of a Student class, which could be used to store information about students
taking a course:
public class Student {
public String name; / / Student ’ s name . p u b l i c double test1 ,
test2, test3; / / Grades on three t e s t s .
public double getAverage() { / / compute average t e s t grade r e t u r n
(test1 + test2 + test3) / 3; }
} / / end of class Student
None of the members of this class are declared to be static, so the class exists
only for creating objects. This class definition says that any object that is an instance of the Student class will include instance variables named name, test1, test2, and
test3, and it will include an instance method named getAverage(). The names
and tests in different objects will generally have different values. When called for
a particular student, the method getAverage() will compute an average using that
student’s test grades. Different students can have different averages. (Again, this is
what it means to say that an instance method belongs to an individual object, not to
the class.)
In JAVA, a class is a type, similar to the built-in types such as int and boolean.
So, a class name can be used to specify the type of a variable in a declaration statement,
the type of a formal parameter, or the return type of a method. For example, a
program could define a variable named std of type Student with the statement
Student std;
However, declaring a variable does not create an object! This is an important
point, which is related to this Very Important Fact:
In JAVA, no variable can ever hold an object. A variable can only hold a
reference to an object.
You should think of objects as floating around independently in the computer’s
memory. In fact, there is a special portion of memory called the heap where objects
live. Instead of holding an object itself, a variable holds the information necessary
to find the object in memory. This information is called a reference or pointer to the
object. In effect, a reference to an object is the address of the memory location where
the object is stored. When you use a variable of class type, the computer uses the
reference in the variable to find the actual object.
In a program, objects are created using an operator called new, which creates an
object and returns a reference to that object. For example, assuming that std is a
variable of type Student, declared as above, the assignment statement
std = new Student();
would create a new object which is an instance of the class Student, and it would
store a reference to that object in the variable std. The value of the variable is a
reference to the object, not the object itself. It is not quite true to say that the object
is the “value of the variable std”. It is certainly not at all true to say that the object
is “stored in the variable std.” The proper terminology is that “the variable std refers
to the object,”.
So, suppose that the variable std refers to an object belonging to the class Student.
That object has instance variables name, test1, test2, and test3. These instance
variables can be referred to as std.name, std.test1, std.test2, and std.test3.
This follows the usual naming convention that when B is part of A, then the full name
of B is A.B. For example, a program might include the lines
System.out.println(" Hello , " + std.name + " . Your tes t grades are : ");
System.out.println(std.test1);
System.out.println(std.test2);
System.out.println(std.test3);
This would output the name and test grades from the object to which std refers.
Similarly, std can be used to call the getAverage() instance method in the object by
saying std.getAverage(). To print out the student’s average, you could say:
System.out.println( " Your average i s " + std.getAverage() );
More generally, you could use std.name any place where a variable of type String
is legal. You can use it in expressions. You can assign a value to it. You can pass it
as a parameter to method. You can even use it to call methods from the String class.
For example, std.name.length() is the number of characters in the student’s name.
It is possible for a variable like std, whose type is given by a class, to refer to no
object at all. We say in this case that std holds a null reference. The null reference
is written in JAVA as “null”. You can store a null reference in the variable std by
saying “std = null;” and you could test whether the value of “std” is null by testing
“if (std == null) . . .”.
If the value of a variable is null, then it is, of course, illegal to refer to instance
variables or instance methods through that variable–since there is no object, and
hence no instance variables to refer to. For example, if the value of the variable st is
null, then it would be illegal to refer to std.test1. If your program attempts to use a
null reference illegally like this, the result is an error called a null pointer exception.
Let’s look at a sequence of statements that work with objects:
Student std, std1, / / Declare four v a r i a b l e s of
std2, std3; / / type Student .
std = new Student(); / / Create a new objec t belonging
/ / to the class Student , and
/ / s tore a reference to t h a t
/ / objec t i n the v a r i a b l e std .
std1 = new Student(); / / Create a second Student objec t
/ / and s tore a reference to
/ / i t i n the v a r i a b l e std1 .
std2 = std1; / / Copy the reference value i n std1
/ / i n t o the v a r i a b l e std2 .
std3 = null; / / Store a n u l l reference i n the
/ / v a r i a b l e std3 .
std.name = " John Smith "; / / Set values of some instance v a r i a b l e s .
std1.name = "Mary Jones ";
/ / ( Other instance v a r i a b l e s have d e f a u l t
/ / i n i t i a l values of zero . )
After the computer executes these statements, the situation in the computer’s
memory looks like this:
This picture shows variables as little boxes, labeled with the names of the variables.
Objects are shown as boxes with round corners. When a variable contains a
reference to an object, the value of that variable is shown as an arrow pointing to the
object. The variable std3, with a value of null, doesn’t point anywhere. The arrows
from std1 and std2 both point to the same object. This illustrates a Very Important
Point:
When one object variable is assigned to another, only a reference is copied.
The object referred to is not copied.
When the assignment “std2 = std1;” was executed, no new object was created.
Instead, std2 was set to refer to the very same object that std1 refers to. This has
some consequences that might be surprising. For example, std1.name and std2.name
are two different names for the same variable, namely the instance variable in the
object that both std1 and std2 refer to. After the string “Mary Jones” is assigned to
the variable std1.name, it is also be true that the value of std2.name is “Mary Jones”.
There is a potential for a lot of confusion here, but you can help protect yourself from
it if you keep telling yourself, “The object is not in the variable. The variable just
holds a pointer to the object.”
You can test objects for equality and inequality using the operators == and !=,
but here again, the semantics are different from what you are used to. The test
“if (std1 == std2)”, tests whether the values stored in std1 and std2 are the
same. But the values are references to objects, not objects. So, you are testing
whether std1 and std2 refer to the same object, that is, whether they point to the
same location in memory. This is fine, if its what you want to do. But sometimes,
what you want to check is whether the instance variables in the objects have the
same values. To do that, you would need to ask whether
std1.test1 == std2.test1 && std1.test2 == std2.test2 && std1.test3
== std2.test3 && std1.name.equals(std2.name)}
I’ve remarked previously that Strings are objects, and I’ve shown the strings
“Mary Jones” and “John Smith” as objects in the above illustration. A variable of type String can only hold a reference to a string, not the string itself. It could also
hold the value null, meaning that it does not refer to any string at all. This explains
why using the == operator to test strings for equality is not a good idea.
The fact that variables hold references to objects, not objects themselves, has a
couple of other consequences that you should be aware of. They follow logically, if
you just keep in mind the basic fact that the object is not stored in the variable. The
object is somewhere else; the variable points to it.
Suppose that a variable that refers to an object is declared to be final. This
means that the value stored in the variable can never be changed, once the variable
has been initialized. The value stored in the variable is a reference to the object. So
the variable will continue to refer to the same object as long as the variable exists.
However, this does not prevent the data in the object from changing. The variable
is final, not the object. It’s perfectly legal to say
final Student stu = new Student();
stu.name = " John Doe"; / / Change data i n the objec t ;
/ / The value stored i n stu i s not changed !
/ / I t s t i l l r e f e r s to the same objec t .
Next, suppose that obj is a variable that refers to an object. Let’s consider what
happens when obj is passed as an actual parameter to a method. The value of obj
is assigned to a formal parameter in the method, and the method is executed. The
method has no power to change the value stored in the variable, obj. It only has a
copy of that value. However, that value is a reference to an object. Since the method
has a reference to the object, it can change the data stored in the object. After the
method ends, obj still points to the same object, but the data stored in the object
might have changed. Suppose x is a variable of type int and stu is a variable of type
Student. Compare:
void dontChange(int z) { void change(Student s) {
z = 42; s.name = " Fred ";
} }
The lines: The lines:
x = 17; stu.name = " Jane";
dontChange(x); change(stu);
System.out.println(x); System.out.println(stu.name);
outputs the value 17. outputs the value " Fred ".
The value of x is not The value of stu is not changed ,
changed by the method, but stu.name is.
which is equivalent to This is equivalent to
z = x; s = stu;
z = 42; s.name = " Fred ";