I have a program with arrays declared in the main function. However, when I want to use that array in my init() function, it doesn't work. May I know what must be done so that I can use my arrays in the init() function?

it doesn't work.

Probably 20 different ways to code it so it "doesn't work".
Can you tell us which one you've used?
Its probably the local variable problem. Move the definition of the array outside of the method.

Copy and paste here the full text of any error messages.

The error message is:

Exception in thread "main" java.lang.NullPointerException
at Align.strip<DynamicProgramming.java:481>
at Align.<init><DynamicProgramming.java:466>
at AlignSimple.<init><DynamicProgramming.java:575>
at NW.<init><DynamicProgramming.java:638>
at MatchApplet.init<MatchApplet.java:376>
at MatchApplet.main<MatchApplet.java:72>

Do you know what is the error?

An object reference variable at line 481 in DynamicProgramming is null.
Look at that line of code and see what variable and then look to see why it is null.

Is the init() method is called from main function? If yes, pass the array to that init() method.

I have a program with arrays declared in the main function. However, when I want to use that array in my init() function, it doesn't work. May I know what must be done so that I can use my arrays in the init() function?

From the errors I assume that we are dealing with Applets so there shouldn't be any main method. If you want to use something anywhere then declare it, create it and initialize it.

Without some code to go with the errors it is difficult to suggest anything than speculations

