HTML Character Entities
To display a less than sign (<) in HTML, we have to use a character entity.
Character Entities
Some characters have a special meaning in HTML, like the less than sign (<) that defines the start of an HTML tag. If we want the browser to actually display these characters we must insert character entities in the HTML source.
A character entity has three parts: an ampersand (&), an entity name or a # and an entity number, and finally a semicolon (;).
To display a less than sign in an HTML document we must write: < or <
The advantage of using a name instead of a number is that a name is easier to remember. The disadvantage is that not all browsers support the newest entity names, while the support for entity numbers is very good in almost all browsers.
Note that the entities are case sensitive.
Non-breaking Space
The most common character entity in HTML is the non-breaking space.
Normally HTML will truncate spaces in your text. If you write 10 spaces in your text HTML will remove 9 of them. To add spaces to your text, use the character entity.
The Most Common Character Entities:Result Description Entity Name Entity Number
non-breaking space
< less than < <
> greater than > >
& ampersand & &
" quotation mark " "
' apostrophe ' (does not work in IE) '
Some Other Commonly Used Character Entities:Result Description Entity Name Entity Number
¢ cent ¢ ¢
£ pound £ £
¥ yen ¥ ¥
€ euro € €
§ section § §
© copyright © ©
® registered trademark ® ®
× multiplication × ×
÷ division ÷ ÷
HTML Attributes
HTML tags can have attributes. Attributes provide additional information to an HTML element.
Attributes always come in name/value pairs like this: name="value".
Attributes are always specified in the start tag of an HTML element.
Use Lowercase Attributes
Attributes and attribute values are case-insensitive. However, the World Wide Web Consortium (W3C) recommends lowercase attributes/attribute values in their HTML 4 recommendation, and XHTML demands lowercase attributes/attribute values.
Always Quote Attribute Values
Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single style quotes are also allowed.
In some rare situations, like when the attribute value itself contains quotes, it is necessary to use single quotes:
name='John "ShotGun" Nelson'
Basic HTML Tags
The best way to learn HTML is to work with examples. We have created a very nice HTML editor for you. With this editor, you can edit the HTML source code if you like, and click on a test button to view the result.
Headings
Headings are defined with the
to tags. defines the largest heading. defines the smallest heading.This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
HTML automatically adds an extra blank line before and after a heading.
Paragraphs
Paragraphs are defined with the
defines the largest heading. defines the smallest heading.This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
HTML automatically adds an extra blank line before and after a heading.
Paragraphs
Paragraphs are defined with the
This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
This is a heading
HTML automatically adds an extra blank line before and after a heading.
Paragraphs
Paragraphs are defined with the
tag.
This is a paragraph
This is another paragraph
HTML automatically adds an extra blank line before and after a paragraph.
Don't Forget the Closing Tag
You might have noticed that paragraphs can be written without end tags :
This is a paragraph
This is another paragraph
The example above will work in most browsers, but don't rely on it. Future version of HTML will not allow you to skip ANY end tags.
Closing all HTML elements with an end tag is a future-proof way of writing HTML. It also makes the code easier to understand (read and browse) when you mark both where an element starts and where it ends.
Line Breaks
The
tag is used when you want to break a line, but don't want to start a new paragraph. The
tag forces a line break wherever you place it.
This
is a para
graph with line breaks
Try it yourself
The
tag is an empty tag. It has no end tag like , since a closing tag doesn't make any sense.
or
More and more often you will see the
tag written like this:
Because the
tag has no end tag (or closing tag), it breaks one of the rules for future HTML (the XML based XHTML), namely that all elements must be closed.
Writing it like
is a future proof way of closing (or ending) the tag inside the opening tag, accepted by both HTML and XML.
Comments in HTML
The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser. You can use comments to explain your code, which can help you when you edit the source code at a later date.
Note that you need an exclamation point after the opening bracket, but not before the closing bracket.
Recap on HTML Elements
Each HTML element has an element name (body, h1, p, br)
The start tag is the name surrounded by angle brackets:
The end tag is a slash and the name surrounded by angle brackets
The element content occurs between the start tag and the end tag
Some HTML elements have no content
Some HTML elements have no end tag
Basic Notes - Useful Tips
When you write HTML text, you can never be sure how the text is displayed in another browser. Some people have large computer displays, some have small. The text will be reformatted every time the user resizes his window. Never try to format the text in your editor by adding empty lines and spaces to the text.
HTML will truncate the spaces in your text. Any number of spaces count as one. Some extra information: In HTML a new line counts as one space.
Using empty paragraphs
to insert blank lines is a bad habit. Use the
tag instead. (But don't use the
tag to create lists. Wait until you have learned about HTML lists.)
HTML automatically adds an extra blank line before and after some elements, like before and after a paragraph, and before and after a heading.
We use a horizontal rule (the
tag), to separate the sections in our tutorials
Basic HTML Tags
If you lookup the basic HTML tags in the reference below, you will see that the reference contains additional information about tag attributes.
You will learn more about HTML tag attributes in the next chapter of this tutorial.
Tag Description
Defines an HTML document
Defines the document's body
to Defines header 1 to header 6
Defines a paragraph
Inserts a single line break
Defines a horizontal rule
Defines a comment
HTML Elements
HTML elements are defined using HTML tags.
HTML Tags
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
HTML tags normally come in pairs like and
The first tag in a pair is the start tag, the second tag is the end tag
The text between the start and end tags is the element content
HTML tags are not case sensitive, means the same as
HTML Elements
Remember the HTML example from the previous page:
This is my first homepage. This text is bold
This is an HTML element:This text is bold
The HTML element starts with a start tag:
The content of the HTML element is: This text is bold
The HTML element ends with an end tag:
The purpose of the tag is to define an HTML element that should be displayed as bold.
This is also an HTML element:
This is my first homepage. This text is bold
This HTML element starts with the start tag , and ends with the end tag .
The purpose of the tag is to define the HTML element that contains the body of the HTML document.
Why do We Use Lowercase Tags?
We have just said that HTML tags are not case sensitive: means the same as . If you surf the Web, you will notice that plenty of web sites use uppercase HTML tags in their source code. We always use lowercase tags. Why?
If you want to follow the latest web standards, you should always use lowercase tags. The World Wide Web Consortium (W3C) recommends lowercase tags in their HTML 4 recommendation, and XHTML (the next generation HTML) demands lowercase tags.
Learn HTML
HTML stands for Hyper Text Markup Language
An HTML file is a text file containing small markup tags
The markup tags tell the Web browser how to display the page
An HTML file must have an htm or html file extension
An HTML file can be created using a simple text editor
Do You Want to Try It?
If you are running Windows, start Notepad.
If you are on a Mac, start SimpleText.
In OSX start TextEdit and change the following preferences: Open the "Format" menu and select "Plain text" instead of "Rich text". Then open the "Preferences" window under the "Text Edit" menu and select "Ignore rich text commands in HTML files". Your HTML code will probably not work if you do not change the preferences above!
Type in the following text:
This is my first homepage. This text is bold
Save the file as "mypage.htm".
Start your Internet browser. Select "Open" (or "Open Page") in the File menu of your browser. A dialog box will appear. Select "Browse" (or "Choose File") and locate the HTML file you just created - "mypage.htm" - select it and click "Open". Now you should see an address in the dialog box, for example "C:\MyDocuments\mypage.htm". Click OK, and the browser will display the page.
Example Explained
The first tag in your HTML document is . This tag tells your browser that this is the start of an HTML document. The last tag in your document is . This tag tells your browser that this is the end of the HTML document.
The text between the tag and the tag is header information. Header information is not displayed in the browser window.
The text between the
The text between the
The text between the and tags will be displayed in a bold font.
HTM or HTML Extension?
When you save an HTML file, you can use either the .htm or the .html extension. We have used .htm in our examples. It might be a bad habit inherited from the past when some of the commonly used software only allowed three letter extensions.
With newer software we think it will be perfectly safe to use .html.
Note on HTML Editors:
You can easily edit HTML files using a WYSIWYG (what you see is what you get) editor like FrontPage or Dreamweaver, instead of writing your markup tags in a plain text file.
However, if you want to be a skillful Web developer, we strongly recommend that you use a plain text editor to learn your primer HTML.
Java criticism
Class path
Running a Java program requires all third party supporting libraries to be in the class path. This can be an obstacle to portability, because its syntax is platform-specific: Windows-based systems use backslashes to mark subdirectories and semicolons to separate entries, whereas all other platforms use forward slashes to mark subdirectories and colons to separate entries.
It is also necessary for each .jar or .zip archive required to be explicitly named in the class path. Java provides a way around this by allowing directories listed in the class path to end in an asterisk (*), which will be expanded to the names of all files ending in .jar or .JAR within the directory. However, such an entry does not match .zip or .class files within that directory.
License
Sun Java's proprietary nature gave it a controversial position in the free software community. Because Sun's implementation of Java was not free software, it could not be included in projects that require a free software or GPL-compatible license, such as Debian main, the $100 laptop, and Fedora Core. Sun announced in JavaOne 2006 that Java will become open source software. The statement was issued by Sun Software Executive Vice President Rich Green: "It's not a question of whether, it's a question of how, and so we'll go do this."
In July 2006, Sun's CTO Robert Brewin commented that Java will be partially open source by June 2007 but the entire platform will take more time to be fully open source. On November 13, 2006, Sun announced that its standard edition Java runtime environment will be released under the GPL by March of 2007. Its source code will be available under the GPL. According to Richard Stallman, this will mean an end to the Java trap. Mark Shuttleworth called the initial press announcement "a real milestone for the free software community."
Resource management
While Java does manage memory, it does not manage all resources, such as JDBC database connections; these must be released just as memory would need to be in C++.
Memory management
Java takes care of memory management. This was done as it makes it harder (but not impossible) for the programmer to create problems such as memory leaks. Java always allocates objects on the heap (unless optimized to the stack or registers by the JIT compiler) and local variables on the stack or in registers. This makes Java less flexible than C++, which allows programmers to choose where objects are allocated.
The garbage collector controls when objects are deleted from memory. Java does not allow programmers to guarantee when garbage collection happens (even with System.gc()), they cannot hold off garbage collection, and they cannot delete one particular object. While this makes programming much simpler and reduces memory leaks, it lacks the flexibility that can, in some cases, result in a more efficient handling of memory. Lower-level languages such as C or assembly language provide this flexibility.
While many programs, such as those written in C++, tend to fall prey to memory leaks, this is not the whole story. Other resource leaks such as file handles, database and network connections are still likely, especially when exceptions are thrown. However, where C++ has the RAII idiom to address both cases, Java programmers need to remember to release resources in finally clauses and must have a good understanding of which resources Java will release and which they must release.
Primitives vs. objects / Autoboxing
Java designers decided not to implement certain features present in other languages (including multiple inheritance, operator overloading, and tuples).
When generics were added to Java 5.0, there was already a large framework of classes (many of which were already deprecated), so generics were chosen to be implemented using erasure to allow backwards compatibility and preservation of these existing classes. This limited the features that could be provided by this addition as compared to other languages.
Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was done for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language and this makes reflection more complicated. However, Java 5.0 supports automatic conversion (autoboxing) of primitive data types to corresponding object form wherever required, during compilation. When autounboxing, a null pointer exception may be thrown. Since this operation occurs implicitly (without a cast or method call), this unchecked exception may not be obvious by inspection of the line of code.
Non-Virtual methods
Java provides no way to make methods non-virtual (although they can be "sealed" by using the final modifier to disallow overriding). This means that there is no way to let derived classes define a new, unrelated method with the same name. This can be a problem when a base class is designed by a different person, and a new version introduces a method with the same name and signature as some method already present in the derived class. This means that the method in the derived class will implicitly override the method in the base class, even though that was not the intent of the designers of either class. To partially accommodate for these versioning problems, Java 5.0 introduced the @Override annotation, but to preserve backwards compatibility it could not be made compulsory by default.
Single paradigm
Java is predominantly a single-paradigm language. The addition of static imports in Java 5.0 accommodates the procedural paradigm better than earlier versions of Java.
Exception handling
Java embraced the concept of exception specifications from C++ where they were optional, but made throws clauses mandatory for any checked exception. While this can be a benefit for small systems, there is not universal agreement that using checked exceptions is a benefit for larger systems. In particular, "higher level" code is often not interested in errors thrown by "lower level" code (eg: NamingException). The coder of the naming classes must make a choice: either force higher level code to deal with naming exceptions as checked exceptions, or allow them to "bubble up" through his own low-level code without compile-time checks.
Closure
Finally, while anonymous inner classes provide a basic form of closures, they are not complete and require referenced variables to either be class fields or declared "final". The rationale behind this is that it allows JVM implementors to choose a stack model for variable lifetimes, so that a variable scope is removed when exited, thus preventing real closures. In addition, when using - for instance - "Runnable" as a closure, one has to declare the "run" method and put the code in that: you cannot simply put some code in braces and pass it around.
Floating point arithmetic
While Java's floating point arithmetic is largely based on IEEE 754 (Standard for Binary Floating-Point Arithmetic), certain features are not supported even when using the "strictfp" modifier, such as Exception Flags and Directed Roundings — capabilities mandated by IEEE Standard 754. Many so-called "Java gotchas" are not problems with Java per se, but problems that are inevitable whenever using floating point arithmetic.
Look and feel
The look and feel of GUI applications written in Java using the Swing platform is often different from native applications. While programmers can choose to use the AWT toolkit that displays native widgets (and thus look like the operating platform), the AWT toolkit is unable to meet advanced GUI programming needs by wrapping around advanced widgets and not sacrificing portability across the various supported platforms, each of which have vastly different APIs especially for higher-level widgets.
The Swing toolkit--written completely in Java--both creates the problem of having a different look and feel from native applications, and avoids the problem of being limited by native toolkit capabilities because it reimplements widgets using only the most basic drawing mechanisms that are guaranteed available on all platforms. Unfortunately, the default installations of the JRE (as of August 2006) do not use the system's "native" look and feel, instead defaulting to the built-in Metal Look and Feel. If the programmer doesn't take care to set the native look and feel, users will have applications whose appearance is vastly different from that of their native applications. Apple Computer's own optimized version of the Java Runtime, which is included within the Mac OS X distribution, by default does set the default and implements its "Aqua" look-and-feel, giving Swing applications on the Macintosh a similar appearance to native software. Even in this environment, the programmer must still do some extra work to ensure that that application looks like an Aqua one (for example, they must set system properties to ensure the menubar is rendered in the OS X menubar and not in the application window as it would be on other platforms).
Performance
It is impossible to make any generalization about the performance of Java programs, because runtime performance is affected much more by the quality of the compiler or JVM than by any intrinsic properties of the language itself. Java bytecode can either be interpreted at run time by a virtual machine, or it can be compiled at load time or runtime into machine code which runs directly on the computer's hardware. Interpretation is slower than native execution, and compilation at load time or runtime has an initial performance penalty for the compilation.
Lack of language features
There are a few language requirements which incur an unavoidable time penalty, although these features are not unique to Java. Among these are array bounds checking, run-time type checking, and virtual function indirection (although each of these can in some situations be avoided by an optimizing compiler). Also the lack of features can affect performance. For example, Java does not have arrays of structures or a true multi-dimensional array, but only an array of references to objects or further arrays. Nor does Java allow returning more than one value from a function without using an object. The net result is that Java code makes more heap allocations than well-written code in some other languages.
Garbage collection
The use of a garbage collector to automatically delete objects adds overhead compared to manual deallocation and can have a positive or negative impact, or no discernible impact at all, on performance depending upon the garbage collector implementation and the characteristics of the application's use of objects. With the modern generational garbage collectors used in many JVMs, many applications actually experience greater performance because of faster allocation and deallocation algorithms.
Byte code vs. native compilation
Relative performance of JIT compilers as compared to native compilers can be quite close, and is often a subject of debate. The JIT compilation stage may be time consuming, which is inconvenient for applications that are short-lived and/or contain large amounts of code. Once compiled to native code, however, the performance of the program can be comparable to that achieved by a native compiler, even on numerical tasks. Although Java does not support manual inlining of method calls, many JIT compilers perform this optimization at load time and can exploit information from the runtime environment to guide more effective transformations, such as profile-directed inlining. Dynamic recompilation, as provided by Sun's HotSpot JVM, can exceed the performance of the static compilation available in most other languages by exploiting information that is only available at runtime.
Hardware interfacing
Because Java was designed with an emphasis on security and portability, it does not support direct access to the machine architecture and address space. This means working directly with a specific piece of hardware such as a scanner, digital camera, audio recorder, video capture, or virtually any hardware that requires direct memory space control (typically those pieces or hardware installed with drivers), cannot easily be accomplished with Java. An illustration of this issue is seen in version 1.0 of Java as it was not possible to access a printer because the interface code to the various printer drivers was not included in this first JVM.
Interfacing with native code
Clients side or server systems that need to "talk" to the hardware must implement a hybrid solution using Java and C/C++ or assembly language via the Java Native Interface (JNI) libraries to link native code to the Java libraries. An alternate solution is to code the hardware software component in its native C/C++/assembler language and then pass the data via files, databases or a shared memory interface, although this is not an ideal solution.
Using the JNI technique introduces many possible inconsistencies such as: machine dependency, potential deadlock situations, memory allocation leaks, and possibly poor application performance, not to mention code complexity of needing to maintain two different code bases. However, it must be noted that it is a common case for other Virtual machine languages, as for example the .NET Framework Common Language Runtime (see Platform Invocation Services).
Inconsistent JVM implementations
Java is a bytecode language that runs on top of the JVM; ultimately the compatibility of the language and the ability to have it run across different platforms is dependent on the stability and version of the JVM. While Java is touted as running on a large variety of systems, the most up to date JVM (and JRE) are only those actively updated for Windows, Linux and Solaris. HP (such as Java for HP-UX) and IBM (for MVS, AIX, OS/400) provide their own implementations for their family of platforms but do not always mirror the latest Sun releases. Other JVM implementations usually follow, but sometimes lag in months or years with the more common implementations and therefore introduce compatibility issues.
Java applet
Applets are used to provide interactive features to web applications that cannot be provided by HTML. Since Java's bytecode is platform independent, Java applets can be executed by browsers for many platforms, including Windows, Unix, Mac OS and Linux. There are open source tools like applet2app which can be used to convert an applet to a stand alone Java application/windows executable. This has the advantage of running a Java applet in offline mode without the need for internet browser software.
A Java Servlet is sometimes informally compared to be "like" a server-side applet, but it is different in its language, functions, and in each of the characteristics described here about applets.
Technical information
Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applet's user interface. The applet can be displayed on the web page by making use of the deprecated applet HTML element or the recommended object element. This specifies the applet's source and the applet's location statistics.
A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (Applet is a descendant of Panel which is a descendant of Container).
Advantages of applets
A Java applet can have any or all of the following advantages:
* it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it cross platform
* the same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the JRE the client will be forced wait during the large download.
* it runs in a sandbox, so the user does not need to trust the code, so it can work without security approval
* it is supported by most web browsers
* it will cache in most web browsers, so will be quick to load when returning to a web page
* it can have full access to the machine it is running on if the user agrees
* it can improve with use: after a first applet is run, the JVM is already running and starts quickly, benefiting regular users of Java
* it can run at a comparable (but generally slower) speed to other compiled languages such as C++
* it can be a real time application
* it can move the work from the server to the client, making a web solution more scalable with the number of users/clients
Disadvantages of applets
A Java applet is open to any of the following disadvantages:
* it requires the Java plug-in, which isn't available by default on all web browsers
* it can't start up until the Java Virtual Machine is running, and this may have significant startup time the first time it is used
* if it is uncached, it must be downloaded (usually over the internet), and this takes time
* it is considered more difficult to build and design a good user interface with applets than with HTML-based technologies
* if untrusted, it has severely limited access to the user's system - in particular having no direct access to the client's disc or clipboard
* some organizations only allow software installed by the administrators. As a result, many users cannot view applets by default.
* applets may require a specific JRE.
Compatibility issues
Sun has made a considerable effort to ensure compatibility is maintained between Java versions as they evolve. For example, Microsoft's Internet Explorer, the most popular web browser since the late 1990s, used to ship with Microsoft's own JVM as the default. The MSJVM had some extra non-Java features added which, if used, would prevent MSJVM applets from running on Sun's Java (but not the other way round). Sun sued for breach of trademark, as the point of Java was that there should be no proprietary extensions and that code should work everywhere. Development of MSJVM was frozen by a legal settlement, leaving many users with an extremely outdated Java virtual machine. Later, in October 2001, MS stopped including Java with Windows, and for some years it has been left to the computer manufacturers to ship Java independently of the OS. Most new machines now ship with official Sun Java.
Some browsers (notably Firefox) do not do a good job of handling height=100% on applets which makes it difficult to make an applet fill most of the browser window (Javascript can, with difficulty, be used for this). Having the applet create its own main window is not a good solution either, as this leads to a large chance of the applet getting terminated unintentionally and leaves the browser window as a largely useless extra window.
Alternatives
Alternative technologies exist (for example, DHTML and Flash) that satisfy some of the scope of what is possible with an applet.
Another alternative to applets for client side Java is Java Web Start, which runs outside the browser. In addition to the features available to applets, a simple permissions box can give Java Web Start programs read and/or write access to specified files stored on the client, and to the client's clipboard.
JAVA String Utility
String Utility
/*
* NumberUtility.java
*
* Source: http://www.freejavaguide.com
*/
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
/**
* Class provides common functions on number formats.
*/
public class NumberUtility {
/**
* Method takes Object as parameter and returns decimal number.
* if argument is float or double and contains tailing zeros
* it removes them. If argument is float or double then no change in return type.
* Change the Format of the Number by changing the String Pattern
*/
public static String changeToDecimalFormat(Object number) {
BigDecimal bdNumber = new BigDecimal(number.toString());
bdNumber = bdNumber.stripTrailingZeros(); //Returns a BigDecimal with any trailing zero's removed
String pattern = "###,##0.0###########"; //To apply formatting when the number of digits in input equals the pattern
DecimalFormat newFormat = new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.US));
return newFormat.format(bdNumber);
}
/* Method takes Object as parameter and removes commas from the parameter */
public static double removeCommasFromNumber(Object number) {
try {
StringBuffer inputNo = new StringBuffer(number.toString());
if (inputNo.length() > 0) {
while (inputNo.indexOf(",") != -1) {
inputNo.deleteCharAt(inputNo.indexOf(","));
}
} else {
return 0.0;
}
return Double.parseDouble(inputNo.toString());
} catch (NumberFormatException e) {
return 0.0;
}
}
/* Some times its required to have a fixed set of decimal places for a
* number. We can set that by changing the precision number for a particular
* input BigDecimal Input String
*/
public static String changeToRequiredDecimals(String bigDecimalString,
int precision) {
String newFormattedString = null;
String afterDecimal = null;
if (bigDecimalString == null || bigDecimalString.length() == 0) {
return "0.0";
}
if (bigDecimalString.contains(".")) {
afterDecimal = bigDecimalString.substring(bigDecimalString
.indexOf(".") + 1);
int length = Math.abs((afterDecimal.length() - precision));
if (afterDecimal.length() < precision) {
newFormattedString = bigDecimalString;
for (int i = 0; i < length; i++) {
newFormattedString = newFormattedString + "0";
}
} else if (afterDecimal.length() > precision) {
newFormattedString = bigDecimalString.substring(0,
bigDecimalString.length() - length);
if (precision == 0) {
newFormattedString = newFormattedString.substring(0,
newFormattedString.indexOf("."));
} else {
newFormattedString = bigDecimalString;
}
} else {
if (precision > 0)
newFormattedString = bigDecimalString + ".";
else
newFormattedString = bigDecimalString;
for (int i = 0; i < precision; i++) {
newFormattedString = newFormattedString + "0";
}
}
}
return newFormattedString;
}
public static void main(String args[]){
int intVar = 10;
double doubleVar = 10.504000;
float floatVar = 343534534348.5687654F;
String commaString = "343,534,535,000.0";
BigDecimal bdNumber = new BigDecimal("1234.8765");
System.out.println(NumberUtility.changeToDecimalFormat(new Integer(intVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Double(doubleVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Float(floatVar)));
System.out.println(NumberUtility.removeCommasFromNumber(commaString));
System.out.println(NumberUtility.changeToRequiredDecimals(bdNumber.toString(), 8));
}
}
JAVA Date Utility
Date and Time
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {
/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/
public static void addToDate(){
System.out.println("In the ADD Operation");
// String DATE_FORMAT = "yyyy-MM-dd";
String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS for formats
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
System.out.println("Todays date in Calendar Format : "+c1);
System.out.println("c1.getTime() : "+c1.getTime());
System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));
System.out.println("Todays date in Date Format : "+d1);
c1.set(1999,0 ,20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
c1.add(Calendar.DATE,40);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}
/*Substract Day/Month/Year to a Date
roll() is used to substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
Note: To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1)
or roll down (substract 1) to the specified Calendar field. The operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in the same
year while add() substract the YEAR field for the correct result
*/
public static void subToDate(){
System.out.println("In the SUB Operation");
String DATE_FORMAT = "dd-MM-yyyy";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
// roll down, substract 1 month
c1.roll(Calendar.MONTH, false);
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));
c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}
public static void daysBetween2Dates(){
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 0 , 20);
c2.set(1999, 0 , 22);
System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");
System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));
System.out.println();
System.out.println();
}
public static void daysInMonth() {
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 6 , 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println("Days in "+month+"th month for year "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();
System.out.println();
}
public static void getDayofTheDate() {
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat("EEEE");
try {
day = f.format(d1);
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("The dat for "+d1+" is "+day);
System.out.println();
System.out.println();
}
public static void validateAGivenDate() {
String dt = "20011223";
String invalidDt = "20031315";
String dateformat = "yyyyMMdd";
Date dt1=null , dt2=null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println("Date is ok = " + dt1 + "(" + dt + ")");
}
catch (ParseException e) {
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e) {
System.out.println("Invalid date");
}
System.out.println();
System.out.println();
}
public static void compare2Dates(){
SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.set(2000, 02, 15);
c2.set(2001, 02, 15);
System.out.print(fm.format(c1.getTime())+" is ");
if(c1.before(c2)){
System.out.println("less than "+c2.getTime());
}else if(c1.after(c2)){
System.out.println("greater than "+c2.getTime());
}else if(c1.equals(c2)){
System.out.println("is equal to "+fm.format(c2.getTime()));
}
System.out.println();
System.out.println();
}
public static boolean isLeapYear(int year){
if((year%100 != 0) || (year%400 == 0)){
return true;
}
return false;
}
public static void main(String args[]){
addToDate();
subToDate();
daysBetween2Dates(); //The "right" way would be to compute the julian day number of both dates and then do the substraction.
daysInMonth();
validateAGivenDate();
compare2Dates();
getDayofTheDate();
}
}
Core Java Programs [ PAGE 2]
/* Write a program to Concatenate string using for Loop
Example:
Input - 5
Output - 1 2 3 4 5 */
class Join{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
String result = " ";
for(int i=1;i<=num;i++){
result = result + i + " ";
}
System.out.println(result);
}
}
Program 12
/* Program to Display Multiplication Table */
class MultiplicationTable{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
System.out.println("*****MULTIPLICATION TABLE*****");
for(int i=1;i<=num;i++){
for(int j=1;j<=num;j++){
System.out.print(" "+i*j+" ");
}
System.out.print("\n");
}
}
}
Program 13
/* Write a program to Swap the values */
class Swap{
public static void main(String args[]){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("\n***Before Swapping***");
System.out.println("Number 1 : "+num1);
System.out.println("Number 2 : "+num2);
//Swap logic
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("\n***After Swapping***");
System.out.println("Number 1 : "+num1);
System.out.println("Number 2 : "+num2);
}
}
Program 14
/* Write a program to convert given no. of days into months and days.
(Assume that each month is of 30 days)
Example :
Input - 69
Output - 69 days = 2 Month and 9 days */
class DayMonthDemo{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
int days = num%30;
int month = num/30;
System.out.println(num+" days = "+month+" Month and "+days+" days");
}
}
Program 15
/*Write a program to generate a Triangle.
eg:
1
2 2
3 3 3
4 4 4 4 and so on as per user given number */
class Triangle{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
for(int i=1;i<=num;i++){
for(int j=1;j<=i;j++){
System.out.print(" "+i+" ");
}
System.out.print("\n");
}
}
}
Program 16
/* Write a program to Display Invert Triangle.
Example:
Input - 5
Output :
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
*/
class InvertTriangle{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
while(num > 0){
for(int j=1;j<=num;j++){
System.out.print(" "+num+" ");
}
System.out.print("\n");
num--;
}
}
}
Program 17
/*Write a program to find whether given no. is Armstrong or not.
Example :
Input - 153
Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */
class Armstrong{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
int n = num; //use to check at last time
int check=0,remainder;
while(num > 0){
remainder = num % 10;
check = check + (int)Math.pow(remainder,3);
num = num / 10;
}
if(check == n)
System.out.println(n+" is an Armstrong Number");
else
System.out.println(n+" is not a Armstrong Number");
}
}
Program 18
/* Write a program to Find whether number is Prime or Not. */
class PrimeNo{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i
if(num%i==0)
{
System.out.println(num+" is not a Prime Number");
flag = 1;
break;
}
}
if(flag==0)
System.out.println(num+" is a Prime Number");
}
}
Program 19
/* Write a program to find whether no. is palindrome or not.
Example :
Input - 12521 is a palindrome no.
Input - 12345 is not a palindrome no. */
class Palindrome{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0){
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(reverse == n)
System.out.println(n+" is a Palindrome Number");
else
System.out.println(n+" is not a Palindrome Number");
}
}
Core Java Programs [PAGE 3]
Some Java programs which help lot of java beginners to understand the basic fundamentals in Java programming. Most of these programs take input from the command line. Ex - int num = Integer.parseInt(args[0]);
Program 20
/* switch case demo
Example :
Input - 124
Output - One Two Four */
class SwitchCaseDemo{
public static void main(String args[]){
try{
int num = Integer.parseInt(args[0]);
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0){
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
String result=""; //contains the actual output
while(reverse > 0){
remainder = reverse % 10;
reverse = reverse / 10;
switch(remainder){
case 0 :
result = result + "Zero ";
break;
case 1 :
result = result + "One ";
break;
case 2 :
result = result + "Two ";
break;
case 3 :
result = result + "Three ";
break;
case 4 :
result = result + "Four ";
break;
case 5 :
result = result + "Five ";
break;
case 6 :
result = result + "Six ";
break;
case 7 :
result = result + "Seven ";
break;
case 8 :
result = result + "Eight ";
break;
case 9 :
result = result + "Nine ";
break;
default:
result="";
}
}
System.out.println(result);
}catch(Exception e){
System.out.println("Invalid Number Format");
}
}
}
Program 21
/* Write a program to generate Harmonic Series.
Example :
Input - 5
Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */
class HarmonicSeries{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
double result = 0.0;
while(num > 0){
result = result + (double) 1 / num;
num--;
}
System.out.println("Output of Harmonic Series is "+result);
}
}
Program 22
/*Write a program to find average of consecutive N Odd no. and Even no. */
class EvenOdd_Avg{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
while(n > 0){
if(n%2==0){
cntEven++;
sumEven = sumEven + n;
}
else{
cntOdd++;
sumOdd = sumOdd + n;
}
n--;
}
int evenAvg,oddAvg;
evenAvg = sumEven/cntEven;
oddAvg = sumOdd/cntOdd;
System.out.println("Average of first N Even no is "+evenAvg);
System.out.println("Average of first N Odd no is "+oddAvg);
}
}
Program 23
/* Display Triangle as follow : BREAK DEMO.
1
2 3
4 5 6
7 8 9 10 ... N */
class Output1{
public static void main(String args[]){
int c=0;
int n = Integer.parseInt(args[0]);
loop1: for(int i=1;i<=n;i++){
loop2: for(int j=1;j<=i;j++){
if(c!=n){
c++;
System.out.print(c+" ");
}
else
break loop1;
}
System.out.print("\n");
}
}
}
Program 24
/* Display Triangle as follow
0
1 0
1 0 1
0 1 0 1 */
class Output2{
public static void main(String args[]){
for(int i=1;i<=4;i++){
for(int j=1;j<=i;j++){
System.out.print(((i+j)%2)+" ");
}
System.out.print("\n");
}
}
}
Program 25
/* Display Triangle as follow
1
2 4
3 6 9
4 8 12 16 ... N (indicates no. of Rows) */
class Output3{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print((i*j)+" ");
}
System.out.print("\n");
}
}
}
Core Java Programs [ PAGE 1]
Some Java programs which help lot of java beginners to understand the basic fundamentals in Java programming.
Program 1
//Find Maximum of 2 nos.
class Maxof2{
public static void main(String args[]){
//taking value as command line argument.
//Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
if(i > j)
System.out.println(i+" is greater than "+j);
else
System.out.println(j+" is greater than "+i);
}
}
Program 2
//Find Minimum of 2 nos. using conditional operator
class Minof2{
public static void main(String args[]){
//taking value as command line argument.
//Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = (i
System.out.println(result+" is a minimum value");
}
}
Program 3
/* Write a program that will read a float type value from the keyboard and print the following output.
->Small Integer not less than the number.
->Given Number.
->Largest Integer not greater than the number.
*/
class ValueFormat{
public static void main(String args[]){
double i = 34.32; //given number
System.out.println("Small Integer not greater than the number : "+Math.ceil(i));
System.out.println("Given Number : "+i);
System.out.println("Largest Integer not greater than the number : "+Math.floor(i));
}
Program 4
/*Write a program to generate 5 Random nos. between 1 to 100, and it
should not follow with decimal point.
*/
class RandomDemo{
public static void main(String args[]){
for(int i=1;i<=5;i++){
System.out.println((int)(Math.random()*100));
}
}
}
Program 5
/* Write a program to display a greet message according to
Marks obtained by student.
*/
class SwitchDemo{
public static void main(String args[]){
int marks = Integer.parseInt(args[0]); //take marks as command line argument.
switch(marks/10){
case 10:
case 9:
case 8:
System.out.println("Excellent");
break;
case 7:
System.out.println("Very Good");
break;
case 6:
System.out.println("Good");
break;
case 5:
System.out.println("Work Hard");
break;
case 4:
System.out.println("Poor");
break;
case 3:
case 2:
case 1:
case 0:
System.out.println("Very Poor");
break;
default:
System.out.println("Invalid value Entered");
}
}
}
JDBC Programming Examples
JDBC Programming Examples
================================
1. Substitute your driver's JDBC URL for the generic JDBC URL
that appears in the code. In other words, put your driver's JDBC URL
between the quotation marks in the follwoing line:
String url = "jdbc:mySubprotocol:myDataSource";
The documentation for your driver should give you this URL.
2. Substitute the driver's full class name for "myDriver.ClassName" in
the following line:
Class.forName("myDriver.ClassName");
3. Substitute the username and password you use for your database
in the following:
"userid", "password"
*/
import javax.swing.JOptionPane;
import java.sql.*;
public class JdbcDemo
{
public static void main(String args[])
{
JOptionPane.showMessageDialog(null,"Welcome to JDBC Demo");
int choice = -1;
String userid="scott";
String password = "tiger";
do
{
choice = getChoice();
if (choice != 0)
{
getSelected(choice, userid, password);
}
}
while ( choice != 0);
System.exit(0);
}
public static int getChoice()
{
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,
"1. Create Coffees Table\n"+
"2. Insert Values into Coffees Table\n"+
"3. Create Suppliers Table\n"+
"4. Insert Values into Suppliers Table\n"+
"5. Update Table Example on Coffees Table\n"+
"6. A PreparedStatement Demo On Coffees Table\n"+
"7. A PreparedStatement Demo On Coffees Table using a FOR Statement\n"+
"8. List of the coffees he buys from Acme, Inc [Supplier]\n"+
"9. Using Transactions Demo"+
"10. Creating a Stored Procedue Demo\n"+
"11. Using Callable Statement to call a Stored Procedure\n"+
"12. Batch Update Demo\n"+
"0. Exit\n\n"+
"Enter your choice");
ch = Integer.parseInt(choice);
return ch;
}
public static void getSelected(int choice, String userid, String password)
{
if(choice==1)
{
createCoffees(userid, password);
}
else if(choice==2)
{
insertCoffees(userid, password);
}
else if(choice==3)
{
createSuppliers(userid, password);
}
else if(choice==4)
{
insertSuppliers(userid, password);
}
else if(choice==5)
{
updateCoffees(userid, password);
}
else if(choice==6)
{
prepare1Demo(userid, password);
}
else if(choice==7)
{
prepare2Demo(userid, password);
}
else if(choice==8)
{
joinDemo(userid, password);
}
else if(choice==9)
{
transDemo(userid, password);
}
else if(choice==10)
{
createProcedure1(userid, password);
}
else if(choice==11)
{
callableDemo(userid, password);
}
else if(choice==12)
{
batchUpdateDemo(userid, password);
}
}
// Create Coffees Table
public static void createCoffees(String userid, String password)
{
String url = "jdbc:odbc:bob"; // String url = "jdbc:mySubprotocol:myDataSource"; ?
// jdbc:subprotocol:subname
Connection con;
String createString;
createString = "create table COFFEES " +
"(COF_NAME varchar(32), " +
"SUP_ID int, " +
"PRICE float, " +
"SALES int, " +
"TOTAL int)";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Class.forName("myDriver.ClassName"); ?
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Insert values into Coffees Table
public static void insertCoffees(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt;
String query = "select COF_NAME, PRICE from COFFEES";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
stmt = con.createStatement();
stmt.executeUpdate("insert into COFFEES " +
"values('Colombian', 00101, 7.99, 0, 0)");
stmt.executeUpdate("insert into COFFEES " +
"values('French_Roast', 00049, 8.99, 0, 0)");
stmt.executeUpdate("insert into COFFEES " +
"values('Espresso', 00150, 9.99, 0, 0)");
stmt.executeUpdate("insert into COFFEES " +
"values('Colombian_Decaf', 00101, 8.99, 0, 0)");
stmt.executeUpdate("insert into COFFEES " +
"values('French_Roast_Decaf', 00049, 9.99, 0, 0)");
ResultSet rs = stmt.executeQuery(query);
System.out.println("Coffee Break Coffees and Prices:");
while (rs.next()) {
String s = rs.getString("COF_NAME"); // OR rs.getString(1);
float f = rs.getFloat("PRICE"); // OR rs.getFloat(3);
System.out.println(s + " " + f);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Create Suppliers Table
public static void createSuppliers(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
String createString;
createString = "create table SUPPLIERS " +
"(SUP_ID int, " +
"SUP_NAME varchar(40), " +
"STREET varchar(40), " +
"CITY varchar(20), " +
"STATE char(2), ZIP char(5))";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Insert values into Coffees Table
public static void insertSuppliers(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt;
String query = "select SUP_NAME, SUP_ID from SUPPLIERS";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
stmt = con.createStatement();
stmt.executeUpdate("insert into SUPPLIERS " +
"values(49, 'Superior Coffee', '1 Party Place', " +
"'Mendocino', 'CA', '95460')");
stmt.executeUpdate("insert into SUPPLIERS " +
"values(101, 'Acme, Inc.', '99 Market Street', " +
"'Groundsville', 'CA', '95199')");
stmt.executeUpdate("insert into SUPPLIERS " +
"values(150, 'The High Ground', '100 Coffee Lane', " +
"'Meadows', 'CA', '93966')");
ResultSet rs = stmt.executeQuery(query);
System.out.println("Suppliers and their ID Numbers:");
while (rs.next()) {
String s = rs.getString("SUP_NAME");
int n = rs.getInt("SUP_ID");
System.out.println(s + " " + n);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Update Coffees Table
public static void updateCoffees(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
String updateString;
updateString = "UPDATE COFFEES " +
"SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
String query = "SELECT COF_NAME, SALES FROM COFFEES " +
"WHERE COF_NAME LIKE 'Colombian'";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
stmt = con.createStatement();
stmt.executeUpdate(updateString);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME"); //1
int n = rs.getInt("SALES"); //2
System.out.println(n + " pounds of " + s +
" sold this week.");
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Update Coffees Table using a prepared Statement
public static void prepare1Demo(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt=null;
String query = "SELECT COF_NAME, SALES FROM COFFEES ";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME"); //1
int n = rs.getInt("SALES"); //2
System.out.println(s + " " + n);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
// Update Coffees Table using a prepared Statement
public static void prepare2Demo(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt=null;
String query = "SELECT COF_NAME, SALES FROM COFFEES ";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast", "Espresso",
"Colombian_Decaf", "French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
// int n= updateSales.executeUpdate() to find out how may rows have been updated
}
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME"); //1
int n = rs.getInt("SALES"); //2
System.out.println(s + " " + n);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
//Using join on 2 table to retrieve results
public static void joinDemo(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
String query = "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +
"from COFFEES, SUPPLIERS " +
"where SUPPLIERS.SUP_NAME like 'Acme, Inc.' and " +
"SUPPLIERS.SUP_ID = COFFEES.SUP_ID";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection (url,
"userid", "password");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("Supplier, Coffee:");
while (rs.next()) {
String supName = rs.getString(1);
String cofName = rs.getString(2);
System.out.println(" " + supName + ", " + cofName);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
// Using Transaction Autocommit Option
public static void transDemo(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con=null;
Statement stmt;
PreparedStatement updateSales;
PreparedStatement updateTotal;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update COFFEES " +
"set TOTAL = TOTAL + ? where COF_NAME = ?";
String query = "select COF_NAME, SALES, TOTAL from COFFEES";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast",
"Espresso", "Colombian_Decaf",
"French_Roast_Decaf"};
int len = coffees.length;
con.setAutoCommit(false);
for (int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
updateTotal.setInt(1, salesForWeek[i]);
updateTotal.setString(2, coffees[i]);
updateTotal.executeUpdate();
con.commit();
}
con.setAutoCommit(true);
updateSales.close();
updateTotal.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String c = rs.getString("COF_NAME");
int s = rs.getInt("SALES");
int t = rs.getInt("TOTAL");
System.out.println(c + " " + s + " " + t);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ");
System.err.println("rolled back");
con.rollback();
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
}
}
}
}
/*Creating a Stored procedure involving the coffees and the suppliers table
create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME
*/
public static void createProcedure1(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt;
String createProcedure = "create procedure SHOW_SUPPLIERS " +
"as " +
"select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +
"from SUPPLIERS, COFFEES " +
"where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " +
"order by SUP_NAME";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"DPST_TRNG", "DPST_TRNG4321");
stmt = con.createStatement();
stmt.executeUpdate(createProcedure);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
//Using Callable Statement to call a Stored Procedure
public static void callableDemo(String userid, String password)
{
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"DPST_TRNG", "DPST_TRNG4321");
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
while (rs.next()) {
String c = rs.getString("SUP_NAME");
String s = rs.getString("COF_NAME");
System.out.println(c + " " + s );
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
//A code showing the Batch Update Syntax
public static void batchUpdateDemo(String userid, String password)
{
ResultSet rs = null;
PreparedStatement ps = null;
String url = "jdbc:odbc:bob";
Connection con;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"userid", "password");
con.setAutoCommit(false);
stmt = con.createStatement();
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Amaretto', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Hazelnut', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");
int [] updateCounts = stmt.executeBatch();
con.commit();
con.setAutoCommit(true);
ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
System.out.println("Table COFFEES after insertion:");
while (uprs.next()) {
String name = uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
float price = uprs.getFloat("PRICE");
int sales = uprs.getInt("SALES");
int total = uprs.getInt("TOTAL");
System.out.print(name + " " + id + " " + price);
System.out.println(" " + sales + " " + total);
}
uprs.close();
stmt.close();
con.close();
} catch(BatchUpdateException b) {
System.err.println("-----BatchUpdateException-----");
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor: " + b.getErrorCode());
System.err.print("Update counts: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
System.err.println("");
} catch(SQLException ex) {
System.err.println("-----SQLException-----");
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor: " + ex.getErrorCode());
}
}
}//End of class
Java/J2EE Programmer Practice Test 1
1. Which of the following are valid definitions of an application's main( ) method?
a) public static void main();
b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );
2. If MyProg.java were compiled as an application and then run from the command line as:
java MyProg I like tests
what would be the value of args[ 1 ] inside the main( ) method?
a) MyProg
b) "I"
c) "like"
d) 3
e) 4
f) null until a value is assigned
3. Which of the following are Java keywords?
a) array
b) boolean
c) Integer
d) protect
e) super
4. After the declaration:
char[] c = new char[100];
what is the value of c[50]?
a) 50
b) 49
c) '\u0000'
d) '\u0020'
e) " "
f) cannot be determined
g) always null until a value is assigned
5. After the declaration:
int x;
the range of x is:
a) -231 to 231-1
b) -216 to 216 - 1
c) -232 to 232
d) -216 to 216
e) cannot be determined; it depends on the machine
6. Which identifiers are valid?
a) _xpoints
b) r2d2
c) bBb$
d) set-flow
e) thisisCrazy
7. Represent the number 6 as a hexadecimal literal.
8. Which of the following statements assigns "Hello Java" to the String variable s?
a) String s = "Hello Java";
b) String s[] = "Hello Java";
c) new String s = "Hello Java";
d) String s = new String("Hello Java");
9. An integer, x has a binary value (using 1 byte) of 10011100. What is the binary value of z after these statements:
int y = 1 <<>
int z = x & y;
a) 1000 0001
b) 1000 0000
c) 0000 0001
d) 1001 1101
e) 1001 1100
10. Which statements are accurate:
a) >> performs signed shift while >>> performs an unsigned shift.
b) >>> performs a signed shift while >> performs an unsigned shift.
c) <<>
d) <<<>
11. The statement ...
String s = "Hello" + "Java";
yields the same value for s as ...
String s = "Hello";
String s2= "Java";
s.concat( s2 );
True
False
12. If you compile and execute an application with the following code in its main() method:
String s = new String( "Computer" );
if( s == "Computer" )
System.out.println( "Equal A" );
if( s.equals( "Computer" ) )
System.out.println( "Equal B" );
a) It will not compile because the String class does not support the = = operator.
b) It will compile and run, but nothing is printed.
c) "Equal A" is the only thing that is printed.
d) "Equal B" is the only thing that is printed.
e) Both "Equal A" and "Equal B" are printed.
13. Consider the two statements:
1. boolean passingScore = false && grade == 70;
2. boolean passingScore = false & grade == 70;
The expression
grade == 70
is evaluated:
a) in both 1 and 2
b) in neither 1 nor 2
c) in 1 but not 2
d) in 2 but not 1
e) invalid because false should be FALSE
14. Given the variable declarations below:
byte myByte;
int myInt;
long myLong;
char myChar;
float myFloat;
double myDouble;
Which one of the following assignments would need an explicit cast?
a) myInt = myByte;
b) myInt = myLong;
c) myByte = 3;
d) myInt = myChar;
e) myFloat = myDouble;
f) myFloat = 3;
g) myDouble = 3.0;
15. Consider this class example:
class MyPoint
{ void myMethod()
{ int x, y;
x = 5; y = 3;
System.out.print( " ( " + x + ", " + y + " ) " );
switchCoords( x, y );
System.out.print( " ( " + x + ", " + y + " ) " );
}
void switchCoords( int x, int y )
{ int temp;
temp = x;
x = y;
y = temp;
System.out.print( " ( " + x + ", " + y + " ) " );
}
}
What is printed to standard output if myMethod() is executed?
a) (5, 3) (5, 3) (5, 3)
b) (5, 3) (3, 5) (3, 5)
c) (5, 3) (3, 5) (5, 3)
16. To declare an array of 31 floating point numbers representing snowfall for each day of March in Gnome, Alaska, which declarations would be valid?
a) double snow[] = new double[31];
b) double snow[31] = new array[31];
c) double snow[31] = new array;
d) double[] snow = new double[31];
17. If arr[] contains only positive integer values, what does this function do?
public int guessWhat( int arr[] )
{ int x= 0;
for( int i = 0; i <>
x = x <>
return x;
}
a) Returns the index of the highest element in the array
b) Returns true/false if there are any elements that repeat in the array
c) Returns how many even numbers are in the array
d) Returns the highest element in the array
e) Returns the number of question marks in the array
18. Consider the code below:
arr[0] = new int[4];
arr[1] = new int[3];
arr[2] = new int[2];
arr[3] = new int[1];
for( int n = 0; n <>
System.out.println( /* what goes here? */ );
Which statement below, when inserted as the body of the for loop, would print the number of values in each row?
a) arr[n].length();
b) arr.size;
c) arr.size -1;
d) arr[n][size];
e) arr[n].length;
19. If size = 4, triArray looks like:
int[][] makeArray( int size)
{ int[][] triArray = new int[size] [];
int val=1;
for( int i = 0; i <>
{ triArray[i] = new int[i+1];
for( int j=0; j <>
{ triArray[i][j] = val++;
}
}
return triArray;
}
a)
1 2 3 4
5 6 7
8 9
10
b)
1 4 9 16
c)
1 2 3 4
d)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
e)
1
2 3
4 5 6
7 8 9 10
20. Which of the following are legal declarations of a two-dimensional array of integers?
a) int[5][5]a = new int[][];
b) int a = new int[5,5];
c) int[]a[] = new int[5][5];
d) int[][]a = new[5]int[5];
21. Which of the following are correct methods for initializing the array "dayhigh" with 7 values?
a) int dayhigh = { 24, 23, 24, 25, 25, 23, 21 };
b) int dayhigh[] = { 24, 23, 24, 25, 25, 23, 21 };
c) int[] dayhigh = { 24, 23, 24, 25, 25, 23, 21 };
d) int dayhigh [] = new int[24, 23, 24, 25, 25, 23, 21];
e) int dayhigh = new[24, 23, 24, 25, 25, 23, 21];
22. If you want subclasses to access, but not to override a superclass member method, what keyword should precede the name of the superclass method?
23. If you want a member variable to not be accessible outside the current class at all, what keyword should precede the name of the variable when declaring it?
24. Consider the code below:
public static void main( String args[] )
{ int a = 5;
System.out.println( cube( a ) );
}
int cube( int theNum )
{
return theNum * theNum * theNum;
}
What will happen when you attempt to compile and run this code?
a) It will not compile because cube is already defined in the java.lang.Math class.
b) It will not compile because cube is not static.
c) It will compile, but throw an arithmetic exception.
d) It will run perfectly and print "125" to standard output.
25. Given the variables defined below:
int one = 1;
int two = 2;
char initial = '2';
boolean flag = true;
Which of the following are valid?
a) if( one ){}
b) if( one = two ){}
c) if( one == two ){}
d) if( flag ){}
e) switch( one ){}
f) switch( flag ){}
g) switch( initial ){}
26. If val = 1 in the code below:
switch( val )
{ case 1: System.out.print( "P" );
case 2:
case 3: System.out.print( "Q" );
break;
case 4: System.out.print( "R" );
default: System.out.print( "S" );
}
Which values would be printed?
a) P
b) Q
c) R
d) S
27. Assume that val has been defined as an int for the code below:
if( val > 4 )
{ System.out.println( "Test A" );
}
else if( val > 9 )
{ System.out.println( "Test B" );
}
else System.out.println( "Test C" );
Which values of val will result in "Test C" being printed:
a) val <>
b) val between 0 and 4
c) val between 4 and 9
d) val > 9
e) val = 0
f) no values for val will be satisfactory
28. What exception might a wait() method throw?
29. For the code:
m = 0;
while( m++ <>
System.out.println( m );
Which of the following are printed to standard output?
a) 0
b) 1
c) 2
d) 3
e) Nothing and an exception is thrown
30. Consider the code fragment below:
outer: for( int i = 1; i <3;>
{ inner: for( j = 1; j <>
{ if( j==2 )
continue outer;
System.out.println( "i = " +i ", j = " + j );
}
}
Which of the following would be printed to standard output?
a) i = 1, j = 1
b) i = 1, j = 2
c) i = 1, j = 3
d) i = 2, j = 1
e) i = 2, j = 2
f) i = 2, j = 3
g) i = 3, j = 1
h) i = 3, j = 2
31. Consider the code below:
void myMethod()
{ try
{
fragile();
}
catch( NullPointerException npex )
{
System.out.println( "NullPointerException thrown " );
}
catch( Exception ex )
{
System.out.println( "Exception thrown " );
}
finally
{
System.out.println( "Done with exceptions " );
}
System.out.println( "myMethod is done" );
}
What is printed to standard output if fragile() throws an IllegalArgumentException?
a) "NullPointerException thrown"
b) "Exception thrown"
c) "Done with exceptions"
d) "myMethod is done"
e) Nothing is printed
32. Consider the following code sample:
class Tree{}
class Pine extends Tree{}
class Oak extends Tree{}
public class Forest
{ public static void main( String[] args )
{ Tree tree = new Pine();
if( tree instanceof Pine )
System.out.println( "Pine" );
if( tree instanceof Tree )
System.out.println( "Tree" );
if( tree instanceof Oak )
System.out.println( "Oak" );
else System.out.println( "Oops" );
}
}
Select all choices that will be printed:
a) Pine
b) Tree
c) Forest
d) Oops
e) (nothing printed).