Home arrow static arrow Java Programming [Archive] - objects and initialization.
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - objects and initialization.
This topic has 14 replies on 1 page.

Posts:130
Registered: 6/8/04
objects and initialization.  
Aug 1, 2004 10:08 PM



 
why can i not instansiate a global class object, then initialize it later in a member function?
I keep getting null pointer exceptions everytime i do this.
doesn't an instansiated class work as an address pointing to that object?
I get this even if i pass it to the function as a reference.
 

Posts:12,831
Registered: 2/22/00
Re: objects and initialization.  
Aug 1, 2004 10:21 PM (reply 1 of 14)



 
Can you give an example of what you mean?

It's certainly possible to do initialization in separate step from instantiation, although generally I think it's a mistake. (It's bad to create objects in an incomplete state. When initialization is separate from instantiation, that can happen.)

An object is an instantiated class. Some variables are references to objects.
 

Posts:5,965
Registered: 5/17/03
Re: objects and initialization.  
Aug 1, 2004 10:21 PM (reply 2 of 14)



 
why can i not instansiate a global class object, then
initialize it later in a member function?
I keep getting null pointer exceptions everytime i do
this.
doesn't an instansiated class work as an address
pointing to that object?
I get this even if i pass it to the function as a
reference.

If you do

MyObject o = new MyObject();

Then the reference variable o will contain a reference (pointer) to the newly created MyObject object. You should the be able to call methods in this object like,

o.myMethod();

If you get a null pointer exception then you've done something wrong. If you post some code maybe someone can help you spot it.
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 1, 2004 10:32 PM (reply 3 of 14)



 
working code
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.io.*; public class homeworkJava extends JFrame {    final int SIZE = 100;    Container container= getContentPane();   GridBagLayout layout= new GridBagLayout();   GridBagConstraints c= new GridBagConstraints();     Box box1 = Box.createVerticalBox();   Box box2 = Box.createVerticalBox();   Box box3 = Box.createVerticalBox();              JTextField commands = new JTextField(18);    JLabel GeneraLabel = new JLabel("Genera", JLabel.RIGHT);   JLabel RatingLabel = new JLabel("Rating", JLabel.RIGHT);   JLabel outputArea1Label = new JLabel("Details",JLabel.RIGHT);      JLabel picture = new JLabel();      JMenuBar bar = new JMenuBar();    JMenu fileMenu = new JMenu("File");   JMenu editMenu = new JMenu("Edit");    String DetailS[][] = new String[SIZE][SIZE];   String TableLabelS[]={"Title","Genera","Rating","Discription"};    String GeneraS[] = new String[SIZE];   String RatingS[] = new String[SIZE];       JTable jt = new JTable(DetailS,TableLabelS);   JScrollPane scrollableTable = new JScrollPane(jt);    File GeneraInputFile = new File   ("/home/buddha/code/homeworkJava/w_29_7_04","GeneraFile.txt");   File RatingInputFile = new File   ("/home/buddha/code/homeworkJava/w_29_7_04","RatingFile.txt");   File DetailsInputFile = new File   ("/home/buddha/code/homeworkJava/w_29_7_04","DetailsFile.txt");    public homeworkJava()   {      super("DVD Database");       setIconImage      (Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("sun.png")));       container.setLayout(layout);           readData(GeneraInputFile,GeneraS);          readData(RatingInputFile,RatingS);       readData(DetailsInputFile,DetailS);        updatePicture();       JComboBox GeneraCB = new JComboBox(GeneraS);      JComboBox RatingCB = new JComboBox(RatingS);       GeneraCB.setSelectedIndex(0);      RatingCB.setSelectedIndex(0);       GeneraCB.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event1)          {            JComboBox gcb = (JComboBox)event1.getSource();            String GeneraSelection = (String)gcb.getSelectedItem();            commands.setText(GeneraSelection);          }        }      );       RatingCB.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event2)          {            JComboBox rcb = (JComboBox)event2.getSource();            String RatingSelection = (String)rcb.getSelectedItem();            commands.setText(RatingSelection);          }        }      );       commands.setText("COMMANDS");               GeneraLabel.setLabelFor(GeneraCB);       RatingLabel.setLabelFor(RatingCB);             box1.add(GeneraLabel);      box1.add(GeneraCB);       box1.add(RatingLabel);      box1.add(RatingCB);       box2.add(picture);       box3.add(outputArea1Label);      box3.add(scrollableTable);          fileMenu.setMnemonic('F');      editMenu.setMnemonic('E');       JMenuItem OpenItem = new JMenuItem("Open");      OpenItem.setMnemonic('O');      OpenItem.setAccelerator      (        KeyStroke.getKeyStroke('O',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      fileMenu.add(OpenItem);      OpenItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Open Executed");          }        }      );               JMenuItem CloseItem = new JMenuItem("Close");      CloseItem.setMnemonic('C');      CloseItem.setAccelerator      (        KeyStroke.getKeyStroke('L',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      fileMenu.add(CloseItem);      CloseItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Close Executed");          }        }      );        JMenuItem SearchItem = new JMenuItem("Search");      SearchItem.setMnemonic('S');      SearchItem.setAccelerator      (        KeyStroke.getKeyStroke('S',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      fileMenu.add(SearchItem);      SearchItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Search Executed");          }        }      );             JMenuItem CutItem = new JMenuItem("Cut");      CutItem.setMnemonic('t');      CutItem.setAccelerator      (        KeyStroke.getKeyStroke('T',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      editMenu.add(CutItem);      CutItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Cut Executed");          }        }      );        JMenuItem CopyItem = new JMenuItem("Copy");      CopyItem.setMnemonic('y');      CopyItem.setAccelerator      (        KeyStroke.getKeyStroke('Y',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      editMenu.add(CopyItem);       CopyItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Copy Executed");          }        }      );                 JMenuItem PasteItem = new JMenuItem("Paste");      PasteItem.setMnemonic('P');      PasteItem.setAccelerator      (        KeyStroke.getKeyStroke('P',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)      );      editMenu.add(PasteItem);      PasteItem.addActionListener      (      	new ActionListener()        {          public void actionPerformed( ActionEvent event)          {            commands.setText("Paste Executed");          }        }      );        bar.add(fileMenu);      bar.add(editMenu);            bar.setBackground(Color.white);       box1.setBackground(Color.white);      box2.setBackground(Color.white);      box3.setBackground(Color.white);            container.setBackground(Color.white);              c.fill=GridBagConstraints.HORIZONTAL;      c.weightx=1;      c.weighty=1;      c.gridx=0;      c.gridy=0;      c.gridwidth=3;      container.add(commands,c);           c.fill=GridBagConstraints.NONE;      c.gridx=0;      c.gridy=1;      c.gridwidth=1;      container.add(box1,c);       c.gridx=2;      c.gridy=1;      c.gridwidth=0;      container.add(box2,c);                   c.fill=GridBagConstraints.BOTH;      c.gridx=0;      c.gridy=2;      c.gridheight=6;      c.gridwidth=3;      container.add(box3,c);       setJMenuBar(bar);      setSize(350,380);      setVisible(true);    }     public static void main(String args[])   {      homeworkJava application = new homeworkJava();      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   }    public void readData(File inputFile,String[] DataStorage)   {        int Count1=0;         try        {          BufferedReader in = new BufferedReader(new FileReader(inputFile));          String line;           while((line = in.readLine())!=null)          {            StringTokenizer tokens = new StringTokenizer(line);                    while(tokens.hasMoreTokens())              DataStorage[Count1++]=tokens.nextToken();          }        }        catch(FileNotFoundException e)        {          System.out.println("File is not accessable");        }        catch(IOException ioe)        {          System.out.println(ioe);        }    }     public void readData(File inputFile, String[][] DataStorage)    {        int Count1=0,Count2=0;         try        {          BufferedReader in = new BufferedReader(new FileReader(inputFile));          String line;           while((line = in.readLine())!=null)          {            StringTokenizer tokens = new StringTokenizer(line," ",false);                    while(tokens.hasMoreTokens())              DataStorage[Count2][Count1++]=tokens.nextToken(); 	    Count1=0;			    Count2++;          }        }        catch(FileNotFoundException e)        {          System.out.println("File is not accessable");        }        catch(IOException ioe)        {          System.out.println(ioe);        }    }     public void updatePicture()//pass the string we will use for the wiki/./.gif    {      ImageIcon icon = new ImageIcon      ("/home/buddha/code/homeworkJava/w_29_7_04/picture.gif");      //ImageIcon icon = wiki/./createImageIcon("/"+name+".gif");       picture.setIcon(icon);               if (icon != null)      {        picture.setText(null);      }      else      {        picture.setText("Image not found");      }    }} 

nullpointer exception not working code
[code]

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

public class CleanedUp extends JFrame
{
final int SIZE = 100;

Container container;
GridBagLayout layout;
GridBagConstraints c;

Box box1;
Box box2;
Box box3;

JTextField commands;

JLabel GeneraLabel;
JLabel RatingLabel;
JLabel outputArea1Label;
JLabel picture;

JMenuBar bar;
JMenu fileMenu;
JMenu editMenu;
JMenuItem OpenItem;
JMenuItem CloseItem;
JMenuItem SearchItem;
JMenuItem CutItem;
JMenuItem CopyItem;
JMenuItem PasteItem;

JComboBox GeneraCB;
JComboBox RatingCB;

JTable jt;
JScrollPane scrollableTable;

String DetailS[][] = new String[SIZE][SIZE];
String TableLabelS[] = {"Title","Genera","Rating","Discription"};
String GeneraS[] = new String[SIZE];
String RatingS[] = new String[SIZE];

File GeneraInputFile;
File RatingInputFile;
File DetailsInputFile;

public CleanedUp()
{
super("DVD Database");

SetProgramIcon();

InitializeFiles();

readData(GeneraInputFile,GeneraS);
readData(RatingInputFile,RatingS);
readData(DetailsInputFile,DetailS);

UpdatePicture();
InitializeBoxs();
InitializeLabels();
InitializeTextFields();
InitializeMenu();
InitializeComboBox();
InitializeTable();
InitializeContainerAndConstraints();

setSize(350,380);
setVisible(true);
}

public static void main(String args[])
{
CleanedUp application = new CleanedUp();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void SetProgramIcon()
{
setIconImage
(
Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("wiki/./sun.png"))
);
}

public void InitializeFiles()
{
GeneraInputFile = new File("/home/buddha/code/homeworkJava","GeneraFile.txt");
RatingInputFile = new File("/home/buddha/code/homeworkJava","RatingFile.txt");
DetailsInputFile = new File("/home/buddha/code/homeworkJava","DetailsFile.txt");
}

public void InitializeTable()
{
jt = new JTable(DetailS,TableLabelS);
scrollableTable = new JScrollPane(jt);
}

public void InitializeBoxs()
{
box1 = Box.createVerticalBox();
box2 = Box.createVerticalBox();
box3 = Box.createVerticalBox();

box1.add(GeneraLabel);
box1.add(GeneraCB);
box1.add(RatingLabel);
box1.add(RatingCB);
box2.add(picture);
box3.add(outputArea1Label);
box3.add(scrollableTable);

box1.setBackground(Color.white);
box2.setBackground(Color.white);
box3.setBackground(Color.white);
}

public void InitializeLabels()
{
GeneraLabel = new JLabel("Genera", JLabel.RIGHT);
RatingLabel = new JLabel("Rating", JLabel.RIGHT);
outputArea1Label = new JLabel("Details",JLabel.RIGHT);

picture = new JLabel();

GeneraLabel.setLabelFor(GeneraCB);
RatingLabel.setLabelFor(RatingCB);
}

public void InitializeTextFields()
{
commands = new JTextField(18);
commands.setText("COMMANDS");
}

public void InitializeContainerAndConstraints()
{
container = getContentPane();
layout = new GridBagLayout();
c = new GridBagConstraints();

container.setLayout(layout);

container.setBackground(Color.white);

c.fill=GridBagConstraints.HORIZONTAL;
c.weightx=1;
c.weighty=1;
c.gridx=0;
c.gridy=0;
c.gridwidth=3;
container.add(commands,c);

c.fill=GridBagConstraints.NONE;
c.gridx=0;
c.gridy=1;
c.gridwidth=1;
container.add(box1,c);

c.gridx=2;
c.gridy=1;
c.gridwidth=0;
container.add(box2,c);

c.fill=GridBagConstraints.BOTH;
c.gridx=0;
c.gridy=2;
c.gridheight=6;
c.gridwidth=3;
container.add(box3,c);
}

public void InitializeComboBox()
{
GeneraCB = new JComboBox(GeneraS);
RatingCB = new JComboBox(RatingS);

GeneraCB.setSelectedIndex(0);
RatingCB.setSelectedIndex(0);

GeneraCB.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event1)
{
JComboBox gcb = (JComboBox)event1.getSource();
String GeneraSelection = (String)gcb.getSelectedItem();
commands.setText(GeneraSelection);
}
}
);

RatingCB.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event2)
{
JComboBox rcb = (JComboBox)event2.getSource();
String RatingSelection = (String)rcb.getSelectedItem();
commands.setText(RatingSelection);
}
}
);
}

