Java Basics – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Wed, 29 Nov 2023 07:18:18 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java Basics – Java2Blog https://java2blog.com 32 32 How to Get Variable From Another Class in Java https://java2blog.com/get-variable-from-another-class-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-variable-from-another-class-java https://java2blog.com/get-variable-from-another-class-java/#respond Tue, 29 Nov 2022 12:31:08 +0000 https://java2blog.com/?p=20241 In this article, you will learn about accessing a variable from another class in a Java Program.

To be able to program in any programming language, it is very critical to be able to understand how to use the variables according to your need, and thus it makes it very important to be able to understand how to access variables.

Classes and Objects in Java

Classes and Objects are fundamental to Java as it is an object-oriented programming language. Classes are nothing but a basic layout of an entity that could represent a real-life object.

Classes create an object. Classes are general whereas an Object is specific. For example, a class of Vehicles can become the blueprint of any real-world object such as a bike, car, truck, or bus.

Access Modifiers in Java

As the name suggests Java provides access modifiers that can help change the scope of variables, member functions, constructors, etc.

There are four types of access modifiers provided by the Java Language Specification, these are Private, Public, Protected, and Default.

It is important for you to understand the basics of access modifiers as it is one of the helpful methods to get variables from another class that we will discuss further in this article.

Get Variable From Another Class in Java

There are multiple ways to get variable from another class in Java.

Using the Default or Public Access Modifier of the Other Class

The public access modifier has the largest scope out of all the access modifiers of Java. Thus if a variable is declared using the public access modifier it can even be accessed outside of the package as well.

However, in the same package, the default access modifier can also provide unrestricted access to variables within different classes.

When you declare a variable without using any specific access modifier such as public, protected, or private, Java considers it as a default scope.

In the following code, you will observe how the usage of a public access modifier can help in accessing the variable from another class.

public class Sample {

    public static void main(String[] args) {
        AnotherClass Ac=new AnotherClass();

        System.out.println(Ac.thevariable+2);
    }
}
class AnotherClass
{
    public int thevariable=2;
}

You can note that the AnotherClass instance cab be accessed in the Sample class because it was declared as public.

Output:

4

Note that if the package of both of your classes is the same, in essence, both classes are inside the same directory, you may even skip the public keyword and nothing would change.

This is due to the fact that by default, Java gives package-level access to all the variables without any modifier.

Using the Static Member of Another Class

Java enables you to define variables that can be static, instance, or maybe local.

Declaring a variable as static means that the variable’s data will be held inside the static memory of the program, and it will be destroyed after the execution of the program.

In case you do not want to create an instance of the class, you still have an option to use variables of other classes in your class. This can happen if your variable is declared as static in nature.

To understand how you can use the static variable, let us have a look at the following sample code.

public class Sample {

    public static void main(String[] args) {

        System.out.println(AnotherClass.thevariable+2);
    }
}
class AnotherClass
{
    static int thevariable=2;
}

Output:

4

As you can see, the static variable can be used by using the class name. This allows us to use the static variable in any class.

Using the Inheritance Concept of Java

Inheritance is one of the pillars of object-oriented programming as implemented in Java.

Inheritance essentially provides all the variables and methods of the parent class to the base class except the private methods and variables.

An example of inheritance can be a class cars that will inherit from the class vehicle, having wheels and engine but specifics involves four wheels and roof, etc.

Java provides the extend keyword to inherit the elements of the base class that are not private.

To understand this concept let us look at the following sample code.

class AnotherClass
{
    int thevariable=2;
}
public class Sample extends AnotherClass{

    public static void main(String[] args) {
        Sample sp=new Sample();
        System.out.println(sp.thevariable+2);
    }
}

Output:

4

Using the Getters and Setters of Another Class

Like Inheritance, Encapsulation is also one of the pillars of Object-Oriented Programming.

One way to implement encapsulation in the Java Language is by making explicit functions to modify private members of the class.

These explicit functions are generally called getters and setters of that particular member variable.

Implementing getters and setters is fairly simple, easy, and straightforward. You can also modify getters and setters according to some conditions as it is explicitly defined.

To understand how you can get a variable of a class from another class, let us look at the following piece of code.

class AnotherClass
{
    private int thevariable=2;

    public int get()
    {
        return thevariable;
    }
    public void set(int newnum)
    {
        thevariable=newnum;
    }
}
public class Sample {

    public static void main(String[] args) {
        AnotherClass Ac=new AnotherClass();
        System.out.println(Ac.get()+2);
    }
}

Output :

4

The get() method of the AnotherClass acts as the getter that provides indirect access to the member variable.

Note that accessing the variable in this way is indirect. It is also safer than other methods.

Using the Singleton Pattern Design for Declaring Global Variables

Singleton Classes in Java are classes that only have one instance of themselves. It has numerous advantages in terms of performance and efficiency in the memory of the program.

