Java Programming



Assembly Language
; hex convertor.
; this example converts a 2 digit hexadecimal number
; into a numeric value and then into decimal/ascii string representation,
; and finally it prints out the result in binary code.

; to see decimal string:
;   1. click "vars"
;   2. click "result" variable
;   3. enter "3" for the elements and "ascii" for show as.


name "hex"

org 100h

jmp start

; source hex value is 2 char string.
; numeric value is stored into temp,
; and string decimal value is stored into result.

source db '1b', 0     ; 1bh is converted to 27 (decimal) 00011011b (binary)
result db '000', 0
temp   dw ?

start:
; convert first digit to value 0..15 from ascii:
mov al, source[0]
cmp al, '0'
jae  f1

f1:
cmp al, '9'
ja f2     ; jumps only if not '0' to '9'.

sub al, 30h  ; convert char '0' to '9' to numeric value.
jmp num1_ready

f2:
; gets here if it's 'a' to 'f' case:
or al, 00100000b   ; remove upper case (if any).
sub al, 57h  ;  convert char 'a' to 'f' to numeric value.

num1_ready:
mov bl, 16
mul bl      ; ax = al * bl

mov temp, ax




; convert second digit to value 0..15 from ascii:
mov al, source[1]
cmp al, '0'
jae  g1

g1:
cmp al, '9'
ja g2     ; jumps only if not '0' to '9'.

sub al, 30h  ; convert char '0' to '9' to numeric value.
jmp num2_ready

g2:
; gets here if it's 'a' to 'f' case:
or al, 00100000b   ; remove upper case (if any).
sub al, 57h  ;  convert char 'a' to 'f' to numeric value.

num2_ready:
xor ah, ah
add temp, ax
; convertion from hex string complete!
push temp ; store original temp value.

; convert to decimal string,
; it has to be 3 decimal digits or less:

mov di, 2  ; point to top of the string.

next_digit:

cmp temp, 0
je stop

mov ax, temp
mov bl, 10
div bl ; al = ax / operand, ah = remainder.
mov result[di], ah
add result[di], 30h ; convert to ascii.

xor ah, ah
mov temp, ax

dec di  ; next digit in string.
jmp next_digit

stop:
pop temp ; re-store original temp value.





; print result in binary:
mov bl, b.temp
mov cx, 8
print: mov ah, 2   ; print function.
       mov dl, '0'
       test bl, 10000000b  ; test first bit.
       jz zero
       mov dl, '1'
zero:  int 21h
       shl bl, 1
loop print

; print binary suffix:
mov dl, 'b'
int 21h

; wait for any key press:
mov ah, 0
int 16h




ret  ; return to operating system.

OUTPUT:










_____________________________________________________________________________


#start=robot.exe#

name "robot"

#make_bin#
#cs = 500#
#ds = 500#
#ss = 500#    ; stack
#sp = ffff#
#ip = 0#

; this is an example of contoling the robot.

; this code randomly moves the robot,
; and makes it to switch the lamps on and off.

; robot is a mechanical creature and it takes
; some time for it to complete a task.
; status register is used to see if robot is busy or not.

; c:\emu8086\devices\robot.exe uses ports 9, 10 and 11
; source code of the robot and other devices is in:
; c:\emu8086\devices\developer\sources\
; robot is programmed in visual basic 6.0


; robot base i/o port:
r_port equ 9

;===================================

eternal_loop:
; wait until robot
; is ready:
call wait_robot

; examine the area
; in front of the robot:
mov al, 4
out r_port, al

call wait_exam

; get result from
; data register:
in al, r_port + 1

; nothing found?
cmp al, 0
je cont  ; - yes, so continue.

; wall?
cmp al, 255
je cont  ; - yes, so continue.

; switched-on lamp?
cmp al, 7
jne lamp_off  ; - no, so skip.
; - yes, so switch it off,
;   and turn:
call switch_off_lamp
jmp  cont  ; continue

lamp_off: nop

; if gets here, then we have
; switched-off lamp, because
; all other situations checked
; already:
call switch_on_lamp

cont:
call random_turn

call wait_robot

; try to step forward:
mov al, 1
out r_port, al

call wait_robot

; try to step forward again:
mov al, 1
out r_port, al

jmp eternal_loop ; go again!

;===================================

; this procedure does not
; return until robot is ready
; to receive next command:
wait_robot proc
; check if robot busy:
busy: in al, r_port+2
      test al, 00000010b
      jnz busy ; busy, so wait.
ret  
wait_robot endp

;===================================

; this procedure does not
; return until robot completes
; the examination:
wait_exam proc
; check if has new data:
busy2: in al, r_port+2
       test al, 00000001b
       jz busy2 ; no new data, so wait.
ret  
wait_exam endp

;===================================

; switch off the lamp:
switch_off_lamp proc
mov al, 6
out r_port, al
ret
switch_off_lamp endp

;===================================

; switch on the lamp:
switch_on_lamp proc
mov al, 5
out r_port, al
ret
switch_on_lamp endp

