Please disable your adblock and script blockers to view this page

Search this blog

Monday, 20 January 2025

10 Common Java Mistakes Every Beginner Should Avoid

Java is a popular programming language known for its simplicity, portability, and wide use in enterprise applications. However, like any language, beginners can make mistakes that can lead to bugs, poor performance, and frustration. 

Whether you're just starting out or have been programming in Java for a while, it's essential to be aware of some common pitfalls. In this blog post, we'll go over 10 mistakes every beginner Java developer should avoid.




1. Not Using Proper Naming Conventions

Java has a well-established naming convention that helps make code readable and maintainable. Beginners often ignore or forget these conventions, leading to confusing or inconsistent code.

Mistake:

  • Incorrect Variable Naming: Using vague variable names like temp, x, or data can make your code hard to understand.
  • Wrong Class Naming: Classes should follow PascalCase (e.g., MyClass), while methods and variables should follow camelCase (e.g., calculateTotal()).

Solution:

  • Always use meaningful names that reflect the purpose of the variable, class, or method.
  • Follow Java naming conventions strictly. For example:
    • Classes: Student, EmployeeDetails
    • Methods: calculateSalary(), printReport()
    • Variables: totalAmount, ageOfPerson

2. Ignoring Exceptions and Error Handling

Beginners often overlook exceptions, which can lead to runtime errors that crash the program. Java provides robust exception handling using try, catch, and finally blocks, but new developers might skip this important feature.

Mistake:

  • Not Handling Exceptions: Ignoring exceptions or letting them propagate without any handling can make your program unstable.
  • Catching Generic Exceptions: Catching general Exception or Throwable classes without specifying the exact exception type can hide bugs.

Solution:

  • Always handle exceptions with specific catch blocks and log errors properly.
  • Use finally for cleanup code that needs to run regardless of exceptions.
  • Example:
    try { int result = divide(a, b); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } finally { System.out.println("Division attempt completed."); }

3. Using the == Operator for String Comparison

In Java, comparing strings with the == operator doesn't compare their contents, but instead their memory references. This leads to unexpected results when comparing two strings with the same value but different memory references.

Mistake:

  • Using == for String Comparison: str1 == str2 will only return true if both str1 and str2 refer to the same object in memory, not if their contents are the same.

Solution:

  • Always use the equals() method to compare the contents of strings:

    if (str1.equals(str2)) { System.out.println("Strings are equal!"); }

4. Forgetting to Close Resources

In Java, resources such as file streams, database connections, and network sockets should be closed when no longer needed. Beginners often forget to do this, leading to resource leaks and memory issues.

Mistake:

  • Forgetting to Close Resources: Not closing resources like file readers or database connections after use.

Solution:

  • Always close resources in a finally block or use the try-with-resources statement, which automatically closes resources at the end.

    try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }

5. Not Understanding NullPointerException

The infamous NullPointerException (NPE) is a common error that occurs when trying to use a null reference, such as calling a method or accessing a property of a null object.

Mistake:

  • Dereferencing Null Objects: Beginners may attempt to call methods or access properties of objects that haven't been initialized, leading to NullPointerException.

Solution:

  • Always check for null before accessing methods or fields of an object.

    if (myObject != null) { myObject.someMethod(); }

6. Confusing Array and ArrayList

Arrays and ArrayList are two commonly used data structures in Java, but they are very different. Beginners may confuse them or use them incorrectly.

Mistake:

  • Confusing Arrays and ArrayLists: Arrays are fixed in size, while ArrayList is dynamic and resizable. Using arrays when you need a dynamic size can lead to problems.

Solution:

  • Use an ArrayList when you need a dynamically resizable array.
  • Use arrays when the size is fixed or when you need better performance.
    ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); String[] arr = new String[3]; arr[0] = "Java"; arr[1] = "Python";

7. Misusing the equals() Method

The equals() method is used to compare objects for equality. Beginners often forget to override this method, or they use it incorrectly when working with custom objects.

Mistake:

  • Not Overriding equals() for Custom Classes: If you don't override equals() and use it to compare instances of a custom class, it will use the default reference comparison.
  • Not Implementing hashCode() when Overriding equals(): If you override equals(), you must also override hashCode() to maintain consistency.

Solution:

  • Always override both equals() and hashCode() when comparing custom objects.

    @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; MyClass myClass = (MyClass) obj; return Objects.equals(field, myClass.field); } @Override public int hashCode() { return Objects.hash(field); }

8. Overcomplicating Simple Problems

Java beginners sometimes overcomplicate simple tasks by trying to implement unnecessary patterns or over-engineering their solutions.

Mistake:

  • Overthinking Simple Solutions: Beginners may use complex algorithms, design patterns, or unnecessary abstractions for problems that can be solved simply.

Solution:

  • Keep your code simple and readable. If a simple for loop or conditional statement solves the problem, use it.

9. Not Using the final Keyword Properly

The final keyword is used in Java to define constants, prevent method overriding, and prevent subclassing. Beginners may either misuse or fail to use final in the right places.

Mistake:

  • Not Using final for Constants: Defining constant values without final leads to accidental changes of those values.

Solution:

  • Always use final when defining constants and use it where applicable to make variables, methods, or classes immutable.

    final int MAX_VALUE = 100;