public void InitializeMenu()
{
bar = new JMenuBar();

fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');

editMenu = new JMenu("Edit");
editMenu.setMnemonic('E');

OpenItem = new JMenuItem("Open");
OpenItem.setMnemonic('O');
OpenItem.setAccelerator
(
KeyStroke.getKeyStroke
(
'O',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false
)
);
fileMenu.add(OpenItem);
OpenItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Open Executed");
}
}
);

CloseItem = new JMenuItem("Close");
CloseItem.setMnemonic('C');
CloseItem.setAccelerator
(
KeyStroke.getKeyStroke('L',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)
);
fileMenu.add(CloseItem);
CloseItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Close Executed");
}
}
);

SearchItem = new JMenuItem("Search");
SearchItem.setMnemonic('S');
SearchItem.setAccelerator
(
KeyStroke.getKeyStroke('S',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)
);
fileMenu.add(SearchItem);
SearchItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Search Executed");
}
}
);

CutItem = new JMenuItem("Cut");
CutItem.setMnemonic('t');
CutItem.setAccelerator
(
KeyStroke.getKeyStroke('T',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)
);
editMenu.add(CutItem);
CutItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Cut Executed");
}
}
);

CopyItem = new JMenuItem("Copy");
CopyItem.setMnemonic('y');
CopyItem.setAccelerator
(
KeyStroke.getKeyStroke('Y',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)
);
editMenu.add(CopyItem);
CopyItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Copy Executed");
}
}
);

