Chitika

Tuesday, October 26, 2010

Fundemantals

Source code of the java program is first written in plain text files ending with the .java extension. When you compile the java program Those source files are then converted into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes

Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer.
Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS.


Identifiers and Keywords

The rules the compiler uses to determine whether a name is legal. 
  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers
Examples:
The following identifiers are legal

int _a;  //starting with underscore
int $c;  //starting with $ sign
int ______2_w;  //starting with underscore
int _$;       //starting with underscore
int this_is_a_very_detailed_name_for_an_identifier; // starting with a letter

The following identifiers are illegal

int :b; // starting letter is not valid
int -d; // starting letter is not valid
int e#; // special charactor # is not legal
int .f; // starting (.) is not valid
int 7g; //starting with number not allowed.

Java Keywords

You cannot use any of the following as identifiers in your programs

abstract   continue   for    new
switch    assert***    default   goto*
package    synchronized    boolean    do
if   private    this    break
double    implements    protected    throw
byte    else     import    public
case    enum****    instanceof    return
transient    catch    extends    int
short    try    char    final
interface    static    void    throws
class    finally    long    strictfp**
volatile    const*    float    native
super    while

* not used 
** added in 1.2 *** added in 1.4 **** added in 5.0

Through the Java VM, the same application is capable of running on multiple platforms.

Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS

Legal Identifiers

Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).

All the Java components —classes, variables, and methods—need names. In Java these names are called
there are rules for what constitutes a legal Java identifier.

Monday, September 13, 2010

Review Questions



  1. Write a java program to display your name on the command prompt
  2. Write a java program to display numbers from 1-10 using a for loop
  3. Write a java program to display numbers for a given range on the command prompt
    eg. Java NumDemo 12 30
    will display numbers starting from 12 to 30
  4. write a java program to sort and display a given number series as user arguments, and also display the maximum and the minimum in the series.
  5. Write a java program to find the mean and the median of a given number series as user arguments: (use two methods to find the two attributes and invoke them inside the main method)
  6. Write a java program to find the mode of a given number series as user arguments.
  7. Identify what are the java keywords from the followings
    a. abstract b. boolean c. interface d.public e. method f. subclasses
  8. Which one of these lists contains only Java programming language keywords? (Choose one.)
    A. class, if, void, long, Int, continue
    B. goto, instanceof, native, finally, default, throws
    C. try, virtual, throw, final, volatile, transient
    D. strictfp, constant, super, implements, do
    E. byte, break, assert, switch, include
  9. Which three are legal array declarations? (Choose three.)
    A. int [] myScores [];
    B. char [] myChars;
    C. int [6] myScores;
    D. Dog myDogs [];
    E. Dog myDogs [7];
  10. Which will legally declare, construct, and initialize an array? (Choose one.)
    A. int [] myList = {“1”, “2”, “3”};
    B. int [] myList = (5, 8, 2);
    C. int myList [] [] = {4,9,7,0};
    D. int myList [] = {4, 3, 7};
    E. int [] myList = [3, 5, 6];
    F. int myList [] = {4; 6; 5};
  11. What is the output of the following program
public class CharDemo{
    public static void main(String arg[]){
       char a = 'A';
       char b = (char)(a+1);
       System.out.println(a+b);
       System.out.println("a+b is "+a+b);
       int x = 75;
       char y = (char)x;
       char half = '\u00AC';
       System.out.println("Y is "+y+"and half is"+half);

       }
    } 