You can also implement the Singleton Pattern Design to access variables from another class. This code basically provides a global variable to an entire project, a single line acts as the declaration of a global variable.

Singleton Classes can be instantiated in two ways:

  • Early instantiation.
  • Lazy instantiation.

You can know more about early and lazy instantiation here.

In the following code, we will use the Lazy instantiation. To understand this whole concept let us look at the following sample code.

//Class Sample

public class Sample {

    public static void main(String[] args) {

        System.out.println(SingletonClass.getinstance().thevariable+2);
    }
}

// Class Singleton

public class SingletonClass
{
    private static SingletonClass instance=null;

    public int thevariable=2;

    static public SingletonClass getinstance()
    {
        if(instance==null)
        {
            instance=new SingletonClass();
        }
        return instance;
    }
}

Output :

4

If you examine carefully, you would notice that you would need two different files of class as both of them are public classes. This is because you can have at most one public class in each file.

The main advantage of using the concept of Singleton Design Pattern is that by using only one single line of code (which in this case is SingletonClass.getinstance().thevariable) anywhere in the project you will directly be able to access the variable making it a go-around of declaring a global variable.

Conclusion

The access modifiers concept is one of the core concepts that may come in very handy for you. However, it should be used with care as it can cause security issues.

Declaring the variable to be static is another shortcut for accessing a member without even creating an instance of a class, however as you can observe it comes with its own set of disadvantages as it will become a very vulnerable variable.

This is all about how to get a variable from another class in Java

Hope you have learned something new and enjoyed reading the article. Stay tuned for more such articles. Happy learning!

]]>
https://java2blog.com/get-variable-from-another-class-java/feed/ 0
Increment for Loop by 2 in Java https://java2blog.com/increment-for-loop-by-2-java/?utm_source=rss&utm_medium=rss&utm_campaign=increment-for-loop-by-2-java https://java2blog.com/increment-for-loop-by-2-java/#respond Sat, 24 Sep 2022 11:02:53 +0000 https://java2blog.com/?p=20750 In this post, we will see how to increment for loop by 2 in Java.

There are several looping statements available in Java and one of them is for loop in java.

There are three parts of for loop.

  • Initialization
  • Condition
  • Increment or decrement
for (initialization; condition; increment/decrement) {
     //block of statements
}

Initialization: Initialization statement executes at start of loop only one time.
condition:Condition gets evaluated in each iteration. For loop executes block of statements in loop unless condition returns false.
Increment/Decrement: These statements get executed in each iteration.

How to increment for loop by 2 in Java

To Increment for loop by 2 in Java, we are interested in Increment/Decrement part of for loop.

We need to use i+=2 in case we need to increment for loop by 2 in java.

for (int i = 1; i < 10; i+=2) {
    System.out.print(" "+i); // Prints 1 3 5 7 9
}

Let’s say we want print all even numbers between 1 to 20 in Java.

We can write a for loop and start the loop from 2 by using i=2 in initialization part and increment the loop by 2 in each iteration by using i+=2.

Here is the program:

package org.arpit.java2blog;

public class PrintEvenNumbers {

    public static void main(String[] args) {
        for (int i=2 ;  i <=20 ; i+=2)
        {
            System.out.print(" "+i);
        }
    }
}

Output

2 4 6 8 10 12 14 16 18 20

How to increment for loop by n in Java

We can use similar logic in case you want to increment for loop by n i.e. 2,3,4,5. We need to put i+=n in increment/decrement part of the for loop.

Here is simple program where we will increment for loop by 3.

package org.arpit.java2blog;

public class IncrementForLoopBy3 {

    public static void main(String[] args) {
        for (int i=1 ;  i <=20 ; i+=3)
        {
            System.out.print(" "+i);
        }
    }
}

Output

1 4 7 10 13 16 19

That’s all about how to increment for loop by 2 in Java.

]]>
https://java2blog.com/increment-for-loop-by-2-java/feed/ 0
Return ArrayList in Java https://java2blog.com/return-arraylist-java/?utm_source=rss&utm_medium=rss&utm_campaign=return-arraylist-java https://java2blog.com/return-arraylist-java/#respond Tue, 20 Sep 2022 07:01:01 +0000 https://java2blog.com/?p=20434 This article discusses cases of returning an ArrayList in Java from a method.

An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return an ArrayList from a method in Java. These cases are as given below.

  • Returning ArrayList from a static method.
  • Returning ArrayList from a non-static method.

Return ArrayList in Java From a Non-static Method

The methods that you normally define under a normal class name are the non-static methods.

You can not directly call the non-static methods using the class name. For calling a non-static method, you would need to create an instance of the class and then call the method using that instance.

This method of returning the ArrayList is similar except that the receiving method must use the class instance to call the returning method.

Let us see the example code.

package org.arpit.java2blog.generic;

import java.util.ArrayList;
import java.util.Arrays;