PasteItem = new JMenuItem("Paste");
PasteItem.setMnemonic('P');
PasteItem.setAccelerator
(
KeyStroke.getKeyStroke('P',Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false)
);
editMenu.add(PasteItem);
PasteItem.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
commands.setText("Paste Executed");
}
}
);

bar.add(fileMenu);
bar.add(editMenu);

bar.setBackground(Color.white);

setJMenuBar(bar);
}

public void readData(File inputFile,String[] DataStorage)
{
int Count1=0;

try
{
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String line;

while((line = in.readLine())!=null)
{
StringTokenizer tokens = new StringTokenizer(line);

while(tokens.hasMoreTokens())
DataStorage[Count1++]=tokens.nextToken();
}
}
catch(FileNotFoundException e)
{
System.out.println("File is not accessable");
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}

public void readData(File inputFile, String[][] DataStorage)
{
int Count1=0,Count2=0;

try
{
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String line;

while((line = in.readLine())!=null)
{
StringTokenizer tokens = new StringTokenizer(line," ",false);

while(tokens.hasMoreTokens())
DataStorage[Count2][Count1++]=tokens.nextToken();

Count1=0;
Count2++;
}
}
catch(FileNotFoundException e)
{
System.out.println("File is not accessable");
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}

public void UpdatePicture()//pass the string we will use for the wiki/./.gif
{
ImageIcon icon = new ImageIcon("wiki/.//home/buddha/code/homeworkJava/picture.gif");
//ImageIcon icon = createImageIcon("/"name"wiki/./.gif");

picture.setIcon(icon);

if (icon != null)
{
picture.setText(null);
}
else
{
picture.setText("Image not found");
}
}
}

[\code]
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 1, 2004 10:32 PM (reply 4 of 14)



 
sorry for just slapping a lot of code down.
 

Posts:12,831
Registered: 2/22/00
Re: objects and initialization.  
Aug 1, 2004 10:39 PM (reply 5 of 14)



 
You don't really need to post every single line of code.

That error message did you get? It should actually give the line number where the NullPointerException occurred.
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 1, 2004 10:51 PM (reply 6 of 14)



 
I posted above on my prior post the working version of the program and the modified version that acquires the null pointer exception. Below is one of the null pointer exceptions.

[code]public void UpdatePicture()//pass the string we will use for the wiki/./.gif
{
ImageIcon icon = new ImageIcon("wiki/.//home/buddha/code/homeworkJava/picture.gif");

picture.setIcon(icon);

if (icon != null)
{
picture.setText(null);
}
else
{
picture.setText("Image not found");
}
}[\code]
 

Posts:5,965
Registered: 5/17/03
Re: objects and initialization.  
Aug 2, 2004 12:12 AM (reply 7 of 14)



 
It's seems you're calling UpdatePicture() before you're calling InitializeLabels(). This means picture is null when it's used. You can check that by putting in a trace.
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 2, 2004 8:23 PM (reply 8 of 14)



 
sorry for a newbie question, but what is a trace?
Do you mean to step through the program, or is there another way to put in a trace?
 

Posts:5,965
Registered: 5/17/03
Re: objects and initialization.  
Aug 2, 2004 8:37 PM (reply 9 of 14)



 
A trace is just a print statement. You put them into your code to follow the execution path of the program and print relevant data along the way.

Anyway the problem seems to be in the CleanedUp() constructor. UpdatePicture() is called before InitializeLabels(). This means picture will be null and throw the exception.
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 2, 2004 8:37 PM (reply 10 of 14)



 
UlrikaJ ,
Thanks for the help.
I didn't notice that I was calling my functions in an invalid order.
That clue helped me fix the remainder of the null pointer exceptions I was having.
You Rock.
X
 

Posts:12,831
Registered: 2/22/00
Re: objects and initialization.  
Aug 2, 2004 9:09 PM (reply 11 of 14)



 

Sometimes when a person says "trace" they also mean a stack trace. That's a list of the execution stack frames, from the first method called (e.g. main(String[] argv)) to the last method called before the exception happened. (Except that often the stack trace is truncated to the last 10 or 20 or so elements.)
 

Posts:130
Registered: 6/8/04
Re: objects and initialization.  
Aug 2, 2004 9:12 PM (reply 12 of 14)



 
can you expand on that,
I feel really dumb, because I'm not following to well.
Stack trace?
I know what a stack is, and I think I know what a trace is, but stack trace is really confusing me.
 

Posts:5,965
Registered: 5/17/03
Re: objects and initialization.  
Aug 2, 2004 9:26 PM (reply 13 of 14)



 
Stack trace?

You got a stack trace when the null exception message was printed. The list of method calls leading up to the method with the error is a call stack trace.
 

Posts:12,831
Registered: 2/22/00
Re: objects and initialization.  
Aug 2, 2004 9:27 PM (reply 14 of 14)



 

When you run a program, the OS (or JVM for java programs) creates some space in memory for the execution stack. This is a special stack that tracks the invocation of methods or functions.

Every time you invoke a method, a frame (some information about the method call) is pushed on the stack. When the method returns, that frame is popped off the stack.

This is why, when one method invokes another, the variables used in the first method don't disappear when the second method starts running. They're being held on the stack.

This is also why poorly-written recursive methods can produce stack overflow errors (or are they just OutOfMemory exceptions in java? I forget) -- it's because each time the method recurses, another frame is pushed on the stack, and eventually the thread or process runs out of space in memory. A properly written recursive method will terminate before this happens.

So when there's an exception thrown in java, and you call Exception.printStackTrace (or something else calls it for you), you see the last several methods that were called. This information comes from the "stack trace" -- the last few frames on the execution stack.
 
This topic has 14 replies on 1 page.