This is the code:

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DynamicProgramming extends JApplet {



	TextArea outputArea;
	//JButton button;
	//JButton reset;

	//JTextField tF1;
	//JTextField tF2;

	//JLabel l1;
	//JLabel l2;

	String s1;
	String s2;
	
	public static BufferedReader input, input2;	
	public static String[] store = new String [10000];
	public static String[] store2 = new String [10000];  
	public static int z=0;
	public static int z2=0;

	public static void main(String[] args)
	{
		//Application for program
  		Frame f = new Frame();
  		f.addWindowListener(new java.awt.event.WindowAdapter()
  		{
       	public void windowClosing(java.awt.event.WindowEvent e)
       	{
       	System.exit(0);
      	};
     	});

  		MatchApplet ut = new MatchApplet();
  		ut.setSize(900,900); // same size as defined in the HTML APPLET
  		f.add(ut);
  		f.pack();
  		ut.init();
  		f.setSize(900,900 + 100); // add 20, seems enough for the Frame title,
  		f.show();
  		
  		//end of application for program
  		
  		
  		
  		int j=0, h=0, i=0;
		
			String[] counter3 = new String [10000];
			String[] counter4 = new String [10000];
			String[] counter1 = new String [10000];
			String[] counter5 = new String [10000];
			String[] counter6 = new String [10000];	 
			String[] counter7 = new String [10000]; 	
			
			
			
	  
	try{	//extract sequence 1
      
      input = new BufferedReader(new FileReader( new File("D:\\project1\\Dynamic Programming\\Alignment Algorithms\\Sequence Testing\\1a00.gz.txt") ) );	// input specified file
      String extract;
      while ( ( extract = input.readLine() ) != null ) 			//reading specified file
      {
      	
      	if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H"))) 		//extract lines that starts with ATOM AND end with anything but H
      	{
			StringTokenizer s = new StringTokenizer(extract," ");		//String tokenizer
      		int counter=0;
      
      	while(s.hasMoreTokens())
      	{
      	 	
      		String ss = s.nextToken();
     		counter++;
      
      		if (counter == 3) 						//extracts 3rd tokens of each line	
 			counter3[j] = ss;			
      												     		
			if(counter == 4)						//extracts 4th tokens of each line
			counter4[h] = ss;     		
      		
      	}// end of while(s.hasMoreTokens())

		    counter1[i] = counter3[j] +"\t"+ counter4[h];    

		    if (counter1[i].trim().startsWith("CA")) 
		    {
	
      		StringTokenizer a = new StringTokenizer(counter1[i],"\t");
      		int amino=0;
      		
      			while(a.hasMoreTokens())
      			{
      	 		
      			String aa = a.nextToken();
     			amino++;
     		
     				if (amino == 2)
     				{	   		     					
						//int z=0;
						  				    	
      					if(aa.trim().startsWith("ALA"))
      					store [z] = "A";  			
     					if(aa.trim().startsWith("ARG"))
      		    		store [z] = "R";
      					if(aa.trim().startsWith("ASN"))
      	      			store [z] = "N";
      					if(aa.trim().startsWith("ASP"))
      					store [z] = "D";
      					if(aa.trim().startsWith("CYS"))
      					store [z] = "C";
      					if(aa.trim().startsWith("GLN"))
      					store [z] = "Q";      			
      					if(aa.trim().startsWith("GLU"))
      					store [z] = "E";
      					if(aa.trim().startsWith("GLY"))
      					store [z] = "G";    
      					if(aa.trim().startsWith("HIS"))
      					store [z] = "H";      			
      					if(aa.trim().startsWith("ILE"))
      					store [z] = "I";
      					if(aa.trim().startsWith("LEU"))
       					store [z] = "L";     			
      					if(aa.trim().startsWith("LYS"))
        				store [z] = "K";    			
      					if(aa.trim().startsWith("MET"))
          				store [z] = "M";  			
      					if(aa.trim().startsWith("PHE"))
         				store [z] = "F";   			      			
      					if(aa.trim().startsWith("PRO"))
        				store [z] = "P";    			
      					if(aa.trim().startsWith("SER"))
        				store [z] = "S";    			
      					if(aa.trim().startsWith("THR"))
        				store [z] = "T";    			
      					if(aa.trim().startsWith("TRP"))
        				store [z] = "W";    			
      					if(aa.trim().startsWith("TYR"))
        				store [z] = "Y";    			
      					if(aa.trim().startsWith("VAL"))
      					store [z] = "V"; 	
      			
      		
      					System.out.print(store[z]);
      					
				
					}//end of if (amino == 2)
					
		
				}//end of while(a.hasMoreTokens())
		
      		
      		}//end of if (counter1[i].trim().startsWith("CA"))	    	
		
														
      	}//end of if ((extract.trim().startsWith("ATOM") && !extract.trim().endsWith("H")))
      	    			
 	    			
      }//end of while ( ( extract = input.readLine() ) != null )
      
      		
			input.close();
			
	}catch( IOException ioException ) {}
	
	
	
	System.out.println("\n");
	
	
	
	
	try{	//extracting sequence 2
      
      input2 = new BufferedReader(new FileReader( new File("D:\\project1\\Dynamic Programming\\Alignment Algorithms\\Sequence Testing\\1a0a.gz.txt") ) );	// input specified file
      String extract2;
      while ( ( extract2 = input2.readLine() ) != null ) 			//reading specified file
      {
      	
      	if ((extract2.trim().startsWith("ATOM") && !extract2.trim().endsWith("H"))) 		//extract lines that starts with ATOM AND end with anything but H
      	{
			StringTokenizer s2 = new StringTokenizer(extract2," ");		//String tokenizer
      		int counter2=0;
      
      	while(s2.hasMoreTokens())
      	{
      	 	
      		String ss2 = s2.nextToken();
     		counter2++;
      
      		if (counter2 == 3) 						//extracts 3rd tokens of each line	
 			counter5[j] = ss2;			
      												     		
			if(counter2 == 4)						//extracts 4th tokens of each line
			counter6[h] = ss2;     		
      		
      	}// end of while(s.hasMoreTokens())

		    counter7[i] = counter5[j] +"\t"+ counter6[h];    

		    if (counter7[i].trim().startsWith("CA")) 
		    {
	
      		StringTokenizer a2 = new StringTokenizer(counter7[i],"\t");
      		int amino2=0;
      		
      			while(a2.hasMoreTokens())
      			{
      	 		
      			String aa2 = a2.nextToken();
     			amino2++;
     		
     				if (amino2 == 2)
     				{	   		
     					//int z=0;						
						      	
      					if(aa2.trim().startsWith("ALA"))
      					store2 [z] = "A";  			
     					if(aa2.trim().startsWith("ARG"))
      		    		store2 [z] = "R";
      					if(aa2.trim().startsWith("ASN"))
      	      			store2 [z] = "N";
      					if(aa2.trim().startsWith("ASP"))
      					store2 [z] = "D";
      					if(aa2.trim().startsWith("CYS"))
      					store2 [z] = "C";
      					if(aa2.trim().startsWith("GLN"))
      					store2 [z] = "Q";      			
      					if(aa2.trim().startsWith("GLU"))
      					store2 [z] = "E";
      					if(aa2.trim().startsWith("GLY"))
      					store2 [z] = "G";    
      					if(aa2.trim().startsWith("HIS"))
      					store2 [z] = "H";      			
      					if(aa2.trim().startsWith("ILE"))
      					store2 [z] = "I";
      					if(aa2.trim().startsWith("LEU"))
       					store2 [z] = "L";     			
      					if(aa2.trim().startsWith("LYS"))
        				store2 [z] = "K";    			
      					if(aa2.trim().startsWith("MET"))
          				store2 [z] = "M";  			
      					if(aa2.trim().startsWith("PHE"))
         				store2 [z] = "F";   			      			
      					if(aa2.trim().startsWith("PRO"))
        				store2 [z] = "P";    			
      					if(aa2.trim().startsWith("SER"))
        				store2 [z] = "S";    			
      					if(aa2.trim().startsWith("THR"))
        				store2 [z] = "T";    			
      					if(aa2.trim().startsWith("TRP"))
        				store2 [z] = "W";    			
      					if(aa2.trim().startsWith("TYR"))
        				store2 [z] = "Y";    			
      					if(aa2.trim().startsWith("VAL"))
      					store2 [z] = "V"; 	
      			
      		
      					System.out.print(store2[z]);
      					
				
					}//end of if (amino2 == 2)
					
		
				}//end of while(a2.hasMoreTokens())
		
      		
      		}//end of if (counter7[i].trim().startsWith("CA"))	    	
		
														
      	}//end of if ((extract2.trim().startsWith("ATOM") && !extract2.trim().endsWith("H")))
      	    			
 	    			
      }//end of while ( ( extract2 = input2.readLine() ) != null )
      
      		
			input2.close();
			
	}catch( IOException ioException ) {}
  		
		
  		
	}//end of public static void main(String[] args)
  	
  	

  public void init(){
  	

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

		outputArea = new TextArea(40,110);
		Font font = new Font("Courier", Font.PLAIN, 12);
		outputArea.setFont(font);
		outputArea.setEditable(false);

		//button = new JButton("Compute alignment");
		//reset = new JButton(" Reset ");

		//tF1 = new JTextField(70);
		//tF2 = new JTextField(70);		

		//l1 = new JLabel("Enter Seq1:");
		//l2 = new JLabel("Enter Seq2:");


		//c.add(l1);
		//c.add(tF1);
		//c.add(l2);
		//c.add(tF2);
		//c.add(button);
		//c.add(reset);
		c.add(outputArea);

	

	final Substitution sub = new Blosum50();
	//button.addActionListener(new ActionListener()
	//{
		//public void actionPerformed(ActionEvent e)
		//{

		//s1 += tF1.getText();
		//s2 += tF2.getText();
		
		s1 = store[z];
		s2 = store[z2];
		Output out = new Output ()
		{
	  		public void print(String s)
	  		{ outputArea.append(s); }

	  		public void println(String s)
	  		{ outputArea.append(s); outputArea.append("\n"); }

	  		public void println()
	  		{ outputArea.append("\n"); }
		};

	outputArea.setText("");
      (new NW      (sub, 8,     s1, s2)).domatch(out, "GLOBAL ALIGNMENT");
      (new SW      (sub, 8,     s1, s2)).domatch(out, "LOCAL ALIGNMENT");
		//};
	//});


  }//end of init()
}//end of class