class Util{
    public ArrayList<String> convertStringToList(String countryStr)
    {
        // Split String by comma and return ArrayList
        ArrayList<String> countryList = new ArrayList<>(Arrays.asList(countryStr.split(",")));
        return countryList;
    }
}

public class ReturnListMain {
    public static void main(String [] args)
    {
        Util obj = new Util();
        String countryStr = "India,China,Japan";
        ArrayList<String> list = obj.convertStringToList(countryStr);
        list.forEach(System.out::println);
    }
}

Output:

India
China
Japan

Here we wrote simple utility method to take string as input and return ArrayList as output. This programs splits String by comma and return ArrayList.

You can also create new ArrayList and add elements one by one.

public ArrayList<String> convertStringToList(String countryStr)
    {
        // Split String by comma and return ArrayList
        ArrayList<String> countryList = new ArrayList<>();
        String[] CountryArr = countryStr.split(",");
        for(String country:CountryArr)
        {
            countryList.add(country);
        }
        return countryList;
    }

Return ArrayList in Java From a Static Method

As you might know, static methods in Java do not need any class instance to call them. You can call a static method using the class name.
Returning an ArrayList from a static method is simple.

  • Create a static method with the return type as ArrayList.
  • Create an ArrayList and instantiate it.
  • Input the data into the list.
  • Return the ArrayList.

Let us see an example code for the same.

package java2blog;

import java.util.ArrayList;

class Main{
    public static ArrayList<Integer> myFun()
    {
        ArrayList<Integer> list = new ArrayList<Integer>();

        list.add(1);
        list.add(2);
        list.add(3);

        return list;
    }
}

public class GetClass {
    public static void main(String [] args)
    {
        ArrayList list = Main.myFun();
        for(int i=0;i

Output:

1 2 3

Conclusion

This is all about returning the ArrayList from a method in Java.

Hope you enjoyed reading the article. Stay tuned for more such articles. Happy Learning!

]]>
https://java2blog.com/return-arraylist-java/feed/ 0
Check if Object Is Null in Java https://java2blog.com/check-if-object-is-null-java/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-object-is-null-java https://java2blog.com/check-if-object-is-null-java/#respond Mon, 14 Mar 2022 10:07:00 +0000 https://java2blog.com/?p=19620 1. Introduction to the Problem Statement

In Java programming, handling null references is essential for preventing the dreaded NullPointerException. Suppose we have an object, MyObject. Our objective is to determine whether MyObject is null. The expected output is a boolean value indicating the null status of the object. This article explores several methods for checking nullity, considering their performance and applicability in different scenarios.

2. Using the Simple == Operator

The most basic and efficient way to check if an object is null is by using the == operator.

Object myObject = null;
if (myObject == null) {
    // Handle null case
}

Explanation:

  • Object myObject = null;: This line declares a variable named myObject of the type Object, which is a class in Java. The variable is immediately initialized to null, meaning it currently references nothing.
  • if (myObject == null) { ... }: This if statement checks whether myObject is null. It uses the == operator to compare myObject with null.

It is highly efficient as it involves a simple reference comparison at the language level.

3. Using Objects Class in Java 8

Java 8 introduced Objects.isNull() for null checks, which is more readable and suitable for streams and lambda expressions.

import java.util.Objects;

Object myObject = null;
if (Objects.isNull(myObject)) {
    // Handle null case
}

Though slightly less efficient due to the method call overhead, it improves code readability.

4. Using Optional Class in Java 8

The Optional class, particularly Optional.ofNullable(), provides a functional-style approach to handling nulls.

import java.util.Optional;

Object myObject = null;
if (Optional.ofNullable(myObject).isEmpty()) {
    // Handle null case
}

This approach is less efficient because of the additional Optional object creation but offers a more modern, functional programming style.

5. Using Ternary Operator

A ternary operator can also be used for a compact null check.

Object myObject = null;
if ((myObject == null) ? true : false) {
    // Handle null case
}

This approach is as efficient as the == operator and provides an inline alternative.

6. Using Object.requireNonNull()

import java.util.Objects;

Object myObject = null;
try {
    Objects.requireNonNull(myObject, "Object cannot be null");
} catch (NullPointerException e) {
    // Handle null object
}
This method is used to check if an object is null and throw a NullPointerException if it is. It’s typically used for validating parameters.

7. Using Objects.requireNonNullElse()

This Java 9 method returns the first argument if it’s non-null; otherwise, it returns the second argument (a default value).

import java.util.Objects;

Object myObject = null;
Object defaultObject = new Object();
Object result = Objects.requireNonNullElse(myObject, defaultObject);
 

8. Using Apache Commons Lang

For projects using Apache Commons Lang, ObjectUtils.isEmpty() can be a versatile option.

import org.apache.commons.lang3.ObjectUtils;

Object myObject = null;
if (ObjectUtils.isEmpty(myObject)) {
    // Handle null case
}

This method checks for both null and empty objects, offering more functionality but with a slight performance cost.

9. Custom Utility Method

Creating a custom utility method for null checks allows for tailored solutions specific to project needs.

Object myObject = null;
if (isNull(myObject)) {
    // Handle null case
}

private static boolean isNull(Object obj) {
    return obj == null;
}

This method is similar in efficiency to the == operator and can be customized as needed.

10. Using Java Streams

For collections, Java Streams can be used to check if any of the elements are null.

import java.util.Arrays;
import java.util.List;

List<Object> objects = Arrays.asList(obj1, obj2, obj3);
boolean hasNull = objects.stream().anyMatch(Objects::isNull);

This method is suitable for checking nulls in collections and aligns with the functional programming paradigm in Java 8 and above.

11. Conclusion

There are several methods to check if an object is null in Java, each with its own use cases and performance implications. The choice of method should be based on the specific requirements of the project, considering factors like readability, performance, and the context in which the check is performed. The == operator is the most efficient for single objects, while utility methods from Java 8 and external libraries provide more readability and functionality at a slightly higher performance cost. For collections, the Java Streams API offers a functional approach to checking nulls.

]]>
https://java2blog.com/check-if-object-is-null-java/feed/ 0
How to Print Multiple Variables in Java https://java2blog.com/print-multiple-variables-java/?utm_source=rss&utm_medium=rss&utm_campaign=print-multiple-variables-java https://java2blog.com/print-multiple-variables-java/#respond Mon, 31 Jan 2022 10:42:46 +0000 https://java2blog.com/?p=19124 1. Introduction