Wrte your answers in the comments area and submit
    Sample solutions

    1. public class NameDisplay{
        public static void main(String[] arg){
          System.out.println("Chaminda Wijesinghe");
        }
       }
    

    Write the above program on a notepad and
    Save the above program using the file name NameDisplay.java and filetype All Files
    Open command prompt and compile the program using "Javac NameDisplay.java"
    Run the program using  "Java DisplayName"

    2. public class NumberDisplay{
       public static void main(String[] arg){
         for(int i=1;i<=10;i++){
           System.out.println(""+i);
           } // end of for loop
        } //end of main method
        } // end of the class
    
    3. public class NumberDisplay2{
       public static void main(String[] arg){
    
       int i = Integer.parseInt(arg[0]);
       int j = Integer.parseInt(arg[1]);
     
       for(int x=i; x<=j; x++){
          System.out.println(""+x);
          }
      }
      }
    
    
    Sample Java Programms

    A program to display prime Numbers

    public class prime{
    private static boolean checkprime(int num)
     {
     boolean done = false;
     
      for(int i=2;i<num;i++)
      {
      if(num%i!=0)
        done=true;
      else
        return false;
      }
      return done;
     }
    public static void main(String[] arg)
     {
     for(int i=2;i<=100;i++)
      {
      if(checkprime(i))
      {
      System.out.println("prime "+i);
      }
      }
     }
    }
    A program to implement a Calculator

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class CalculatorApplet extends Applet implements ActionListener
    {
    private Button keysArray[];
    private Panel keyPad;
    private TextField lcdField;
    private double result;
    private boolean first;
    private boolean foundKey;
    static boolean clearText;
    private int prevOperator;
    public void init()
    {
      lcdField = new TextField(20);
      keyPad = new Panel ();
      keysArray = new Button[17];
      result = 0.0;
      prevOperator = 0;
      first = true;
      clearText = true;
      //Set frame layout manager setLayout(new BorderLayout());
      lcdField.setEditable(false);
      //Create buttons
      for (int i = 0; i <=9; i++)
       keysArray[i] = new Button(String.valueOf(i));
       keysArray[10] = new Button("/");
       keysArray[11] = new Button("*");
       keysArray[12] = new Button("-");
       keysArray[13] = new Button("+");
       keysArray[14] = new Button("=");
       keysArray[15] = new Button(".");
       keysArray[16] = new Button("CLR");

       //Set panel layout manager
       keyPad.setLayout(new GridLayout (4,4));
       //Add button to keyPad panel
       for (int i = 7; i <=10; i++) //adds Button 7,8,9, and divide to Panel
        keyPad.add(keysArray[i]);
       for (int i = 4; i <6; i++) //adds buttons 4,5,6 to Panel
        keyPad.add(keysArray[i]);
       keyPad.add(keysArray[11]); //adds multiply button to Panel
       for (int i = 1; i <= 3;i++) //adds buttons 1,2 and 3 to Panel
        keyPad.add(keysArray[i]);
       keyPad.add(keysArray[12]);//adds minus button to Panel
       keyPad.add(keysArray[0]); //adds 0 key to Panel
       for (int i = 15; i >=13; i--)
        keyPad.add(keysArray[i]); //adds decimal point, equal, and addition keys Panel
        add(lcdField, BorderLayout.NORTH); //adds text field to top of Frame
        add(keyPad, BorderLayout.CENTER); //adds Panel to center of Frame
        add(keysArray[16], BorderLayout.EAST); //adds Clear key to right side of applet
        for(int i = 0; i < keysArray.length; i++)
         keysArray[i].addActionListener(this);
     }
     public void actionPerformed(ActionEvent e)
     {
       foundKey = false;
       //Search for the key pressed
       for (int i = 0; i < keysArray.length && !foundKey; i++)
       if(e.getSource() == keysArray[i]) //key match found
       {
         foundKey = true;
         switch(i)
         {
         case 0: case 1: case 2: case 3: case 4: //number buttons
         case 5: case 6: case 7: case 8: case 9: //0-9
         case 15:
         if (clearText)
         {
         lcdField.setText("");
         clearText = false;
      }
      lcdField.setText(lcdField.getText() +
      keysArray[i].getLabel());
      break;
      case 10:// divide button
      case 11:// multiply button
      case 12:// minus button
      case 13:// plus button
      case 14:// equal button
        clearText = true;
        if (first) // First operand
        {
        if(lcdField.getText().length()==0)
         result = 0.0;
        else
         result = Double.valueOf(lcdField.getText()).doubleValue();
      first = false;
                    prevOperator = i; //save previous operator
         }
           else //second operand already enter, so calculator total
           {
       switch(prevOperator)
       {
       case 10: //divide Button
        result /= Double.valueOf(lcdField.getText()).
        doubleValue();
      break;
      case 11: //multiply Button
      result *= Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
      case 12: //minus button
      result -= Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
      case 13: //plus button
      result += Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
        }
        lcdField.setText(Double.toString(result));
        if (i==14)//equal button
         first = true;
        else
         prevOperator = i; //save previous opetator
         }
         break;
         case 16://Clear button
         clearText = true;
         first = true;
         lcdField.setText("");
         result = 0.0;
         prevOperator = 0;
         break;
         }
         }
        }
       }
    A program to display Candidate's preferencial votes as a Histogram
    import javax.swing.*;
    public class Histogram
         {
         public static void main( String args[] )
             {
             int n[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
             String output = "";
           
             output += "Canidate No\tVotes\tHistogram";
           
             for ( int i = 0; i < n.length; i++ )
                 {
                 output += "\n" + i + "\t" + n[ i ] + "\t";
               
                 for ( int j = 1; j <= n[ i ]; j++ ) // print a bar
                 output += "*";
             }
           
             JTextArea outputArea = new JTextArea( 11, 30 );
             outputArea.setText( output );
           
             JOptionPane.showMessageDialog( null, outputArea,"Histogram Printing Program",JOptionPane.INFORMATION_MESSAGE );
           
             System.exit( 0 );
         }
    }