// The class of substitution (scoring) matrices

abstract class Substitution1 {
  public int[][] score;

  void buildscore(String residues, int[][] residuescores) {
    // Allow lowercase and uppercase residues (ASCII code <= 127):
    score = new int[127][127];
    for (int i=0; i<residues.length(); i++) {
      char res1 = residues.charAt(i);
      for (int j=0; j<=i; j++) {
        char res2 = residues.charAt(j);
        score[res1][res2] = score[res2][res1]
	  = score[res1][res2+32] = score[res2+32][res1]
	  = score[res1+32][res2] = score[res2][res1+32]
	  = score[res1+32][res2+32] = score[res2+32][res1+32]
	  = residuescores[i][j];
      }
    }
  }

  abstract public String getResidues();
}


// The BLOSUM50 substitution matrix for amino acids (Durbin et al, p 16)

class Blosum50 extends Substitution {

  private String residues = "ARNDCQEGHILKMFPSTWYV";

  public String getResidues()
  { return residues; }

  private int[][] residuescores =
            /* A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V */
  { /* A */ {  5                                                          },
    /* R */ { -2, 7                                                       },
    /* N */ { -1,-1, 7                                                    },
    /* D */ { -2,-2, 2, 8                                                 },
    /* C */ { -1,-4,-2,-4,13                                              },
    /* Q */ { -1, 1, 0, 0,-3, 7                                           },
    /* E */ { -1, 0, 0, 2,-3, 2, 6                                        },
    /* G */ {  0,-3, 0,-1,-3,-2,-3, 8                                     },
    /* H */ { -2, 0, 1,-1,-3, 1, 0,-2,10                                  },
    /* I */ { -1,-4,-3,-4,-2,-3,-4,-4,-4, 5                               },
    /* L */ { -2,-3,-4,-4,-2,-2,-3,-4,-3, 2, 5                            },
    /* K */ { -1, 3, 0,-1,-3, 2, 1,-2, 0,-3,-3, 6                         },
    /* M */ { -1,-2,-2,-4,-2, 0,-2,-3,-1, 2, 3,-2, 7                      },
    /* F */ { -3,-3,-4,-5,-2,-4,-3,-4,-1, 0, 1,-4, 0, 8                   },
    /* P */ { -1,-3,-2,-1,-4,-1,-1,-2,-2,-3,-4,-1,-3,-4,10                },
    /* S */ {  1,-1, 1, 0,-1, 0,-1, 0,-1,-3,-3, 0,-2,-3,-1, 5             },
    /* T */ {  0,-1, 0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1, 2, 5          },
    /* W */ { -3,-3,-4,-5,-5,-1,-3,-3,-3,-3,-2,-3,-1, 1,-4,-4,-3,15       },
    /* Y */ { -2,-1,-2,-3,-3,-1,-2,-3, 2,-1,-1,-2, 0, 4,-3,-2,-2, 2, 8    },
    /* V */ {  0,-3,-3,-4,-1,-3,-3,-4,-4, 4, 1,-3, 1,-1,-3,-2, 0,-3,-1, 5 }
            /* A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V */
  };