In Java programming, it’s common to need to print multiple variables for various purposes like debugging, logging, or displaying information to the user. These variables might be of different data types (such as integers, strings, or floats), and our goal is to effectively combine and display them. The expected output is a coherent string that includes the values of all these variables. This article will explore various methods to print multiple variables in Java, considering performance, readability, and use case scenarios.

2. Using Concatenation with the ‘+’ Operator

One of the simplest ways to print multiple variables in Java is by using the + operator to concatenate them into a single string.

Example:

int age = 30;
String name = "John";
System.out.println("Name: " + name + ", Age: " + age);
// Output: Name: John, Age: 30

Explanation:

  • The + operator is used to concatenate strings and variables into a single string.
  • This method is straightforward and easy to read, making it great for simple scenarios.

Performance:
In terms of performance, using + for concatenation can be less efficient, especially in loops, as it creates intermediate String objects.

3. Using String.format() Method

The String.format() method offers a more flexible way to combine variables into a string, allowing formatted output.
Example:

int age = 30;
String name = "John";
String output = String.format("Name: %s, Age: %d", name, age);
System.out.println(output);
// Output: Name: John, Age: 30

Explanation:

  • String.format uses format specifiers like %s for strings and %d for integers.
  • It provides better control over formatting, such as precision for floating-point numbers and padding for integers.

Performance:
String.format() is slightly slower than simple concatenation due to parsing the format string but offers enhanced control over the output.

4. Using StringBuilder or StringBuffer

For scenarios where multiple string concatenations are required, such as in loops, StringBuilder (or StringBuffer in multi-threaded environments) is more efficient.

Example:

int age = 30;
String name = "John";
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(name).append(", Age: ").append(age);
System.out.println(sb.toString());
// Output: Name: John, Age: 30

Performance:
Both StringBuilder and StringBuffer are more performance-efficient in scenarios involving multiple concatenations.
Explanation:

  • StringBuilder sb = new StringBuilder();: A StringBuilder object named sb is created. StringBuilder is a mutable sequence of characters, and it’s used for building strings efficiently.
  • sb.append("Name: ").append(name).append(", Age: ").append(age);: Appends variables and string(For display) to StringBuilder
  • sb.toString(): Converts the StringBuilder object sb to a String. The resulting string is Name: John, Age: 30.

5. Using System.out.printf()

This method provides a way to format strings and output them to the console, similar to the printf function in languages like C. It allows us to create a formatted string with placeholders, which are then replaced by the values of variables.
This is similar to String.format() method.

Example:

int age = 30;
String name = "John";
System.out.printf("Name: %s, Age: %d%n", name, age);
// Output: Name: John, Age: 30

Explanation:

  • %s is a placeholder for a string. In the example, it’s replaced by the value of name.
  • %d is a placeholder for a decimal integer. In the example, it’s replaced by the value of age.
  • %n is a platform-independent newline character.
  • The printf() method does not automatically add a newline at the end, so %n is often used to append a newline character.

Performance:

  • System.out.printf() is quite efficient for printing formatted strings.
  • It’s particularly useful when we need to control the formatting of the output (like specifying the number of decimal places for floating-point numbers, padding, or aligning text).

6. Using Java Streams for Collection of Variables

When dealing with a collection of variables, Java Streams can be used for efficient concatenation.
Example:

