Printing Object Values In Java - java

With the code
package items;
public class itemtest {
static itemobject[] item = new items[10];
{
items[0] = new Toy("Example ID","Example Desc");
items[1] = new Toy("Second Example ID", " Second Example Desc");
}
public static void main(String[] args)
{
String tid = items[0].exampleiD;
System.out.print(tid);
}
}
I get the error :
Exception in thread "main" java.lang.NullPointerException at items.itemtest.main(itemtest.java:17)
on the code line: String tid = item[0].exampleID;
Sorry I'm very new to java, could anyone shed some light on what I'm doing wrong ?

{
items[0] = new Toy("Example ID","Example Desc");
items[1] = new Toy("Second Example ID", " Second Example Desc");
}
You need to precede this block with the word static to have it take effect when the class is loaded -- which is what you actually want to happen, based on your code -- as opposed to when a new instance of itemobject is created, which never happens in your code.

From your code snippet I assume that you think you are trying to do the following:
Declare an array of items
Initialize the the first two items with Toy objects
Get the first item of the array and print it
The problem in the code is:
You declare items array as static field
You have an instance initialization block where you initialize the array
You have a main function where you get the item and print it
The problem is that the initialization block is done at initialization of instances. The main method however is a static method and has no instance. Therefore the block has not been called yet and you get a NPE.
You need to make the initialization block also static like this:
static {
items[0] = new Toy...
items[1] = new Toy...
}
A static initialization block is called once when the class is initialized. So that way it is called before main will be run.

Related

ArrayList added item is replaced by the next item in for loop

I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)
This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.
public class Serv
{
#Autowired
GrpHeader objGrpHeader;
#Autowired
CompPesoOutgoingMsg objMsg;
#Autowired
OutwardMessage objOutwardMessage;
public List<OutwardMessage> outgoingMessagesAsSingleTrx()
{
List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
List<OutwardMessage> myTrxList = new ArrayList<>();
for (OutgoingMsg_Obj outgoingMsg : trxList)
{
BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
trxAmt = (trxAmt).divide(new BigDecimal(100));
GrpHeader grpHeader = objGrpHeader;
CompPesoOutgoingMsg outMsg2 = objMsg;
OutwardMessage objOutwardMessage2 = objOutwardMessage;
outgoingMsg.setRmtInf(objRmtInf);
outgoingMsg.setPmtTpInf(objPmtTpInf);
outMsg2.setHeader(grpHeader);
outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
objOutwardMessage2.setObjMsg(outMsg2);
**//Here, Correct object details are printed**
log.info("outwardMsg 100 {} ", objOutwardMessage2);
//Add Item to the list
myTrxList.add(objOutwardMessage2);
for (OutwardMessage outwardMsgx : myTrxList)
{
//1. When this loop executed first time, first object details are printed
//2. When printed second time, first added object is no more. And second added object is there twice.
log.info("outwardMsg 101 {} ", outwardMsgx);
}
}
return myTrxList;
}
}
You have a single reference. By setting the objOutwardMessage2to objOutwardMessageyou are just changing the data inside the reference.
Since no new object is created for each iteration, the same objOutwardMessage2 value is getting replaced each time.
Try
OutwardMessage objOutwardMessage2 = new OutwardMessage();
and copy the value of objOutwardMessage to the newly created objOutwardMessage2.

out of bound error i have changed this code from array to array list now it is giving bound error?

This whole project previously had array in package products in class produt list now i am using Array list now in the package main in the Swi test it is giving error that it cannot be converted to Productlist from product. i think there is problem with this part too. i think there is something wrong with the productlist.
now it is giving an out of bound error
public void storeProduct(Product p) {
products.addProd(p);
}
Update your SwiTest Function like above.
Also, the naming convention that you followed is not up to the standard.
Like, package name and variable name should start with small letters and follow the camelCase.
The add function you used gets ProductList as parameter. But you passed a new Product. First you need to change storeProduct argument ProductList to Product, and then you need to use addProd method instead of add inside of the storeProduct method.
public void add(ProductList prods)
public void addProd(Product prod)
public static void main(String[] args) {
SwiTest shop = new SwiTest("My Online Shop");
// prepare list of products
ProductList selectedProductList = new ProductList();
selectedProductList.addProd(new Product("CD Spieler", new Price(new Euro(315,0),19),10));
selectedProductList.addProd(new Product("CD Miles Davis: Kind of Blue", new Price(new Euro(10,50),19),5));
selectedProductList.addProd(new Product("Wasserkocher", new Price(new Euro(80,98),19),5));
selectedProductList.addProd(new Product("Champagner Taittinger", new Price(new Euro(42,81),19),2));
selectedProductList.addProd(new Product("Korkenzieher", new Price(new Euro(5,21),7),10));
selectedProductList.addProd(new Product("Italienische Nudeln 500g", new Price(new Euro(11,21),7),5));
// assign list of products to storeProduct
shop.storeProduct (selectedProductList);
// your others code
}

