- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a String is empty ("") or null in Java
To check if a string is null or empty in Java, use the == operator.
Let’s say we have the following strings.
String myStr1 = "Jack Sparrow"; String myStr2 = "";
Let us check both the strings now whether they are null or empty. Result will be a boolean.
res = (myStr1 == null || myStr1.length() == 0); res = (myStr2 == null || myStr2.length() == 0);
Example
public class Demo { public static void main(String[] args) { String myStr1 = "Jack Sparrow"; String myStr2 = ""; boolean res; res = (myStr1 == null || myStr1.length() == 0); System.out.println("String 1 is null or empty? "+res); res = (myStr2 == null || myStr2.length() == 0); System.out.println("String 2 is null or empty? "+res); } }
Output
String 1 is null or empty? False String 2 is null or empty? True
Advertisements