List<String> items = Arrays.asList("Apple", "Banana", "Cherry");
String combined = items.stream().collect(Collectors.joining(", "));
System.out.println("Items: " + combined);

Explanation:

  • Streams provide a high-level and functional approach to handle collections of data.
  • Collectors.joining is used to concatenate elements of the stream with a delimiter.
    Performance:
    Streams offer a balance between performance and readability, especially for operations on collections.

7. Print Multiple Variables using Logger

In Java applications, particularly in larger or more complex applications, using a logging framework instead of System.out.println for outputting information is a standard practice. Logging frameworks provide more flexibility, such as logging levels, formatting, and directing output to various destinations (like files, console, network, etc.). Let’s explore how to print multiple variables using a logger.

Using java.util.logging.Logger:
Java’s built-in logging framework, java.util.logging, can be used for this purpose.
Example:

import java.util.logging.Logger;
import java.util.logging.Level;

public class Main {
    private static final Logger logger = Logger.getLogger(Main.class.getName());

    public static void main(String[] args) {
        int age = 30;
        String name = "John";
        logger.log(Level.INFO, "Name: {0}, Age: {1}", new Object[]{name, age});
    }
}
Jul 30, 2023 10:00:00 AM Main main
INFO: Name: John, Age: 30

Explanation:

  • Logger.getLogger(Main.class.getName()) initializes a logger instance for the Main class.
  • logger.log(Level.INFO, "Name: {0}, Age: {1}", new Object[]{name, age}); logs the formatted string at the INFO level. The placeholders {0} and {1} are replaced by the name and age values, respectively.
  • The Level.INFO is a logging level indicating the importance of the message. There are various levels like SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST.

Please note that there are multiple libraries available for logging such as log4j, slf4j etc. apart from java inbuilt logging. We should choose library based on our needs.

Performance:

  • Logging frameworks like java.util.logging are generally more efficient in handling strings compared to direct concatenation, especially when the logging level is set to ignore certain messages. This can prevent unnecessary string concatenation and processing when the log message is not required to be recorded.
  • Another advantage is the ability to easily switch between different levels of logging (like turning on debug messages) without changing the source code.

8. Frequently Asked Questions

1) How Can We Print Multiple Values on One Line in Java?
We can use System.out.print or System.out.printf to print multiple values on one line in java.

System.out.print(str1 +" "+ str2);
System.out.printf("%s %s",str1,str2);

2) How Can We Print Multiple Integers in Java?
We can print multiple integers with the help of System.out.print or System.out.printf.

public class PrintMultipleVariablesMain {

    public static void main(String[] args) {
        int i=1;
        int j=2;
        System.out.println(i+" "+j);
        System.out.printf("%d %d",i,j);
    }
}

Output:

1 2
1 2

3) How Can We Print String and Integer in Same Line in Java?
Here is example to print string and integer in same line in java:

public class PrintMultipleVariablesMain {

    public static void main(String[] args) {
        String str1="Employee";
        int i=1;
        System.out.println(str1+" "+i);
        System.out.printf("%s %d",str1,i);
    }
}

Output:

Employee 1
Employee 1

9. Conclusion

Printing multiple variables in Java can be achieved through various methods, each suited to different use cases. Simple concatenation with the + operator is easy and straightforward for a small number of variables. String.format offers more control over formatting, while StringBuilder and StringBuffer provide efficient ways to handle multiple concatenations. Java Streams are useful for handling collections of variables. The choice of method should be based on the specific requirements of the task, balancing factors like simplicity, performance, and the complexity of the data being handled.

]]>
https://java2blog.com/print-multiple-variables-java/feed/ 0
What is == in java https://java2blog.com/what-is-equals-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-equals-in-java https://java2blog.com/what-is-equals-in-java/#respond Wed, 01 Dec 2021 12:56:10 +0000 https://java2blog.com/?p=18200 In this tutorial, we will learn what is == in Java as it is a common lexeme that we will use while developing applications.

The == lexeme can be confused with = which is another lexeme of the Java language and we will also learn in detail how the two differ to avoid issues such as logical errors in our applications.

We will also learn the difference between the == lexeme and the Java method equals() that uses the == lexeme behind the scenes to realize a different functionality.

What is meaning of == in Java

We mentioned above that == is a lexeme and a lexeme is a sequence of alphanumeric characters consisting of letters, digits, or punctuation and formed using a regular expression.

The string formed by the sequence of characters describes the construct of a programming language features such as identifiers, keywords, and operators.

In Java, there are several operators that can be used by the language such as arithmetic operators, logical operators, relational operators, and many others depending on the problem at hand.

These operators are represented by individual lexemes for the specific operations and the == lexeme is an example of an operator for the relational operators in Java.

This operator is pronounced as equal to and note that we must use the == instead of = when we want to test whether two operands of the primitive type are equal.

(MALE == FEMALE) returns false

Code example of ==

