logo

Како проверити нулл у Јави?

у Јави, нула је буквално. Углавном се користи за додељивање нул вредности променљивој. Нулл вредност је могућа за стринг, објекат или датум и време, итд. Не можемо доделити вредност нулл примитивним типовима података као што су инт, флоат, итд.

У програмирању обично морамо да проверимо да ли је објекат или стринг нулл или не да бисмо извршили неки задатак на њему. Да бисмо проверили нулл стринг, имамо неке унапред дефинисане методе стринга. Узмимо неке примере различитих типова података да бисмо разумели како можемо да проверимо да ли су нулл или не.

Низ

У Јави, Стринг може бити нулл, празан или празан, и сваки од њих је различит.

уметните водени жиг у ворд

1. Празан стринг је стринг објекат који има неку вредност, али је његова дужина једнака нули. На пример:

 String str1 = '' 

2. Празан стринг је стринг који има размак као вредност. Његова дужина је увек већа од 0 и није ни празна ни нула. На пример:

 String str2 = '' 

3. Нулл стринг нема вредност и чини стринг нултим додељивањем а нула кључну реч као вредност за то. На пример:

 String str3 = null 

Да бисмо проверили да ли је стринг нулл или не, користимо оператор поређења(==). Узмимо његов пример да бисмо разумели како га можемо користити за проверу нуле.

НуллЦхецкЕкампле1.јава

 // import required classes and packages packagejavaTpoint.javacodes; // create class NullCheckExample1 class to check whether a string is empty or null class NullCheckExample1 { // main() method start public static void main(String[] args) { // create null, empty, and blank strings String string1 = null; String string2 = ''; String string3 = ' '; String string4 = 'Test'; // check whether string1 is null, empty, or blank System.out.println('string1 is ' + checkNullEmptyBlank(string1)); // check whether string2 is null, empty, or blank System.out.println('string2 is ' + checkNullEmptyBlank(string2)); // check whether string3 is null, empty, or blank System.out.println('string3 is ' + checkNullEmptyBlank(string3)); // check whether string4 is null, empty, or blank System.out.println('string4 is ' + checkNullEmptyBlank(string4)); } // create checkNullEmptyBlank() method which check whether the string is empty, null or blank and return result to the main() method public static String checkNullEmptyBlank(String strToCheck) { // check whether the given string is null or not if (strToCheck == null) { return 'NULL'; } // check whether the given string is empty or not else if(strToCheck.isEmpty()) { return 'EMPTY'; } // check whether the given string is blank or not else if(strToCheck.isBlank()) { return 'BLANK'; } else { return 'neither NULL, EMPTY nor BLANK'; } } } 

Излаз:

Како проверити нулл у Јави

Објекат Дате андДатеТиме

И датум и датум и време су непримитивни типови података, тако да могу да складиште нулту вредност. Узмимо пример објекта датума и времена да бисмо разумели како можемо да проверимо нулти објекат датума или датума и времена.

програмирање у ц низовима

НуллЦхецкЕкампле2.јава

 //import required classes and packages packagejavaTpoint.javacodes; importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.Scanner; //create class NullCheckExample2 class to check whether the Date object is null or not public class NullCheckExample2 { // declare a variable of date type and initialize it with null public static Date d1 = null; public static Date finalResult; // main() method start public static void main(String args[]) { // declare a variable of type string that will store the user-entered date in string format String d2; // create scanner class object Scanner sc = new Scanner(System.in); System.out.print('Enter Date in dd/mm/yyyy format:'); // take input from user and initialize variable d2 = sc.nextLine(); // close scanner class obj sc.close(); // create an instance of the SimpleDateFormat class for modifying the date object SimpleDateFormatobj = new SimpleDateFormat('dd/MM/yyyy'); // use try-catch to parse string to date try { finalResult = obj.parse(d2); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // check whether date1 and date2 is null or not by using comparison operator if(d1 == null) { System.out.println('Date d1 is NULL.'); } if(finalResult == null) { System.out.println('Date d2 is NULL.'); }else { System.out.println('Date d2 is not NULL.'); } } } 

Излаз:

Како проверити нулл у Јави

Јава Објецт

Да бисмо проверили да ли је Јава објекат Нулл или не, можемо користити метод исНулл() Објекти класа или оператор поређења. Узмимо пример да разумемо како можемо да користимо метод исНулл() или оператор поређења за проверу нуле Јава објекта.

НуллЦхецкЕкампле3.јава

 // import required classes and packages packagejavaTpoint.javacodes; // create NullCheckExample3 class to check whether Java object is null or not public class NullCheckExample3 { // main() method start public static void main(String[] args) { // create instance of User2 User2 userObj = new User2(); // get data of User2 by calling User1 firstUser = userObj.getFirstUser(); // check whether firstUser is null or not if (firstUser == null) { System.out.println('Object is Null'); } else { System.out.println('Object is not Null'); // set name for user1 firstUser.setName('Paul'); System.out.println(firstUser.getName()); } } } // create User1 class having a name attribute class User1 { // declare name variable String name; // getter for getting name of User1 public String getName() { // return name of User1 return name; } // setter for setting name of User1 public void setName(String name) { this.name = name; } } // create class User2 having variable of type User1 class User2 { User1 obj; // getter to get object of User1 public User1 getFirstUser() { returnobj; } } 

Излаз:

сајтови попут цоомеет
Како проверити нулл у Јави

НуллЦхецкЕкампле4.јава

 // import required classes and packages packagejavaTpoint.javacodes; importjava.util.Objects; // create NullCheckExample3 class to check whether Java object is null or not public class NullCheckExample4 { // main() method start public static void main(String[] args) { // create instance of User2 User2 userObj = new User2(); // get data of User2 by calling User1 firstUser = userObj.getFirstUser(); // check whether firstUser is null or not if (Objects.isNull(firstUser) ){ System.out.println('Object is Null'); } else { System.out.println('Object is not Null'); // set name for user1 firstUser.setName('Paul'); System.out.println(firstUser.getName()); } } } // create User1 class having a name attribute class User1 { // declare name variable String name; // getter for getting name of User1 public String getName() { // return name of User1 return name; } // setter for setting name of User1 public void setName(String name) { this.name = name; } } // create class User2 having variable of type User1 class User2 { User1 obj; // getter to get object of User1 public User1 getFirstUser() { returnobj; } } 

Излаз:

Како проверити нулл у Јави