new, switch and assert keywords in Java
Table of Contents
As we talked about abstract, for and continue keywords in our last article. We will be talking about the new, switch, and assert keyword in Java.
new
When we create a class in Java and decide to use this class, we need to make an object of this class and using the object of the aforementioned class, we control and use the components of the class.
An object of a class works like the handle of a motorbike. Suppose you need to control the bike; you need to hold the handle of this bike. I believe you have understood why we need to create an object.
If the object is so important, you must be thinking that we need to know how to create an object of a class. We create an object of a class by using the ‘new’ keyword. The ‘new’ keyword gives the processor instructions to hold the memory in the system to store the object of this class.
Car.java Class Code
package newKeyword;
public class Car {
public String ColorOftheCar;
public int HightOftheCar;
public void StarttheEngine() {
System.out.println("Engine is Running");
}
}
Main Class
package newKeyword;
public class Hello {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car.ColorOftheCar = "Red");
System.out.println(car.HightOftheCar = 5);
car.StarttheEngine();
}
}
Explanation
As you can see in the above program. We created a class named Car, and in that class, we created two variables to hold the color of the car and the height of the class. There is one function to start the engine of the car. We first created the variable of type Car class.
Car car
Then gave this variable a memory to hold the object of the type Car class.
Car car = new Car();
Later on, the ‘car’ variable acted as the object of the class, and we used this word to set the color and size of the car and invoked the method named car.StarttheEngine().
switch
The switch case is used to print one statement or execute one block of code based on the value of a variable. Let us take an example.
Example –
In a program, if the value of a variable ‘X’ is 1, the statement should be printed as ‘The value of X is 1’. If the value of variable ‘X’ is 2, the statement should be printed as ‘The value of X is 2’. If the value of ‘X’ is something else other than 1,2, then the statement should be printed as ‘The value of ‘X’ is something else.
Syntax
switch (key) { case value: break; default: break; }
Programs
public class Switch { public static void main(String[] args) { int X =3; switch (X) { case 1: System.out.println("The value of X is 1"); break; case 2: System.out.println("The value of X is 2"); break; default:System.out.println("The value of X is something else"); break; } } }
In the above program, we have just printed some statements, but the same switch can be used to print one block of code as well by using the {code goes here}. Let us see the same program below.
public class Switch { public static void main(String[] args) { int X =3; switch (X) { case 1: { System.out.println("The value of X is 1"); } break; case 2: { System.out.println("The value of X is 2"); } break; default: { System.out.println("The value of X is something else"); } break; } }
As you can see in the above program, the program is the same, but the only difference is the { } around the print statements. These { } creates a block which means the block can be used to execute a single block of code rather than printing just a statement if the condition is true.
Note – The switch statement can also take Strings as the case. Look at the program below.
public class Switch { public static void main(String[] args) { String X ="c"; switch (X) { case "a": { System.out.println("The value of X is a"); } break; case "b": { System.out.println("The value of X is b"); } break; default: { System.out.println("The value of X is something else"); } break; } } }
One question should come to your mind: Java is a case-sensitive language, and what will happen if someone gives upper-class String value. The whole program will fail. The switch has got that situation covered. You can add two cases of values. Look at the program below.
public class Switch { public static void main(String[] args) { String X ="c"; switch (X) { case "a": case "A": { System.out.println("The value of X is a"); } break; case "b": case "B": { System.out.println("The value of X is b"); } break; default: { System.out.println("The value of X is something else"); } break; } } }
Also, there is no upper limit on how many cases can be added here. The switch can take an ‘n’ number of cases. The default statement is for the situation when any case conditions are not met; the default statement or block of code will be executed.
assert
The assert keyword in java is used to test whether the program is working as expected or not. For example, you are making a program that has the age of a person. We both know a person’s age can never be negative and will always be greater than zero. When we run the program, we need a mechanism to check if the age is greater than zero or not. One way to do it is to use if statement. We can use if the value of a certain variable is greater than zero, then the program should be continued; otherwise, print a statement on the screen that the variable’s value is zero.
Another way of achieving this is to use the assert statement. You can assert and assert will through an AssertError to let the user know that the value is negative.
Note – Assert condition is believed to be true when running a program, and in case the condition is not true, AssertError is thrown. Also, be informed that Assertion is an Error, not an Exception.
To use assertion, you will have to enable it because it is not by default enabled. I use Eclipse, so I will tell you how to enable assertion in Eclipse. You can use the following steps and enable assertion when using Eclipse.
Steps to Enable Assertion in Eclipse
After writing your program > Go to Window tab on the Menu Bar > Click Preferences > Expand Java option on the left-hand side > Click on Installed JREs > Click on Configuration File on right-hand side > Click Edit Button > In Default VM Arguments Field type -ea > Press Finish Button > Press Apply Button > Press Apply and Close Button.
Assertion Example
package assertExample; public class AssertExample { static int val = 4; public static int getNum() { return val--; } }
Main Class
package Assert; import assertExample.AssertExample; public class Assert { public static void main(String[] args) { int n; for (int i = 0; i < 6; i++) { n = AssertExample.getNum(); assert n<=0 : "This Error will be thrown if the value of n is less than equal to zero"; System.out.println(n); } } }
Program Result
Program Explanation
As you can see in the above example program, we have created a separate class named assertExample, and in that class, we have declared a static int variable and a static method. The value of the static int variable is already initialized as 4. The static method named getNum() is used to call and return the value of the static variable, but the value is decremental. Decremental means every time when the variable has been used, the value inside that variable will be reduced by 1.
In the main method, we have declared an int variable and did not initialize its value because we will use it to store the value returned by the getNum() method. We created a ‘for loop’ and programmed it to run 6 times. The method is called directly by using the name of the class because the method is a static method and can be called with its class name.
The ‘for loop‘ keeps on invoking the getNum() method, and the value of its static int val variable inside the getNum() method keeps decreasing. In 5 repetitions, the value comes to zero. When the value comes to zero, the assertion gets invoked because the condition in the assert statement says the assertion should throw an AssertionError when the value of n comes to zero.
Versions of assert Statement
There are two versions of assert. In one version, you don’t get to show your own message when the assertion is invoked. In another version, you get an option where you can write your own statement to understand which assertions are invoked in case you are using multiple assertions in a program.
assert <condition>;
assert <consition> : "Your own message goes here";
You can see my above program. I have used the second version of the assertion. I have given my own message: “This Error will be thrown if the value of n is less than equal to zero”.
Conclusion
I hope you have understood the new switch and assert keywords in-depth and will be able to use them whenever you need them. We will continue this journey of learning Java in our next article and discuss the remaining keywords. Till then take care. Good Bye!
LinuxAndUbuntu Newsletter
Join the newsletter to receive the latest updates in your inbox.