The operator is used with primitive data types such as int, short, long, float, and double in Java.

The operator compares the two operands and returns a boolean value of true if they are equal and false otherwise.

The following is an example of the == operator that compares two operands of type integer.

package com.java2blog;

public class EqualityOperator {
    public static void main(String[] args) {

        int numOne = 1;

        int numTwo = 1;

        System.out.println(numOne ==numTwo);

    }
}

Output:

true

Object equality using equal to ==

In Java, we can use the == operator to compare whether two objects have the same address and the following is an example that compares two strings.

When we create multiple strings in Java without creating new objects using the new keywords, the collection of strings is stored in the same location which is the reason that the == operator returns true when comparing two string objects.

When comparing custom objects created from custom classes the case is different depending on whether the objects being compared were instantiated.

package com.java2blog;

public class EqualityOperator {
    public static void main(String[] args) {

        String firstName = "john";

        String lastName = "john";

        System.out.println(firstName == lastName);

    }
}

Output:

true

The difference between == and equals

The == operator checks the reference of two variables as demonstrated with the above example and in this section, we will learn how == differs from equals.

Equals is a Java method that we can use to test the equality of two objects based on their contents and to achieve this we must override the equals() method in the class.

Also, note that an equals method is accompanied by a hashcode() method to store objects with the same hashcode in one bucket and this prevents returning the same objects as unique.

We will use a product object that overrides the equals() method and uses id in a hashcode to identify the same objects.

The equals method works similarly to the == operator if the hashcode is not overridden in the products class and we should take note of it to avoid errors in our applications.

If you are not aware about concept of hashcode() and equals() method, you should go through hashcode() and equals() method in java.

The following example demonstrates the usage of equals that compares two product objects with different id’s which implies different hashcode and a boolean result of false.

package com.java2blog;

import java.util.Objects;

public class EqualityOperator {
    public static void main(String[] args) {

        Product bookOne =
                new Product(1,
                        "Introduction to Java",
                        60.00,
                "Basics of Java");

        Product bookTwo = new Product(2,
                "Advanced data structures",
                70.00,
                "advanced data structures");

        System.out.println(bookOne.equals(bookTwo));

    }
}

class Product{
    private int id;
    private String productName;
    private Double productPrice;
    private String productDescription;

    public Product(int id, String productName, Double productPrice, String productDescription) {
        this.id = id;
        this.productName = productName;
        this.productPrice = productPrice;
        this.productDescription = productDescription;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return id == product.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

Output:

false

== in Enum

You can use == to check enum equality.
Here is an example:

package org.arpit.java2blog;

public class EnumEquality {

        enum RATING {
            ONE,
            TWO,
            THREE
        }

        public static void main(String[] args) {
            RATING r = RATING.TWO;

            if(r == RATING.TWO)
            {
                System.out.println("Rating is two");
            }
        }
}

Output:

Rating is two

Conclusion

In this tutorial, we have learned what is the meaning of the == operator, how the operator can be used to compare string objects and custom objects, and finally looked at the difference between the equal to operator == and the Java equals() method.

That’s all about what is == in java.

]]>
https://java2blog.com/what-is-equals-in-java/feed/ 0
Multiple classes in one file in Java https://java2blog.com/multiple-classes-in-one-file-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=multiple-classes-in-one-file-in-java https://java2blog.com/multiple-classes-in-one-file-in-java/#respond Mon, 18 Oct 2021 10:18:14 +0000 https://java2blog.com/?p=17893 In this post, we will see how to have multiple classes in one file in java.

Introduction

You need to have any number of classes in a single Java file, but there is a restriction that you can declare only one Java class as public modifier with the main() method and declare (without public) for the remaining classes. Moreover, we have one rule in Java that your filename must be the same as your public class name.

Methods to Implement Multiple Classes In One Java Program

1) Nested classes

A nested class is one type of inner class that accesses other instance variables of an outer class. We can use any access modifiers for the nested inner class such as private, public, protected, or default.

There are two types of nested classes defined in Java.
1.static nested class

  1. non-static nested class.

If You define an inner class with a static keyword, such type of class is said to be a static nested class, and an inner class is also said to be a non-static nested class in Java.

Example

class Organization {
  private int totalProjects;

   Organization() {
      System.out.println("Inside Organization class constructor");
      this.totalProjects = 0;
      System.out.println("Total Organization projects: " + this.totalProjects);
   }

   public void createProject() {
      Project proj1 = new Project(10); // creating a new project object instance
      proj1.displayDuration();

      Project proj2 = new Project(20); // creating another project object instance
      proj2.displayDuration();
   }

   private void greetings() {
      System.out.println("Greetings from private method of Organization class");
   }

   class Project {
      private int durationInDays;
      public int dummyVariable = 10;

      Project(int duration) {
         System.out.println("Inside Project class constructor.");
         this.durationInDays = duration;

         totalProjects++;
         System.out.println("Total Company projects: " + totalProjects);

         System.out.println("Calling private method of Organization class from Project class");
         greetings();
    }