;===================================

; generates a random turn using
; system timer:
random_turn proc

; get number of clock
; ticks since midnight
; in cx:dx
mov ah, 0
int 1ah

; randomize using xor:
xor dh, dl
xor ch, cl
xor ch, dh

test ch, 2
jz no_turn

test ch, 1
jnz turn_right

; turn left:
mov al, 2
out r_port, al
; exit from procedure:
ret

turn_right:
mov al, 3
out r_port, al

no_turn:
ret
random_turn endp

;===================================
OUTPUT:










________________________________________________________________________

; this is a program in 8086 assembly language that
; accepts a character string from the keyboard and
; stores it in the string array. the program then converts 
; all the lower case characters of the string to upper case. 
; if the string is empty (null), it doesn't do anything.

name "upper"

org 100h


jmp start


; first byte is buffer size,
; second byte will hold number
; of used bytes for string,
; all other bytes are for characters:
string db 20, 22 dup('?')

new_line db 0Dh,0Ah, '$'  ; new line code.

start:

; int 21h / ah=0ah - input of a string to ds:dx, 
; fist byte is buffer size, second byte is number 
; of chars actually read. does not add '$' in the
; end of string. to print using int 21h / ah=09h
; you must set dollar sign at the end of it and 
; start printing from address ds:dx + 2.

lea dx, string

mov ah, 0ah
int 21h

mov bx, dx
mov ah, 0
mov al, ds:[bx+1]
add bx, ax ; point to end of string.

mov byte ptr [bx+2], '$' ; put dollar to the end.

; int 21h / ah=09h - output of a string at ds:dx.
; string must be terminated by '$' sign.
lea dx, new_line
mov ah, 09h
int 21h


lea bx, string

mov ch, 0
mov cl, [bx+1] ; get string size.

jcxz null ; is string is empty?

add bx, 2 ; skip control chars.

upper_case:

; check if it's a lower case letter:
cmp byte ptr [bx], 'a'
jb ok
cmp byte ptr [bx], 'z'
ja ok

; convert to uppercase:

; upper case letter do not have
; third bit set, for example:
; 'a'             : 01100001b
; 'a'             : 01000001b
; upper case mask : 11011111b

; clear third bit:
and byte ptr [bx], 11011111b

ok:
inc bx ; next char.
loop upper_case


; int 21h / ah=09h - output of a string at ds:dx.
; string must be terminated by '$' sign.
lea dx, string+2
mov ah, 09h
int 21h
; wait for any key press....
mov ah, 0
int 16h 
null:
ret  ; return to operating system.
 OUTPUT:













CODEs

Batman Begins - Unavailable *
Problem  1). Write a program that prompts the user to input an integer and then output the number with the digits reversed.
For example :If the Input is:12345,
                     Then outputs should be:54321
Java Codes:
File name should be Reverse2 

import javax.swing.*;

