Java length on null string

difference between (string == null) and (string.length() == 0)? [duplicate]

The first code gave me [«»], which passed the testing. While the second one gave me [], got failed. And I also noticed that there is another way: S.isEmpty() Would anyone please explain? Many thanks!

7 Answers 7

String == null checks if the object is null (nothing, not even an empty string) and String#length() == 0 (actually, you should use String#isEmpty() instead) checks if the string object has 0 chars. Also, you can’t access any methods if the object is null , it will throw a NullPointerException (or NPE for short).

difference between (string == null) and (string.length() == 0)?

When you check (string == null) , it checks whether the string reference is pointing to any existing object. If it is not referencing to any object, it will return true .

string.length() == 0 just checks your existing String object’s content and see if its length is 0. If no object exist in the current variable when you invoke .length() , you get a NullPointerException .

S is a reference variable (you should write it in lower case).

S (or rather s) references an object that provides the method length().

You can only access the object referenced by s, if s is a really a reference to an object. If s is null (s==null), s does not reference an object and therefore, you can not call the method length(). If you try, you will get a NullPointerException.

When s references an object, you can call the length method on that object. In this case, it is a string object. A string object may exist without any characters (empty string, or «»).

  • String s; // just a reference, initial value is null
  • s = «»; // s now references an empty string and is no longer null
  • new String(«»); // create a new object with an empty string
Читайте также:  For next loop in python

In Java, you never really work with objects. You only work with references to objects, though in most cases, it appears as if you work with the object directly.

Keep in mind that the reference variable and the object are really to different things.

Источник

‘int java.lang.String.length()’ on a null object reference

I am very new to android. I know this question is duplicate, i tried all solution from SO but i cloud not fix my problem.I hope you understand.Here is my code to retrieve data from MYSQL and displayed into table format. But I stuck with some where. I tried lot of solution to fix my problem but i failed to get output. Every time i run my app it goes on crushed.Also i failed in display data in table view. main.java

 public class MainActivity extends Activity < public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String result = null; InputStream is = null; try < HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://IP/stat_api/myjson.json"); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.e("log_tag", "Connection Success"); // Toast.makeText(getApplicationContext(), “pass”, Toast.LENGTH_SHORT).show(); >catch (Exception e) < Log.e("log_tag", "Error in HTTP Connection" + e.toString()); Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show(); >//convert response to string try < BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) < sb.append(line + "\n"); >is.close(); result = sb.toString(); > catch (Exception e) < Log.e("log_tag", "Error converting result" + e.toString()); Toast.makeText(getApplicationContext(), "Input reading fail", Toast.LENGTH_SHORT).show(); >//parse json data try < JSONArray jArray = new JSONArray(result); TableLayout tv = (TableLayout) findViewById(R.id.table); tv.removeAllViewsInLayout(); int flag = 1; for (int i = -1; i < jArray.length() - 1; i++) < TableRow tr = new TableRow(MainActivity.this); tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); if (flag == 1) < TextView tv1 = new TextView(MainActivity.this); tv1.setText("eid"); tv1.setTextColor(Color.BLUE); tv1.setTextSize(15); tr.addView(tv1); TextView tv2 = new TextView(MainActivity.this); tv2.setPadding(10, 0, 0, 0); tv2.setTextSize(15); tv2.setText("name"); tv2.setTextColor(Color.BLUE); tr.addView(tv2); TextView tv3 = new TextView(MainActivity.this); tv3.setPadding(10, 0, 0, 0); tv3.setText("user_name"); tv3.setTextColor(Color.BLUE); tv3.setTextSize(15); tr.addView(tv3); tv.addView(tr); final View vline = new View(MainActivity.this); vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2)); vline.setBackgroundColor(Color.BLUE); tv.addView(vline); flag = 0; >else < JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag", "eid: " + json_data.getInt("eid") + ", name: " + json_data.getString("name") + ", user_name: " + json_data.getString("user_name")); TextView b = new TextView(MainActivity.this); String stime = String.valueOf(json_data.getInt("eid")); b.setText(stime); b.setTextColor(Color.RED); b.setTextSize(15); tr.addView(b); TextView b1 = new TextView(MainActivity.this); b1.setPadding(10, 0, 0, 0); b1.setTextSize(15); String stime1 = json_data.getString("name"); b1.setText(stime1); b1.setTextColor(Color.BLACK); tr.addView(b1); TextView b2 = new TextView(MainActivity.this); b2.setPadding(10, 0, 0, 0); String stime2 = json_data.getString("user_name"); b2.setText(stime2); b2.setTextColor(Color.BLACK); b2.setTextSize(15); tr.addView(b2); tv.addView(tr); final View vline1 = new View(MainActivity.this); vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1)); vline1.setBackgroundColor(Color.WHITE); tv.addView(vline1); >> > catch (JSONException e) < Log.e("log_tag", "Error parsing data" + e.toString()); Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show(); >> > 
Process: com.example.newtable.newtable, PID: 5668 java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) at org.json.JSONTokener.nextValue(JSONTokener.java:94) at org.json.JSONArray.(JSONArray.java:92) at org.json.JSONArray.(JSONArray.java:108) at com.example.newtable.newtable.MainActivity.onCreate(MainActivity.java:65) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Источник

Читайте также:  Красиво распечатать массив php

Java NPE for String Length [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn’t work, and the expected results. See also: Stack Overflow question checklist

String temp_content = null; while((line = br.readLine())!= null) < if(temp_content.length() == 0) /* NPE */ < temp_content = line; >else < temp_content = temp_content+line; >> 

I am getting a NullPointerException at the above indicated line. Is it wrong to use «temp_content.length() == 0» to find out if the string is null ?. Can anyone tell me why?

You should initialize your string variable like temp=»» or temp=new temp(); when you are try to perform any function in null object you will get NPE.

5 Answers 5

String temp_content = null; while((line = br.readLine())!= null) < if(temp_content == null) < temp_content = line; >else < temp_content += line; >> 

Using StringBuilder will make it even better :

StringBuilder temp_content = new StringBuilder(); while((line = br.readLine())!= null)

temp_content is initialized to null . Make sure its initialized to empty string to avoid NPE

temp_content is null , so calling .length() on it is like calling null.length() , which causes a NullPointerException . In order for this not to happen, you must initialize it:

To determine if a String is null , you can use:

Because temp_content is null and you are calling an instance methond on null reference.

If you want to know whether a String is null, then you need to use == to verify the same.

NPE is thrown everytime you try to invoke an instance method on null reference.

Note: NPE is NOT thrown when invoking a static method on null reference.

Источник

Оцените статью