    public void displayDuration() {
      System.out.println("Inside Project class displayDuration method");
      System.out.println("Project duration: " + this.durationInDays);
    }
  }
}

class NestedClassTest {
  public static void main(String[] args) {
    Organization orgObject = new Organization(); // create an object

    // now create a new project of the Organization
    orgObject.createProject();
  }
}

output

Inside Organization class constructor

Total Organization projects: 0
Inside Project class constructor.
Total Company projects: 1
Calling private method of Organization class from Project class
Greetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 10
Inside Project class constructor.
Total Company projects: 2
Calling private method of Organization class from Project classGreetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 20

Explanation of the program

In the above program, we have created outer class Organization, and inside it, we have created an inner class Project*. In the output, we have decided to directly access the methods and variables of an outer class Organization from the inner class Project.


2) Multiple non-static nested classes

The non-static nested class is a class within another class and should be accessible to members of the enclosing class (outer class). This class is also known as an inner class in Java. While an inner class exists within the outer class, you must instantiate the outer class first in order to instantiate the inner class.

Example

class OuterClass {
    int outer_a = 75;

    void test() {
        InnerClass inner = new InnerClass();
        inner.show();
    }

    // Inner Class
    class InnerClass {
        void show() {
            System.out.println("Inner class show() method : outer_a = " + outer_a);
        }
    }
}

class InnerClassTest {
    public static void main(String args[]){
        OuterClass outer = new OuterClass();
        outer.test();
    }
}

Output

Inner class show() method : outer_a = 75

Explanation

In the above program, we have created OuterClass and InnerClass classes, and also defined test()method in OuterClass and show() method in InnerClass. As you can see, we are able to access the outer_a variable directly without creating the object of an outer class.

That’s all about how to have multiple classes in one file in Java

]]>
https://java2blog.com/multiple-classes-in-one-file-in-java/feed/ 0
How to break out of nested loops in Java https://java2blog.com/break-out-of-nested-loops-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=break-out-of-nested-loops-in-java https://java2blog.com/break-out-of-nested-loops-in-java/#respond Thu, 22 Jul 2021 07:28:57 +0000 https://java2blog.com/?p=15619 In this post, we will see how to break out of nested loops in Java.

Using break (will break inner loop)

It is very important to understand how nested loops work to ensure that applying break will output the desired result.

If you are a novice with nested loops, I am going to make the concept as easy as possible for you to understand.

When you apply break in the inner loop, it results in breaking the loop when a specific condition is met, but the outer loop continues to execute.

The following nested loop outputs the result of multiplying the two loops until the outer loop reaches position 3.

The loop will skip position 3 and continue executing for the remaining positions.

public static void main(String[] args){
        //using break
        for (int i=1; i<=5; i++){
            for (int j=1; j<=5; j++){
                if (i == 3) break;{
                    System.out.println(i +" * " +j+" = "+(i*j));
                }
            }
        }
}

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16

Using named loop

In the first example we discussed, the nested loop continued to execute the outer loop after breaking position 3.

To prevent the outer loop from continuing to execute, we can use a named loop which is simply a loop with a label.

When the condition is met, instead of just breaking the nested loop, we want to add the named loop to the break statement to ensure that it breaks the outer loop.

For this approach, the nested loop will print out the product of the two loops until the outer loop reaches position 3.

The break statement will break the outer loop preventing it from iterating further.

//using named loop
public static void main(String[] args){
     firstLoop: for (int i=1; i<=4; i++){
            for (int j = 1; j <= 4; j++) {
                if (i == 3) break firstLoop;{
                    System.out.println(i + " * " + j + " = " + (i * j));
                }
            }
        }
}

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8

Using named block

Block is a sequence of statements containing local classes and variables within braces and can be used to break out of nested loops.

The block executes the statements one by one until the last line of code. If the code executes successfully, the block terminates successfully, and the same case applies if the code terminates abnormally.

To break out of a nested loop using this approach, we will print out the product of the nested loop until a condition is fulfilled.

Once the condition is fulfilled, we will break the execution of the block, which will, in effect, break the execution of the nested loop.

The block will break the nested loop when the product is equal to 4, and you can also add some statements to be executed if the condition was not valid before the closing braces of the block.

public static void main(String[] args){
     block: {
            for (int i = 1; i < 5; i++) {
                for (int j = 1; j < 5; j++) {
                    if ((i * j) == 4) break block;{
                        System.out.println(i+" * "+j+" = "+(i*j));
                    }
                }

            }
            System.out.println("The nested loop failed");
        }
}

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

Using return

The return keyword works the same way as the break keyword by terminating the nested loop after a condition is met but returns a value for the loop to break.

To break from nested loops using the return approach, create a method and initialize a value that will be returned by the method once a condition is met.