10. Ignoring Code Style and Formatting

Code style and formatting are essential for writing clean and readable code. Beginners often neglect proper indentation, spacing, or inconsistent use of brackets.

Mistake:

  • Inconsistent Code Formatting: Messy, unindented, and hard-to-read code that makes it difficult to maintain.

Solution:

  • Follow a consistent coding style. Use IDE tools or linters to automatically format your code. For example, always indent with spaces (usually 4 spaces), and place opening curly braces { on the same line as the method signature or control statement.

Conclusion

By being aware of these common Java mistakes, you can avoid a lot of frustration and improve the quality of your code. Following best practices, understanding Java concepts, and writing clean, readable code will help you become a better Java developer. Always remember to stay curious, continue learning, and don’t be afraid to make mistakes — because that's how we grow!

Do you have any more Java mistakes you'd like to add to the list? Share your thoughts in the comments below!

Thursday, 7 November 2024

Working with Dates in Oracle ADF and Java

Get Current JBO Date with Time 



Sometimes we need to get and set the current date in our Oracle ADF code

To get the current date in an Oracle ADF application using oracle.jbo.domain.Date, we can use this code, this code can be written in model implementation classes or in Managed Bean





 /**Method to get current JBO Date with time part
     * @return
     */
    public Date getCurrentJboDate(){
        Date currentDate = (Date) Date.getCurrentDate();
        return currentDate;
    }



Get the current JBO Date in a Specific format (JBO Date without time part)


There are times when you need to work with just the date and not the time, whether it's for formatting purposes or for cleaner data extraction. In such cases, you can use a simple code snippet to retrieve the date in a specific format. Here's how you can do it!

    /**Method to get current JBO Date in Specific format
     * @return
     */
    public Date getformattedJboDate() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd");
        java.util.Date date = new java.util.Date();
        String date1 = dateFormat.format(date);
        try {
            date = dateFormat.parse(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        oracle.jbo.domain.Date formattedDate = new oracle.jbo.domain.Date(sqlDate);
        return formattedDate;
    }

Convert java.util Date to java.sql Date



/**Method to convert java.util.Date to java.sql.Date * @return */ public java.sql.Date convertToSqlDate() { //Util Date java.util.Date date = new java.util.Date(); //SQL Date java.sql.Date sqlDate = new java.sql.Date(date.getTime()); return sqlDate; }


Convert java.util Date to oracle.jbo.domain Date



/**Method to convert java.util.Date to oracle.jbo.domain.Date * @return */ public Date convertToJboDate() { //Util Date java.util.Date date = new java.util.Date(); //SQL Date java.sql.Date sqlDate = new java.sql.Date(date.getTime()); //JBO Date oracle.jbo.domain.Date jboDate = new oracle.jbo.domain.Date(sqlDate); return jboDate; }

Get current day of week in Java 8 and later



To get the current day of the week in Java, you can use the LocalDate class from the java.time package, which is part of Java 8 and later. Here’s how you can do it:

import java.time.LocalDate; import java.time.format.TextStyle; import java.util.Locale; /**Method to get current day of week * */ public void getCurrentDayOfWeek() { // Get the current date LocalDate currentDate = LocalDate.now(); // Get the day of the week as a string String dayOfWeek = currentDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH); // Print the day of the week System.out.println("Today is: " + dayOfWeek); }

Code to get current day of week using Calendar class is like this

/**Method to get current day of week *using Calendar clas */ public void getCurrentDayOfWeek() { // Get the current date and time Calendar calendar = Calendar.getInstance(); // Get the day of the week (1 = Sunday, 2 = Monday, ..., 7 = Saturday) int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // Print the corresponding day of the week String dayName = ""; switch (dayOfWeek) { case Calendar.SUNDAY: dayName = "Sunday"; break; case Calendar.MONDAY: dayName = "Monday"; break; case Calendar.TUESDAY: dayName = "Tuesday"; break; case Calendar.WEDNESDAY: dayName = "Wednesday"; break; case Calendar.THURSDAY: dayName = "Thursday"; break; case Calendar.FRIDAY: dayName = "Friday"; break; case Calendar.SATURDAY: dayName = "Saturday"; break; } System.out.println("Today is- " + dayName); }

Get Number of days between 2 JBO Date


/**Method to calculate number of days between two jbo dates * @param date1 * @param date2 */ public void getNumberOfDaysBetweenDates(oracle.jbo.domain.Date date1, oracle.jbo.domain.Date date2) { long numberOfDays = 0; if (date1 != null && date1 != null) { numberOfDays = ((date1.getValue().getTime() - date2.getValue().getTime()) / (24 * 60 * 60 * 1000)); } }

Saturday, 28 September 2019

Oracle ADF and JDeveloper 12.2.1.4 Are Available

Finally some good news for Oracle ADF Community :)

Director of Product Management Shay Shmeltzer has posted a blog about new realse of Oracle ADF and Jdeveloper 12.2.1.4

Oracle JDeveloper and Oracle ADF 12.2.1.4 Now Available

List of new features - Oracle ADF 12.2.1.4 new features

List of fixed bugs - List of fixed bugs

Download and let us know about your experience