Initializing empty instance variables in constructor

I have a LogAnalyzer class that looks at a web server log, creates LogEntry objects and puts those objects into HashMaps for analyzing.
My LogAnalyzer class has these fields:
private int totalVisits;
private int uniqueVisits;
private ArrayList<LogEntry> records;
private HashMap<String, ArrayList<LogEntry>> uniqueIPs; //<address, log entries>
private HashMap<String, ArrayList<LogEntry>> dailyRecords; // <date, log entries>
My constructor looks like this:
public LogAnalyzer() {
records = new ArrayList<>();
dailyRecords = new HashMap<>();
uniqueIPs = new HashMap<>();
}
And then I have this method:
public void initializeRecords(String path){
readFile(path); //reads the web log file and fills out the records and dailyRecords fields
getUniqueIPs(); //fills out the uniqueIPs HashMap field.
uniqueVisits = uniqueIPs.size(); //fills out the uniqueVisits field
totalVisits = records.size(); //fills out the totalVisits field
}
So my question:
I have read (but don't really understand) it's "bad" to call methods inside the constructor. However it seems like the constructor is pointless here, since it is actually the initializeRecords that is doing all of the meaningful work of "creating" the object.
I don't have the background in Java or programming to understand the explanations I've found so far. There is a lot of talk of overriding things, and I think that's what I'm not clear on. I'm wondering why I should keep my constructor and this method seperated, in simple terms that a beginner can understand.
**EDIT: ** Here's the code for readFile():
public void readFile(String filename) {
FileResource fr = new FileResource(filename);
for (String line : fr.lines()){
LogEntry le = WebLogParser.parseEntry(line);
String date = le.getAccessTime().toString().substring(4, 10);
if (dailyRecords.keySet().contains(date)){
dailyRecords.get(date).add(le);
}
else{
ArrayList<LogEntry> entries = new ArrayList<>();
entries.add(le);
dailyRecords.put(date, entries);
}
records.add(le);
}
Keeping the two methods allows you more flexibility in the use of your code. You can instantiate your LogAnalyzer without knowing the path to your log. I would rename initializeRecords to processRecords which IMO is more descriptive of what you are doing there.
We should create the object first and then call methods on it. If your readFile method were to throw an Exception because it can't read the file for example. I would find it very odd to get that exception when I am constructing the object. The point of the constructor is to provide an object that can be used to do something.
It's not a good practice to call methods from within constructor, because Java always calls the most derived method, which means we could call a method on a half-initialized object.
To answer your question,
public LogAnalyzer() {
records = new ArrayList<>();
dailyRecords = new HashMap<>();
uniqueIPs = new HashMap<>();
}
What the above part exactly does is, it gives the variables, records, dailyRecods and uniqueIPs a physical address in the memory stack.
When we write something like private ArrayList<LogEntry> records; in the class, at this time only a reference is generated, but actual initialization happens only when records = new ArrayList<>(); this line gets executed.
Hope this clarifies your doubt!!!
As you can see in readFile() it uses the following instruction
dailyRecords.keySet().contains(date)
without initializing dailyRecords prior to it. So if you do not initialize dailyRecords either while declaring it or in constructor you will face NullPointerException.
In your case instead of using constructor for initialization you can use declaration part like this
private HashMap<String, ArrayList<LogEntry>> dailyRecords = new HashMap<>();

What's wrong with this error? ----Syntax error on token ";", { expected after this token

Syntax error on token ";", { expected after this token.
I got this error on the 11th line and 19th line. Is there anyone can tell me what's the problem with it?
import java.util.*;
class veding_machine{
State st;
veding_machine vm;
private int price;
private int k;
private int k1;
private int t;
private int s;
State Ls[]=new State[7]; // 11th line
Ls[0]=idle;
Ls[1]=coins_inserted;
Ls[2]=sugar;
LS[3]=nsc;
Ls[4]=nlc;
Ls[5]=et;
Ls[6]=st; // 19th line
public veding_machine(){ k=0; k1=0; t=0; price=0;
}
public void setK(int k){
this.k=k;
}
Initialize that array inside a Constructor, you can't initialize them like that, initialize them when you declare the array, or in a Constructor or in a initialization block. And correct the spelling mistake. Have look on this tutorial.
Ls[0]=idle;
Ls[1]=coins_inserted;
Ls[2]=sugar;
Ls[3]=nsc;
Ls[4]=nlc;
Ls[5]=et;
Ls[6]=st
;
The initialization of Ls should be inside the vending_machine constructor and should be creating instances of the classes "idle" and "coins_inserted", etc...
Ls[0] = new idle();
Ls[1] = new coins_inserted();
Ls[2] = new sugar();
Ls[3] = new nsc();
Ls[4] = new nlc();
Ls[5] = new et();
Ls[6] = new st();
and these classes need to extend the State class
class idle extends State {
// ...
}
They don't need a state instance inside them.
// removed, State st;
public coins_inserted(){
// removed, st=new State();
}
State Ls[]=new State[7]; // 11th line
This is an instantiated array. You should place it in the constructor or initialization block. Also it is better to init the reference in the Java way:
State[] Ls = new State[7];
This
LS[3]=nsc;
should be
Ls[3]=nsc;
And again init those elements in the constructor or init block.
Also, I know this doesn't answer the question but I just have to say something about naming and style. Please name vending_machine class like VendingMachine and give the other objects more descriptive names instead of vague letters. Following convention helps when you come back to your code a week/month/year later and saves you from trying to figure out what the hell you were doing. Even if it is just a little project in school that is where it matters most that you learn and practice these conventions.
Also, it's nice when code is aesthetically pleasing.

Nullpointer Exception using ArrayList with ResultSet

I have a function "getStudent()" that returns an ArrayList of strings and when i call this function in another class, i get a NullPointerException, i thought i had correctly initialized my List.
Here are the two functions and the line i get a NullPointerException is in bold.
public ArrayList<String> getStudents(){
try
{
System.out.println("gets here ");
Statement newStat = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet res = newStat.executeQuery("SELECT FirstName FROM Students");
String data = "";
while (res.next()){
studentList.add(res.getString("FirstName"));
}
}
catch(SQLException e){
System.err.println("SQLException: " + e.getMessage());
}
return studentList;
}
Function that calls 'getStudents()'
public class CancelListener implements ActionListener{
private Main_Menu menu;
private ArrayList<String> arrayList = new ArrayList<String>();;
Iterator iterator = arrayList.iterator();
public CancelListener(Main_Menu menu) {
this.menu = menu;
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equalsIgnoreCase("Cancel")){
**arrayList = StudentModel.getStudents();**// NULLPOINTER EXCEPTION
while(iterator.hasNext()){
System.out.println(iterator.next().toString());
}
this.menu.resetStudent();
}
}
}
Your StudentModel variable is probably null. The code you posted doesn't show how that variable is initialized so I can't tell you exactly what you're doing wrong, but when you reach the line marked it must be null.
You should check that you are initializing that variable correctly before you try to use it.
You probably didn't initialize StudentModel. But I can't tell for sure since this part of the code doesn't appear here.
getStudents() isn't static, and it looks like you're calling it as a static method (judging by the way you've capitalized StudentModel.) So, as others have already said, you probably need to instantiate a StudentModel object, then call instance.getStudents().
Further, I don't see where you're creating an array instance. getStudents() adds items to studentList, but we don't see how studentList is initialized. This might also be the problem. Frankly, given what you're doing, there's probably no reason to make studentList an instance variable. So just declare the variable locally and allocate the array in the getStudents() method.
You mentioned that you think you initialized the list correctly, but this isn't what you are getting the exception on. Also, you may have another problem.
You get an iterator for your list:
Iterator iterator = arrayList.iterator();
Then you assign a different object to that reference:
arrayList = StudentModel.getStudents();// NULLPOINTER EXCEPTION
Then you try to use the iterator:
while(iterator.hasNext()){
My understanding is that this shouldn't cause an exception, since you're not making changes to list the iterator refers. But, you are almost certainly iterating through a different list that you think you are. Is it possible you may be mis-interpreting an exception that is somehow caused here?

Categories