The following example initializes the variable named multiply with 1 and tracks the multiplication of the nested loops until the result of the multiplication is 8.

When the product is 8, the method will return the value, and the nested loop will break immediately.

The for loop will also be printing out the product of the nested loops until the condition is met.

//using return
 public static int usingReturn(){
        int multiply = 1;
        for (int i=1; i<=5; i++){
            for (int j=1; j<=5; j++){
                multiply = (i*j);
                if (multiply == 8)return multiply;{
                    System.out.println(i +" * "+j+" = "+multiply);
                }

            }
        }
        return multiply;
    }
public static void main(String[] args){
    System.out.println(usingReturn());
}

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
8

Conclusion

In this tutorial, you have learned four ways that you can use to break out of nested loops in java. The methods you covered include using break, return, named loop, and named block.

]]>
https://java2blog.com/break-out-of-nested-loops-in-java/feed/ 0
public static void main(String[] args) – Java main method https://java2blog.com/public-static-void-main-string-args-java-main-method/?utm_source=rss&utm_medium=rss&utm_campaign=public-static-void-main-string-args-java-main-method https://java2blog.com/public-static-void-main-string-args-java-main-method/#respond Fri, 11 Jun 2021 06:40:21 +0000 https://java2blog.com/?p=15037 If you have worked with Java programs before, you know that all Java programs start by running the main() method(public static void main(String[] args)). The main() method is the entry point.
The signature of the main method is fixed, and each portion of the statement has significance.

Why is the main method so important?

The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.

The execution of Java program, the java.exe is called. The Java.exe inturn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program stops execution.

Syntax

There are mainly three ways in which we can write the main method in Java. They are as follows:

public static void main(String[] args)
public static void main(String... args)
static public void main(String args[])

Besides these keywords, we can also attach the final, synchronized, and strictfp keywords in the main method.

Explanation of the Keywords

The keywords in the method: public static void main(String args[]) are as follows:
public: Public is an access specifier. Marking a method as public makes it visible to all methods across all packages. We need to mark the main() method as public otherwise, it is not visible to the JVM.
static: The JVM invokes the main method without creating objects and hence the main method needs to be marked static.
void: Since the main method does not need to return anything, the main method is marked void. If we define a return type for the main method, the program execution fails.
main(): This is the default signature as defined by the JVM.
String args[]: These are arguments passed to the main method so that users can give inputs while running the program in the form of an array of Strings.

Examples of Java main method Programs

Simple Java Program

The first example we see is the correct way to run the main method.

public class SimpleProgram{ 

  public static void main(String[] args) {
      System.out.println("Hello World!!");  
  }
}

The Output of this program is
Java main method output 1

Passing arguments in the main method

If we pass arguments in the main method, we can use them as follows:

public class SimpleProgram{ 

  public static void main(String[] args) {
      System.out.println("Hello Dear " + args[0]);  
  }
}

Where args is the array we pass as arguments to the main method.
Java main method output 2

Non-Public main method.

If we declare the main method as private, the program compiles but running the program results in an exception.

private static void main(String[] args) {
    System.out.println("Hello Dear " + args[0]);
    }

Output
Java main method output 3

Defining a return value for the main method

If we define the main method to have a return value then the Java program will compile but will result in an exception as follows:

public static int main(String[] args) {
    System.out.println("Hello Dear " + args[0]);
    return 0;
}

Output
Java main method output 3

Overloading the main method

We have overloaded the main method to have an Integer array and a Character array in this example. We have also included the original definition of the main method. These definitions are allowed and valid, and so the code compiles. However, if we observe when the code runs, only the original definition of main i.e. public static void main(String[] args) executes.

public class SimpleProgram {

    public static void main(Integer args) {
        System.out.println("Overloaded method 1 with Integer args");
    }

    public static void main(char args) {
        System.out.println("Overloaded method 1 with char args");
    }

    // Original main() method
    public static void main(String[] args) {
        System.out.println("Main as it should be");
    }
}

Output
Java main method output 5

Questions

Can we run java without main method?

Answer: You can not run main method without main method Java 8 onwards.
Here are the steps performed by jvm.

  1. JVM will load class.
  2. It will execute static blocks of the class.
  3. It will search for main method.

If static blocks are present in the class, then they will be executed even though there is no main method in the class.

Here is an example:

package org.arpit.java2blog.entry;

public class JavaHelloWorldWithoutMain {

    static {
        System.out.println("In staic block");
    }
}

When you will try to run this java program using java JavaHelloWorldWithoutMain, you will getbelow output:

In staic block
java.lang.NoSuchMethodError: main

Can we have more than one main method in class

Yes, you can have multiple main method in the class, but when you execute java program, only method with signature public static void main(String[] args) will be called.

Conclusion

In the above article, we saw the public static void main(String[] args)- main method in Java and all its variants.

]]>
https://java2blog.com/public-static-void-main-string-args-java-main-method/feed/ 0