  public Blosum50()
  { buildscore(residues, residuescores); }
}



// Pairwise sequence alignment

abstract class Align {
  Substitution sub;             // substitution matrix
  int d;                        // gap cost
  String seq1, seq2;            // the sequences
  int n, m;                     // their lengths
  Traceback B0;                 // the starting point of the traceback

  final static int NegInf = Integer.MIN_VALUE/2; // negative infinity

  public Align(Substitution sub, int d, String seq1, String seq2) {
    this.sub = sub;
    this.seq1 = strip(seq1); this.seq2 = strip(seq2);
    this.d = d;
    this.n = this.seq1.length(); this.m = this.seq2.length();
  }

  public String strip(String s) {
    boolean[] valid = new boolean[127];
    String residues = sub.getResidues();
    for (int i=0; i<residues.length(); i++) {
      char c = residues.charAt(i);
      if (c < 96)
	valid[c] = valid[c+32] = true;
      else
	valid[c-32] = valid[c] = true;
    }
    StringBuffer res = new StringBuffer(s.length());
    for (int i=0; i<s.length(); i++)
      if (valid[s.charAt(i)])
	res.append(s.charAt(i));
    return res.toString();
  }

  // Return two-element array containing an alignment with maximal score

  public String[] getMatch() {
    StringBuffer res1 = new StringBuffer();
    StringBuffer res2 = new StringBuffer();
    Traceback tb = B0;
    int i = tb.i, j = tb.j;
    while ((tb = next(tb)) != null) {
      if (i == tb.i)
        res1.append('-');
      else
        res1.append(seq1.charAt(i-1));
      if (j == tb.j)
        res2.append('-');
      else
        res2.append(seq2.charAt(j-1));
      i = tb.i; j = tb.j;
    }
    String[] res = { res1.reverse().toString(), res2.reverse().toString() };
    return res;
  }

  public String fmtscore(int val) {
    if (val < NegInf/2)
      return "-Inf";
    else
      return Integer.toString(val);
  }

  // Print the score, the F matrix, and the alignment
  public void domatch(Output out, String msg, boolean udskrivF) {
    out.println(msg + ":");
    out.println("Score = " + getScore());
    if (udskrivF) {
      out.println("The F matrix:");
      printf(out);
    }
    out.println("An optimal alignment:");
    String[] match = getMatch();
    out.println(match[0]);
    out.println(match[1]);
    out.println();
  }

  public void domatch(Output out, String msg)
  { domatch(out, msg, true); }

  // Get the next state in the traceback
  public Traceback next(Traceback tb)
  { return tb; }                // dummy implementation for the `smart' algs.

  // Return the score of the best alignment
  public abstract int getScore();

  // Print the matrix (matrices) used to compute the alignment
  public abstract void printf(Output out);

  // Auxiliary functions
  static int max(int x1, int x2)
  { return (x1 > x2 ? x1 : x2); }

  static int max(int x1, int x2, int x3)
  { return max(x1, max(x2, x3)); }

  static int max(int x1, int x2, int x3, int x4)
  { return max(max(x1, x2), max(x3, x4)); }

  static String padLeft(String s, int width) {
    int filler = width - s.length();
    if (filler > 0) {           // and therefore width > 0
      StringBuffer res = new StringBuffer(width);
      for (int i=0; i<filler; i++)
        res.append(' ');
      return res.append(s).toString();
    } else
      return s;
  }
}


// Alignment with simple gap costs