public class Reverse2 {
    public static void main(String[] args) {

        String input;    // Used for the input string.
        String reversed; // Reversed form or the input string.

        while (true) {
            input = JOptionPane.showInputDialog(null, "Enter a string");
            if (input == null) break;

            reversed = "";
            for (int i=0; i


C++ Codes:


#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
const int numberOfDig = 5;
string num = "0";
cout << endl << "Enter a Integer number: ";
cin >> num;

string revNum = "00000";
for (int i = 0; i < numberOfDig; i++)
{
revNum[numberOfDig - i - 1] = num[i];
}

cout << endl << "You have entered: " << num
<< endl << "Reversed number is: " << revNum
<< endl;

system("PAUSE");
return 0;
}


 Other Problem= Make a program that has a clickable menu or buttons that are associated with each other.
Simple Menu and Window interface - not Internationalized



Java Codes:

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
 * pioneering role in inventing and promulgating (and standardizing) the Java
 * language and environment is gratefully acknowledged.
 *
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

///

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 * Simple Menu and Window interface - not Internationalized.
 *
 * @author Ian Darwin
 */
public class JiltBefore extends JFrame implements ActionListener {
  JMenuBar mb;

  /** File, Options, Help */
  JMenu fm, om, hm;

  /** Options Sub-Menu */
  JMenu opSubm;

  /** The JMenuItem for exiting. */
  JMenuItem exitItem;

  // Constructor
  JiltBefore(String s) {
    super("JiltBefore: " + s);

    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());

    mb = new JMenuBar();
    setJMenuBar(mb);

    JMenuItem mi;
    // The File Menu...
    fm = new JMenu("File");
    fm.add(mi = new JMenuItem("Open"));
    mi.addActionListener(this);
    fm.add(mi = new JMenuItem("Close"));
    mi.addActionListener(this);
    fm.addSeparator();
    fm.add(mi = new JMenuItem("Print"));
    mi.addActionListener(this);
    fm.addSeparator();
    fm.add(mi = new JMenuItem("Exit"));
    exitItem = mi; // save for action handler
    mi.addActionListener(this);
    mb.add(fm);

    // The Options Menu...
    om = new JMenu("Options");
    fm.add(mi = new JMenuItem("Enable"));
    opSubm = new JMenu("SubOptions");
    opSubm.add(new JMenuItem("Alpha"));
    opSubm.add(new JMenuItem("Gamma"));
    opSubm.add(new JMenuItem("Delta"));
    om.add(opSubm);
    mb.add(om);

    // The Help Menu...
    hm = new JMenu("Help");
    hm.add(mi = new JMenuItem("About"));
    mi.addActionListener(this);
    hm.add(mi = new JMenuItem("Topics"));
    mi.addActionListener(this);
    mb.add(hm);
    // mb.setHelpMenu(hm); // needed for portability (Motif, etc.).

    // the main window
    cp.add(new JLabel("Menu Demo Window"));
    // pack();
    setSize(250, 200);
  }

  /** Handle action events. */
  public void actionPerformed(ActionEvent evt) {
    // System.out.println("Event " + evt);
    String cmd;
    if ((cmd = evt.getActionCommand()) == null)
      System.out.println("You chose a menu shortcut");
    else
      System.out.println("You chose " + cmd);
    Object cmp = evt.getSource();
    // System.out.println("Source " + cmp);
    if (cmp == exitItem)
      System.exit(0);
  }

  public static void main(String[] arg) {
    new JiltBefore("Testing 1 2 3...").setVisible(true);
  }
}

 Menu Glue Demo














Java Codes:


/* From http://java.sun.com/docs/books/tutorial/index.html */

/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;

/**
 * @author ges
 * @author kwalrath
 */
/* MenuGlueDemo.java is a 1.4 application that requires no other files. */
public class MenuGlueDemo {
  public JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(createMenu("Menu 1"));
    menuBar.add(createMenu("Menu 2"));
    menuBar.add(Box.createHorizontalGlue());
    menuBar.add(createMenu("Menu 3"));
    return menuBar;
  }

  public JMenu createMenu(String title) {
    JMenu m = new JMenu(title);
    m.add("Menu item #1 in " + title);
    m.add("Menu item #2 in " + title);
    m.add("Menu item #3 in " + title);
    return m;
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    //Create and set up the window.
    JFrame frame = new JFrame("MenuGlueDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    MenuGlueDemo demo = new MenuGlueDemo();
    frame.setContentPane(demo.createMenuBar());

    //Display the window.
    frame.setSize(300, 100);
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

A quick demonstration of checkbox menu items

















Java Codes:


/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly
*/
// CheckBoxMenuItemExample.java
// A quick demonstration of checkbox menu items.
//

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.border.BevelBorder;

public class CheckBoxMenuItemExample extends JPanel {
  public JTextPane pane;

  public JMenuBar menuBar;

  public JToolBar toolBar;

  public CheckBoxMenuItemExample() {
    menuBar = new JMenuBar();
    JMenu justifyMenu = new JMenu("Justify");
    ActionListener actionPrinter = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          pane.getStyledDocument().insertString(
              0,
              "Action [" + e.getActionCommand()
                  + "] performed!\n", null);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    };
    JCheckBoxMenuItem leftJustify = new JCheckBoxMenuItem("Left",
        new ImageIcon("1.gif"));
    leftJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
    leftJustify.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit
        .getDefaultToolkit().getMenuShortcutKeyMask()));
    leftJustify.addActionListener(actionPrinter);
    JCheckBoxMenuItem rightJustify = new JCheckBoxMenuItem("Right",
        new ImageIcon("2.gif"));
    rightJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
    rightJustify.setAccelerator(KeyStroke.getKeyStroke('R', Toolkit
        .getDefaultToolkit().getMenuShortcutKeyMask()));
    rightJustify.addActionListener(actionPrinter);
    JCheckBoxMenuItem centerJustify = new JCheckBoxMenuItem("Center",
        new ImageIcon("3.gif"));
    centerJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
    centerJustify.setAccelerator(KeyStroke.getKeyStroke('M', Toolkit
        .getDefaultToolkit().getMenuShortcutKeyMask()));
    centerJustify.addActionListener(actionPrinter);
    JCheckBoxMenuItem fullJustify = new JCheckBoxMenuItem("Full",
        new ImageIcon("4.gif"));
    fullJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
    fullJustify.setAccelerator(KeyStroke.getKeyStroke('F', Toolkit
        .getDefaultToolkit().getMenuShortcutKeyMask()));
    fullJustify.addActionListener(actionPrinter);

    justifyMenu.add(leftJustify);
    justifyMenu.add(rightJustify);
    justifyMenu.add(centerJustify);
    justifyMenu.add(fullJustify);

    menuBar.add(justifyMenu);
    menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));

  }

  public static void main(String s[]) {
    CheckBoxMenuItemExample example = new CheckBoxMenuItemExample();
    example.pane = new JTextPane();
    example.pane.setPreferredSize(new Dimension(250, 250));
    example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));

    JFrame frame = new JFrame("Menu Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(example.menuBar);
    frame.getContentPane().add(example.pane, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}

****