Sunday, December 30, 2012

Java Exercise #102: ArrayList Implementation

Exercise: Write a program that implements ArrayList

(1)[America]
(2)[Canada, America]
(3)[Canada, America, Russia]
(4)[Canada, America, Russia, France]
(5)[Canada, America, Germany, Russia, France]
(6)[Canada, America, Germany, Russia, France, India]
(7)[America, Germany, Russia, France, India]
(8)[America, Germany, France, India]
(9)[America, Germany, France]

Download Code: ArrayList Implementation

Saturday, December 29, 2012

Java Exercise #101: Count Word Occurrences

Exercise: Write a program that count the occurrences of words in a String.

and : 1
day : 1
fun : 1
good : 1
great : 1
have : 2
keep : 1
learning : 1
morning : 1

Download Code: Count Words

Thursday, December 27, 2012

Java Exercise #100: Eight Queens Problem (Recursion)

Eight Queens problem is to find a solution o place a queen in each row on a chess board such that no two queens attach each other

Exercise: Use recursion to write a program that finds a solution to Eight Queens problem.

Download Code: Eight Queens

Wednesday, December 26, 2012

Java Exercise #99: Sierpinski Triangle

Sierpinski triangle is created as follows:

    • Begin with an equilateral triangle, which is Sierpinski triangle of order 0.
      Connect the midpoints of the sides of triangle of order 0 to create Sierpinski triange of order 1.
      Leave the center triangle intact.
      Repeat the same process recursively to create Sierpinski triangle of order 3, 4 etc..
  • Exercise: Use recursion to write a program that creates Sierpinski triangles of the order which is input by the user.

    Download Code: Sierpinski Triangle

    Tuesday, December 25, 2012

    Java Exercise #98: Towers of Hanoi (Recursion)

    Towers of Hanoi is a classic recursion problem. The problem involves moving a specified number of disks of distinct sizes from one tower to another while observing the following rules.

    • There are n disks labeled 1,2,3...n and three towers labeled A, B and C.
      No disk can be on top of a smaller disk at any time.
      All the disks are initially placed on tower A.
      Only one disk can be moved at a time and it must be the top disk on the tower.
  • The objectve of the problem is to move all the disks from A to B with the assistance of C.

    Exercise: Use recursion to write a program that will take user input for number of disks and solve the problem for that number of disks.

    
    Enter the number of disks:3
    The moves are:
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B
    
    
    
    

    Download Code: Towers of Hanoi

    Java Exercise #97: Determine Directory Size

    Exercise: Use recursion to write a program that will determine the size of a given directory.

    
    Enter a file or directory: C:\Users\Maya\Favorites
    17711 bytes.
    
    Enter a file or directory: C:\Users\Maya\Desktop\aneesh\Java Exercises\Bouncing Ball.png
    26651 bytes.
    
    Enter a file or directory: C:\Users\Maya\Desktop\aneesh\Java Exercises\No File.txt
    0 bytes.
    
    
    

    Download Code: Directory Size

    Java Exercise #96: Recursive Selection Sort

    Exercise: Write a program that uses selection sort with recursion to sort a list.

    
    Before sort:
    2.0 5.0 3.0 1.2 9.8 3.0 
    After sort:
    1.2 2.0 3.0 3.0 5.0 9.8 
    
    

    Download Code: Recursive Selection Sort

    Monday, December 24, 2012

    Java Exercise #95: Palindrome With Recursion

    Exercise: Write a program that determines whether a String is a Palindrome. Use recursion.

    
    Is moon a Palindrome: false
    Is noon a Palindrome: true
    
    
    

    Download Code: Palindrome Using Recursion

    Java Exercise #94: Fibonacci With Recursion

    Exercise: Write a program that asks user input for a positive integer and then print the Fibonacci number for that index. Use recursion.

    
    Enter the Fibonacci Index: 7
    Fibonacci at index 7 is 13
    
    

    Download Code: Fibonacci Using Recursion

    Sunday, December 23, 2012

    Java Exercise #93: Factorial Using Recursion

    Exercise: Write a program that asks user input for a positive integer and then print the factorial of the input. The program should use recursion to determine factorial.

    
    Enter a non-negative number
    10
    Factorial of 10 is 3628800
    
    
    

    Download Code: Factorial Using Recursion

    Saturday, December 22, 2012

    Java Exercise #92: RandomAccessFile

    RandomAccessFile class allows a file to be read from or written to at random locations. Constructor takes String arguments "r"/"rw" for read only/read-write access to file. The method seek(int) can be used to place the pointer where the read and write can be done.

    Exercise: Write a program that demonstrates RandomAccessFile

    
    Current file length is 800
    First number is 0
    Second number is 1
    Tenth number is 9
    Modifying the eleventh number to 555
    Current file length is 800
    Eleventh number is 555
    
    

    Download Code: Random Access File

    Java Exercise #91: Reading & Writing Objects

    ObjectInput/OutputStreams can be used to read and write objects. These are filter streams that can completely replace data stream because it has all the functions available in the data streams like reading and writing integer, double, UTF etc. Apart from those, this also has functionality to read and write objects.

    However, please note that only Serializable objects (Classes or super classes of which implements Serializable interface) can be read or written to file.

    Exercise: Write a program that uses object streams to read and write objects.

    
    John 85.5
    Sat Dec 22 13:56:00 IST 2012
    
    
    

    Download Code: Object Stream Demo

    Java Exercise #90: Copy File Using IO

    BufferedInput/OutputStreams help performance by reducing the read and write from/to files. These are filter streams that read to or write from a byte array instead of doing it one by one.

    Exercise: Write a program that uses buffered streams to copy a file to a target file.

    
    The file ButtonDemo.java has 1578 bytes.
    Copy Done!
    
    

    Download Code: Copy

    Thursday, December 20, 2012

    Java Exercise #89: Data Stream Demo

    Data streams are actually wrappers on existing input and output streams. They are inherited from the filter streams, which in facts are the wrappers. Ordinary input/output streams can work only with bytes. Filter streams gives the capability to work with integers, doubles, strings etc.

    Exercise: Write a program that writes and reads from a binary file using data filter streams.

    
    John 85.5
    Jim 185.5
    George 105.5
    
    

    Download Code: Data Stream

    Java Exercise #88: FileStream Demo

    FileInputStream/FileOutputStream is for reading and writing bytes from/to files. All the methods are inherited from InputStream and OutputStream respectively.

    Exercise: Write a program that writes and reads from a binary file using input output streams

    
    0 1 2 3 4 5 6 7 8 9 
    
    

    Download Code: File Stream

    Wednesday, December 19, 2012

    Java Exercise #87: Image And Audio Demo

    Exercise: Write a program that creates an applet which will show the national flag of a selected country and play its national anthem. The applet will automatically display the next country and play its national anthem once the previous national anthem audio clip is completely played.

    Download Code: National Flats & National Anthems

    Java Exercise #86: Bouncing Ball

    Exercise: Write a program that creates an applet that has a bouncing ball. You can suspend/resume the ball using the buttons and also change the speed of the ball using the scroll bar.

    Download Code: Bouncing Ball Applet

    Sunday, December 16, 2012

    Java Exercise #85: Tic Tac Toe Applet

    Exercise: Write a program that creates an applet for playing tic tac toe game between two players.

    Download Code: Tic Tac Toe Applet

    Saturday, December 15, 2012

    Java Exercise #84: Compute Loan with Applet

    Exercise: Write a program that creates an applet for computing loan re-payment.

    Download Code: Loan Applet

    Java Exercise #83: Simple Applet

    Exercise: Write a program that creates a simple Applet that displays a message. Use AppletViewer to run it as a standalone window.

    Download Code: Simple Applet

    Java Exercise #82: Multiple Window Demo

    Exercise: Write a program that has a text area and a button where the user can enter a message in the text area. Clicking the button should open a new window which has a histogram on the count of each letter in the text area message.

    Download Code: Histogram

    Wednesday, December 12, 2012

    Java Exercise #81: Slider Demo

    Exercise: Write a program that creates a message in a panel. The message can be moved across the panel using a vertical and a horizontal slider (instead of scroll bar which was used in exercise# 81).

    Download Code: Slider Demo

    Tuesday, December 11, 2012

    Java Exercise #80: Scroll Bar Demo

    Exercise: Write a program that creates a message in a panel. The message can be moved across the panel using a vertical and a horizontal scroll bar.

    Download Code: Scroll Bar Demo

    Monday, December 10, 2012

    Java Exercise #79: List Demo

    Exercise: Write a program that uses a drop down list from which the user can select one or more countries. The program will then populate the flags of respective countries in the panel.

    Download Code: List Demo

    Sunday, December 9, 2012

    Java Exercise #78: Combo Box Demo

    Exercise: Write a program that enhances exercise 77 with a combo box from which the country can be selected to display its corresponding flag and flag description.

    Download Code: Combo Box Demo

    Java Exercise #77: Text Area Demo

    Exercise: Write a program that creates the following GUI which uses a non-editable text area.

    Download Code: Text Area Demo

    Saturday, December 8, 2012

    Java Exercise #76: Text Field Demo

    Exercise: Write a program on top of Exercise 75, where a text field is used to create the displayed message.

    Download Code: Text Field Demo

    Java Exercise #75: Radio Button Demo

    Exercise: Write a program on top of Exercise 74, where radio buttons are used to give color to the message.

    Download Code: Radio Button Demo

    Java Exercise #74: Check Box Demo

    Exercise: Write a program on top of Exercise 73, where check boxes are added to center, bold and italic the message

    Download Code: Check Box Demo

    Tuesday, December 4, 2012

    Java Exercise #73: Button Demo

    Exercise: Write a program that creates a frame with a message panel and two buttons - Left and Right. Clicking on the buttons make the message to move in the respective directions.

    Download Code: Button Demo

    Monday, December 3, 2012

    Java Exercise #72: Button Icons

    Exercise: Write a program that creates a frame with a button with icons. The icon will change when mouse rolls over and when clicked (as in the images below).

    Download Code: Button Icons

    Sunday, December 2, 2012

    Java Exercise #71: Live Clock that ticks

    Exercise: Write a program that creates a live analog clock that ticks every second.

    Download Code: Live Clock

    Saturday, December 1, 2012

    Exercise #70: Moving Message demo using Timer class

    The javax.swing.Timer class is a source component that can trigger ActionEvent at a predetermined interval. Listeners to this class needs to implement ActionListener. Listener can be added in the constructor of the Timer class or more listeners can be added using the addActionListener method on the class. Also the delay/interval can be adjusted at a later point of time using the setDelay method. Timer is started using the start() and stopped using the stop methods.

    Exercise: Write a program that demonstrates javax.swing.Timer class where a message moves across a panel at an interval of 1 second.

    Download Code: Moving Message with Timer

    Friday, November 30, 2012

    Java Exercise #69: Key Event Demo

    This exercise is to demonstrate Key Event. Key events enables the use of keys to control and perform actions. A key event is fired whenever a key is pressed, released or typed on a component.

    Exercise: Write a program prints the character key pressed on a panel and help move it using the arrow keys

    Download Code: Key Event

    Thursday, November 29, 2012

    Java Exercise #68: Mouse Event - Dragging message with Mouse

    This exercise is to demonstrate Mouse events. MouseEvent inherits InputEvent. There are two listener interfaces MouseListener and MouseMotionListener. This exercise is a demo on MouseMotionListener

    Exercise: Write a program that drags a message with the mouse on a panel

    Download Code: Mouse Drag Message

    Wednesday, November 28, 2012

    Java Exercise #67: Handling Window Events

    Any subclass of a Window class can fire window events: window opened, window closed, window closing, window activated, window deactivated, window iconified and window de-iconified. This program creates a frame that listens to the window event and displays the message.

    Exercise: Write a program that demonstrates Window Events and Window Listener

    
    Window Activated
    Window Opened
    Window Iconified
    Window Deactivated
    Window Deiconified
    Window Activated
    Window Deactivated
    Window Iconified
    
    
    
    

    Download Code: Window Event Demo

    Monday, November 26, 2012

    Java Exercise #66: Control Ball

    Exercise: Write a program that uses two buttons to control the size of the circle drawn on the GUI.

    Download Code: Control Ball

    Java Exercise #65: Simple Event Demo

    This exercise is to demonstrate simple Event handling in Java GUI. Buttons are source of ActionEvent. Clicking a button invokes the actionPerformed method on the registered listeners. In this implementation, it will invoke getActionCommand() which by default returns the label of the button. The program also uses the event.getWhen() to return the time in long when the event was generated

    This implementation also uses an inner class to create listener instance.

    Exercise: Write a program that creates two buttons and print event information when clicked!

    
    The OK button is clicked at 
    Mon Nov 26 05:52:43 IST 2012
    The Cancel button is clicked at 
    Mon Nov 26 05:52:46 IST 2012
    The Cancel button is clicked at 
    Mon Nov 26 05:52:47 IST 2012
    The OK button is clicked at 
    Mon Nov 26 05:52:49 IST 2012
    The OK button is clicked at 
    Mon Nov 26 06:01:12 IST 2012
    
    
    

    Download Code: Event Demo

    Sunday, November 25, 2012

    Java Exercise #64: Display Image

    Image icons can be used to display image on labels and buttones. However, ImageIcon displays a fixed size image. We can use the Image class to display images in flexible sizes.

    ImageObserver is an asynchronous update interface that receives notifications of image information as the image is constructed. The Component class implements ImageObserver and hence all GUI Components is an instance of ImageObserver. Graphic's drawImage can then be used to draw the image

    Exercise: Write a program that draws the following image.

    Download Code: Draw Image

    Saturday, November 24, 2012

    Java Exercise #63: Still Clock

    Exercise: Write a program that creates the following Still Clock.

    Download Code: Still Clock

    Friday, November 23, 2012

    Java Exercise #62: Message Panel

    This exercise is to develop a useful class that displays a message in the panel. The class enables user to set the location of the message, center the message and move the message with specified interval.

    Exercise: Write a program that creates a message panel that helps user to center the message or even move it.

    Download Code: Message Panel

    Thursday, November 22, 2012

    Java Exercise #61: Centering Message on Panel

    This exercise is to learn to write a String on a panel while centering it. To do so, we need to use the FontMetrics class to measure the exact height and width of the String

    Exercise: Write a program that writes a String centered on the panel.

    Download Code: Center Message

    Wednesday, November 21, 2012

    Java Exercise #60: Drawing Polygon on Panel

    Exercise: Write a program that creates the following GUI with a Polygon painted on the panel

    Download Code: Drawing Polygon

    Tuesday, November 20, 2012

    Java Exercise #59: Drawing Arcs

    Exercise: Write a program that creates the following GUI with arcs painted on the panel

    Download Code: Drawing Arcs

    Monday, November 19, 2012

    Java Exercise #58: Drawing Figures on Panel

    Exercise: Write a program that draws figures on the GUI

    Download Code: Draw Figures

    Sunday, November 18, 2012

    Java Exercise #57: Drawing on Panel

    This exercise is to learn to draw on panels using the paintComponent(Graphics) method of the component. This method is invoked evry time a component is displayed/redisplayed. The Graphics object is automatically created by the JVM for every visible GUI component and then passed to the paintComponent method.

    Panels are invisible and are used as containers. They are used to create the required layout. Panels can also be used for drawing,

    Exercise: Write a program that creates a GUI similar to the following on a Panel.

    Download Code: Draw on Panel

    Saturday, November 17, 2012

    Java Exercise #56: Adding images in GUI

    Exercise: Write a program that creates the following GUI for added image icons

    Download Code: Image Icon GUI

    Friday, November 16, 2012

    Java Exercise #55: Common Swing Features

    Exercise: Write a program that creates the following GUI

    Download Code: Swing Features

    Java Exercise #54: Create a GUI similar to Microwave interface

    Java Panels can also be used as a sub-container where a panel can be added to another panel. This gives better control in developing more compex GUI frames.

    Exercise: Write a program that creates a GUI similar to a Microwave Oven interface.

    Download Code: Microwave Interface

    Thursday, November 15, 2012

    Java Exercise #53: Demonstrate Border Layout

    The BorderLayout manager divides the window into five areas - East, West, South, North and Center. Components can be added to the container using BorderLayout by using add method with the index as parameter. Index is a constant from BorderLayout.EAST, BorderLayout.WEST, BorderLayout.SOUTH, BorderLayout.NORTH or BorderLayout.CENTER

    The components are laid out according to their preferred sizes where they are placed. The North and South components can stretch horizontally, East and West can stretch vertically and Center can stretch bothways.

    Exercise: Write a program that demonstrates BorderLayout.

    Download Code: Border Layout

    Tuesday, November 13, 2012

    Java Exercise #52: Demonstrate GridLayout

    GridLayout manager arranges components in a matrix/grid formation with the specified number of rows and columns. The components are arranged in the container from left to right in the first row until all the columns are occupied. It then starts with the next row and so on.

    With GridLayout, if you resize the frame, the layout remains unchanged.

    Exercise: Write a program that demonstrates GridLayout.

    Download Code: Grid Layout

    Monday, November 12, 2012

    Java Exercise #51: Demonstrate Flow Layout

    Flow Layout is a simple layout manager in Java GUI. The components are arranged in the container from left to right (depending on the alignment configuration used) in the order in which they are used. When one row is filled, the other row gets started.

    You can specify the alignement using the following 3 constants: FlowLayout.LEFT, FlowLayout.RIGHT or FlowLayout.CENTER. Re-arranging the size of the frame, will automatically re-arrange the layout of the components.

    Exercise: Write a program that demonstrates Flow Layout.

    Download Code: Flow Layout

    Sunday, November 11, 2012

    Java Exercise #50: Prime Numbers Above Long.MAX_VALUE

    The problem is to write a program that finds out the prime numbers greater than Long.MAX_VALUE

    Exercise: Write a program that prints five prime numbers greater than Long.MAX_VALUE

    The program was running for hours and hence could not determine the output. However, to ensure that the program is fine, I tested the program for lower values.

    Download Code: Big Prime Numbers

    Saturday, November 10, 2012

    Java Exercise #49: Large Factorial

    If we need to compute very huge numbers or high-precision floating point values, we need to use BigInteger and BigDecimal classes in the java.math package. Both these classes are immutable and also implements Comparable interface. You can use add, subtract, multiple, reminder etc. methods to perform computations.

    Exercise: Write a program that prints the value for 50!

    
    50! is 30414093201713378043612608166064768844377641568960512000000000000
    
    

    Download Code: Large Factorial

    Java Exercise #48: Generic Sort of Comparables

    The problem is to write a generic method to sort an array of Comparable objects. The objects are sorted using the compareTo() method of the Comparable interface.

    Exercise: Write a program that sorts any generic array of objects that implements Comparable interface

    
    Sorted Integer Objects: 2 3 4 
    Sorted Double Objects: -22.1 1.4 3.4 
    Sorted Character Objects: J a r 
    Sorted String Objects: Fred John Tom 
    
    
    
    

    Download Code: Generic Sort

    Java Exercise #47: Click Buttons

    The problem is to write a GUI with two buttons - OK and Cancel. The program will print that the user has clicked OK/Cancel button on console.

    Exercise: Write a program that creates a Frame with OK and Cancel buttons. Program should print on the console which button the user clicked.

    
    Clicked OK Button
    Clicked Cancel Button
    Clicked OK Button
    Clicked OK Button
    Clicked Cancel Button
    Clicked Cancel Button
    
    
    
    

    Download Code: Click Buttons

    Wednesday, November 7, 2012

    Java Exercise #46: Anagram

    The problem is to write a method that checks whether two strings are Anagrams.

    Two words are anagrams if they contain the same letters in any order. For example, "silent" and "listen" are anagrams.

    Exercise: Write a program that prompts the user to enter two strings and verify whether they are anagrams

    
    Enter the first String: garden
    Enter the second String: ranged
    garden and ranged are anagrams
    
    
    Enter the first String: gardens
    Enter the second String: dangers
    gardens and dangers are anagrams
    
    
    

    Download Code: Anagrams

    Tuesday, November 6, 2012

    Java Exercise #45: Counting Digits in a String

    The problem is to write a method that counts the number of digits in a String.

    This implementation uses Character.isDigit() method to verify whether a character is a digit.

    Exercise: Write a program that prompts the user to enter a String and then prints out the number of digits in the String.

    
    Enter string: d#1@bcd23f1gb
    Number of digits is: 4
    
    

    Download Code: Count Digits

    Java Exercise #44: Checking Substring

    Java provides indexOf method in the String class to check whether a String is a sub-string of another string. The problem is to implement such a function.

    This implementation helped me to come to know about labeled break and continue in Java. Default break/continue (non-labeled) breaks or continue from the inner most for, switch, while, do-while statements. However labeled ones help to break from/continue with the outer statements.

    Exercise: Write a program that prompts the user to enter two Strings and then verify whether the first String is a sub-string of the second.

    
    Enter the first string: el
    Enter the second string: hello
    el is a substring of hello
    
    Enter the first string: hello
    Enter the second string: al
    No substring found
    
    
    
    

    Download Code: Check Sub-String

    Sunday, November 4, 2012

    Java Exercise #43: Common Prefix

    Write a method that returns the common prefix for two strings. For example, the common prefix for "distance" and "disappoint" is "dis". If the strings don't have a common prefix, print there is no common prefix between them.

    Exercise: Write a program that prompts the user to enter two strings and display their common prefix.

    
    Enter first string: paddy
    Enter second string: wheat
    No common prefix!
    
    Enter first string: Display
    Enter second string: disappoint
    Common prefix is : dis
    
    
    

    Download Code: Common Prefix

    Saturday, November 3, 2012

    Java Exercise #42: Stack of Integers

    A stack is a data structure that holds objects in a last-in, first-out fashion.

    A stack has many applications. Java Compiler uses a stack to process method invocations. When a method is invoked, its parameter and local variables are pushed to the stack. When the mentod calls another method, the new method's parameters and local variables are pushed into the stock. When the method finishes its work and return to the caller, its associated space is released.

    Exercise: Write a program that implements a stack for storing integers. Stack should internally use an array to hold the elements.

    
    Pushing: 
    0 1 2 3 4 5 6 7 8 9 
    Popping: 
    9 8 7 6 5 4 3 2 1 0 
    
    
    
    

    Download Code: Stack of Integers

    Friday, November 2, 2012

    Java Exercise #41: Choose and Then Read From File

    This exercise is to write a program that chooses a file using the dialog box and then prints the content of the file. This program uses JFileChooser to create the dialog box for choosing file and Scanner class for printing the output

    Exercise: Write a program that chooses a text file using dialog box and then prints the output

    
    
    BODY {
    font-family: Segoe UI;
    font-size: 10pt;
    color: 000000;
    margin-left: 10 px;
    margin-top: 15 px;
    background-position: top left;
    background-repeat: repeat;
    }
    
    
    
    

    Download Code: Choose and Read File

    Thursday, November 1, 2012

    Java Exercise #40: Replace Text In File

    The problem is to write a program that replaces all occurrences of a String in the file. The program uses Scanner class to read from the file and PrintWriter to write to the file.

    Exercise: Write a program that replaces all occurrences of a String in a file. Replace "world" with "universe".

    
    ####hello_world.txt###
    Hello world!
    Good Morning world!
    
    ###hello_universe.txt###
    Hello universe!
    Good Morning universe!
    
    
    
    

    Download Code: Replace Text In File

    Wednesday, October 31, 2012

    Java Exercise #39: Read From Text File

    The problem is to write a program that reads from a text file using Scanner.

    Exercise: Write a program that reads from a text file.

    
    First Name: John Middle Name: T Last Name: Smith: 90
    First Name: Eric Middle Name: K Last Name: Jones: 50
    
    

    Download Code: Read From Text File

    Java Exercise #38: Write to Text File

    The problem is to write a program that writes to a text file using PrintWriter.

    Exercise: Write a program that writes to a text file.

    Download Code: Write to Text File

    Monday, October 29, 2012

    Java Exercise #37: Count Each Letter of String

    The problem is to write a program that prompts the user to enter a string and counts the number of occurrences of each letter of the string regardless of the case.

    The following are the steps involved.

    1. Convert the String to lowercase
    2. Create an array of size 26 for storing the count of each letter
    3. Increment the count for each letter after confirming that each letter is an alphabet

    Exercise: Write a program that implements the above to count each letter of a string

    
    Enter string: ababax
    a appears 3 times
    b appears 2 times
    x appears 1 time
    
    
    
    

    Download Code: Count Each Letter

    Sunday, October 28, 2012

    Java Exercise#36: Check Palindrome

    A Palindrome is a string that reads the same when read forward or backward. Few examples are "Malayalam", "Dad" , "Mom".

    The problem is to write a program that prompts the user to enter a string and then check whether it is a Palindrome or not. One intuitive solution to the problem is to compare the first and last characters of the string. If they are same, then compare the second and second-last and so on. This can continue until all characters are matched or until a mismatch is found

    Exercise: Write a program that implements the above to check whether a String is a Palindrome

    
    Enter a String: moon
    moon is  not  a Palindrome!
    
    Enter a String: malayalam
    malayalam is  a Palindrome!
    
    
    

    Download Code: Check Palindrome

    Saturday, October 27, 2012

    Java Exercise #35: Grading Multiple Choice Test

    This exercise is to write a program that grades multiple choice test. The focus of this program is to use multi-dimensional arrays

    Exercise: Write a program the grades the multiple choice test as below.

    
                Students' Answers to the Questions 
                0  1  2  3  4  5  6  7  8  9
    Student 0 : A  B  A  C  C  D  E  E  A  D
    Student 1 : D  B  A  B  C  A  E  E  A  D
    Student 2 : E  D  D  A  C  B  E  E  A  D
    Student 3 : C  B  A  E  C  D  E  E  A  D
    Student 4 : A  B  D  C  C  D  E  E  A  D
    Student 5 : B  B  E  C  C  D  E  E  A  D
    Student 6 : B  B  A  C  C  D  E  E  A  D
    Student 7 : E  B  E  C  C  D  E  E  A  D
    
                 Key to the Questions
                 0   1   2   3   4   5   6   7   8   9
        Key:     D   B   D   C   C   D   A   E   A   D
    
    ########### OUTPUT #################
    
    For student 0's correct count is 7
    For student 1's correct count is 6
    For student 2's correct count is 5
    For student 3's correct count is 6
    For student 4's correct count is 8
    For student 5's correct count is 7
    For student 6's correct count is 7
    For student 7's correct count is 7
    
    
    
    

    Download Code: Grade Exam

    Friday, October 26, 2012

    Java Exercise #34: Insertion Sort

    Insertion sort algorithm sorts a list of values by repeatedly inserting a new element into a sorted sublist until the whole list is sorted. Starting out, the sorted sublist is the list of size 1 which is the first element in the list. It then inserts the second element to the list by comparing with the element in the list and so on. For the thirde element, it compares the element with the sorted sub-list of size 2. It will move the larger elements to the right and insert the element in the appropriate position in the sub list. With each element being processed, the sublist size increments by one until all the elements are processed.

    Exercise: Write an implementation for Insertion Sort.

    
    Before sort: 
    List is : [69, 4, 2, 10, 60, 50, 59, 11, 7, 70, 66, 79, 45 ]
    After sort: 
    List is : [2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79 ]
    
    
    
    

    Download Code: Insertion Sort

    Thursday, October 25, 2012

    Java Exercise #33: Selection Sort

    Selection sort finds the largest number in the list and places it last. It then finds the largest number from the remaining list and places it second last and so on.

    Exercise: Write an implementation for Selection Sort.

    
    Before sort: 
    List is : [69, 4, 2, 10, 60, 50, 59, 11, 7, 70, 66, 79, 45 ]
    After sort: 
    List is : [2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79 ]
    
    
    
    

    Download Code: Selection Sort

    Wednesday, October 24, 2012

    Java Exercise #32: Binary Search

    Java JDK provides Binary Search. This program is to implement such a binary search.

    Exercise: Write an implementation of binary search and test as below.

    
    List is : [2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79 ]
    Binary Search of 2: 0
    Binary Search of 11: 4
    Binary Search of 12: -6
    Binary Search of 1: -1
    Binary Search of 3: -2
    
    
    

    Download Code: Binary Search

    Java Exercise #31: Count Letters

    This program is to count the occurrences of each letter in an array.

    Exercise: Write a program that generates 100 random lower case letters and then count the occurrence of each letter.

    
    The lowercase letters are: 
    m w u e b l g r p z v f h e n l u t c t 
    e d k j k i r p a x g f p m v m x u c y 
    w f b l k l k m w v c b l k s q a z h f 
    g e v e p m v t g l j k u r b z k g q i 
    s o z x y d f c n j u r c y j a l g q p 
    
    The occurrence of each letter are:
    3 a 4 b 5 c 2 d 5 e 5 f 6 g 2 h 2 i 4 j
    7 k 7 l 5 m 2 n 1 o 5 p 3 q 4 r 2 s 3 t
    5 u 5 v 3 w 3 x 3 y 4 z 
    
    

    Download Code: Count Letters

    Java Exercise #30: Assign Grades

    This program is to read student scores and assign grades to each student

    Exercise: Write a program that reads student scores, get the best score and then assign grade to each student using the following scheme:

    
           Grade is A if score is >= best - 10;
           Grade is B if score is >= best - 20;
           Grade is C if score is >= best - 30;
           Grade is D if score is >= best - 40;
           Grade is F otherwise.
      

    
    Enter the number of students: 4
    
    Please enter a score: 40
    Please enter a score: 50
    Please enter a score: 60
    Please enter a score: 70
    Student 0 score is 40 and grade is C
    Student 1 score is 50 and grade is B
    Student 2 score is 60 and grade is A
    Student 3 score is 70 and grade is A
    
    

    Download Code: Assign Grades

    Saturday, October 20, 2012

    Java Exercise #29: Max Number & Count

    This program is to find the largest number in an array and then count its occurrences.

    Exercise: Write a program that reads 6 integers from the user, then find the largest of them and count its occurrences.

    
    Enter the number: 3
    Enter the number: 5
    Enter the number: 2
    Enter the number: 5
    Enter the number: 5
    Enter the number: 4
    
    The array is 5 2 5 5 4 
    The largest number is 5
    The number of occurrence is 3
    
    
    
    

    Download Code: Max and its Count

    Java Exercise #28: Print Calendar

    This program is to display the calendar for given month of the year.

    Exercise: Write a program that prompts the user to enter the year and the month, and then displays the entire calendar for the month as shown below.

    
    Enter year as int (eg: 2003): 2006
    Enter month as int (eg: 1 for January): 6
               June  2006
    -----------------------------
     Sun Mon Tue Wed Thu Fri Sat
                   1   2   3   4
       5   6   7   8   9  10  11
      12  13  14  15  16  17  18
      19  20  21  22  23  24  25
      26  27  28  29  30
    
    
    

    Download Code: Print Calendar

    Friday, October 19, 2012

    Java Exercise #27: Random Characters

    This program is to print random characters

    Exercise: Write a program that prints random characters.

    
    Random Character: ?
    Random Lower Case Character: d
    Random Upper Case Character: M
    Random Upper Case Digit Character: 0
    
    
    
    

    Download Code: Random Characters

    Thursday, October 18, 2012

    Java Exercise #26: Sentinel Value (Dialog Box)

    This exercise is to use sentinel value using Dialog Box.

    Exercise: Write a program that takes input from users using Dialog Box. The program takes input integers and then sum them up and display the sum value.

    Download Code: Sentinel Value (Dialog Box)