abstract class AlignSimple extends Align {
  int[][] F;                    // the matrix used to compute the alignment
  Traceback2[][] B;             // the traceback matrix

  public AlignSimple(Substitution sub, int d, String seq1, String seq2) {
    super(sub, d, seq1, seq2);
    F = new int[n+1][m+1];
    B = new Traceback2[n+1][m+1];
  }

  public Traceback next(Traceback tb) {
    Traceback2 tb2 = (Traceback2)tb;
    return B[tb2.i][tb2.j];
  }

  public int getScore()
  { return F[B0.i][B0.j]; }

  public void printf(Output out) {
    for (int j=0; j<=m; j++) {
      for (int i=0; i<F.length; i++)
	out.print(padLeft(fmtscore(F[i][j]), 5));
      out.println();
    }
  }
}


// Traceback objects

abstract class Traceback {
  int i, j;                     // absolute coordinates
}


// Traceback2 objects for simple gap costs

class Traceback2 extends Traceback {
  public Traceback2(int i, int j)
  { this.i = i; this.j = j; }
}


// Auxiliary classes for output

abstract class Output {
  public abstract void print(String s);
  public abstract void println(String s);
  public abstract void println();
}

class SystemOut extends Output {
  public void print(String s)
  { System.out.print(s); }

  public void println(String s)
  { System.out.println(s); }

  public void println()
  { System.out.println(); }
}


// Global alignment with the Needleman-Wunsch algorithm (simple gap costs)

class NW extends AlignSimple {

  public NW(Substitution sub, int d, String sq1, String sq2) {
    super(sub, d, sq1, sq2);
    int n = this.n, m = this.m;
    int[][] score = sub.score;
    for (int i=1; i<=n; i++) {
      F[i][0] = -d * i;
      B[i][0] = new Traceback2(i-1, 0);
    }
    for (int j=1; j<=m; j++) {
      F[0][j] = -d * j;
      B[0][j] = new Traceback2(0, j-1);
    }
    for (int i=1; i<=n; i++)
      for (int j=1; j<=m; j++) {
        int s = score[seq1.charAt(i-1)][seq2.charAt(j-1)];
        int val = max(F[i-1][j-1]+s, F[i-1][j]-d, F[i][j-1]-d);
        F[i][j] = val;
        if (val == F[i-1][j-1]+s)
          B[i][j] = new Traceback2(i-1, j-1);
        else if (val == F[i-1][j]-d)
          B[i][j] = new Traceback2(i-1, j);
        else if (val == F[i][j-1]-d)
          B[i][j] = new Traceback2(i, j-1);
        else
          throw new Error("NW 1");
      }
    B0 = new Traceback2(n, m);
  }
}


// Local alignment with the Smith-Waterman algorithm (simple gap costs)

class SW extends AlignSimple {
  public SW(Substitution sub, int d, String sq1, String sq2) {
    super(sub, d, sq1, sq2);
    int n = this.n, m = this.m;
    int[][] score = sub.score;
    int maxi = n, maxj = m;
    int maxval = NegInf;
    for (int i=1; i<=n; i++)
      for (int j=1; j<=m; j++) {
        int s = score[seq1.charAt(i-1)][seq2.charAt(j-1)];
        int val = max(0, F[i-1][j-1]+s, F[i-1][j]-d, F[i][j-1]-d);
        F[i][j] = val;
        if (val == 0)
          B[i][j] = null;
        else if (val == F[i-1][j-1]+s)
          B[i][j] = new Traceback2(i-1, j-1);
        else if (val == F[i-1][j]-d)
          B[i][j] = new Traceback2(i-1, j);
        else if (val == F[i][j-1]-d)
          B[i][j] = new Traceback2(i, j-1);
        else
          throw new Error("SW 1");
        if (val > maxval) {
          maxval = val;
          maxi = i; maxj = j;
        }
      }
    B0 = new Traceback2(maxi, maxj);
  }
}

There are many null values being passed to many constructors in your code.
Try debugging your code by adding println("arg=" + arg) statements to show ALL the values of args being passed to all the class constructors.
Then back track to see why those variables are null.

I don't really get you. Erm, meaning using System.out.println("arg=" + arg); ? I tried doing this, but there is error saying cannot find variable symbol arg.

Sorry, it is necessary for you to look at your code and see the names of the args that are used in each constructor and replace the word 'arg' with the names from your program. In serveral constructors there is more than one arg so you need to add to the println() statement to include them all.

For example take this constructor:
public NW(Substitution sub, int d, String sq1, String sq2) {
Add this line after the above:
System.out.println("sub=" + sub + ", sq1=" + sq1 + ", sq2=" +sq2); // show args

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.