Java Keywords With Examples
A complete list of Java keywords are covered with examples in hopes that they will satisfy educational requirements.
Java Keywords List
As a result of Java keywords, there are a set of reserved words that can’t be used as variables, methods, classes, or any other identifiers:
Java Keywords | Overview |
---|
abstract | Non-access modifiers are implemented for classes and methods. It is not possible to create objects out of abstract classes (you need to inherit them from another class). Methods that are abstract cannot be used outside of abstract classes, and they lack bodies. Subclasses (inherited from) provide the body to the method. |
assert | Debugging. |
boolean | Only true and false values can be stored in this data type. |
break | Exits a loop or switch block. |
byte | Whole numbers between -128 and 127 can be stored as a data type. |
case | Blocks of code in switch statements are marked by using it. |
catch | Try statements generate exceptions that are caught by this function. |
char | Data type for storing single characters. |
class | Classes are defined by this function. |
continue | A loop is continued to the next iteration. |
const | Constants are defined here. Inactive – use the final function in its place. |
default | When a switch statement is used, it specifies the default block of code to be executed. |
do | Do-while loops are created by using the do keyword in conjunction with the while keyword. |
double | Whole numbers between 1.7e’308 and 1.7e+308 are stored as this data type. |
else | Java keywords can be used in conditional statements. |
enum | Declares an enumerated type that cannot be changed. |
exports | A package with a module is exported. One of Java 9’s new features. |
extends | Inherits a class from another class (extends the class). |
final | Non-access modifiers are used to prevent classes, attributes and methods from changing (i.e. from inheriting or overriding). |
finally | Java keywords are used along with exceptions to define a block of code that is executed regardless of whether there is an exception or not. |
float | This type of data can store whole numbers from 3.4e−038 to 3.4e+038. |
for | Generates a for loop. |
goto | There is no function for this item, and it is not used. |
if | Declares a If condition. |
implements | Provides an interface for implementation. |
import | Imports a package, class, or interface by using the Java keyword import |
instanceof | Specifies whether or not an object is an instance of a specific class or an interface. |
int | This is a data type that is capable of storing whole numbers from -2147483648 to 2147483647. |
interface | The purpose of this method is to declare a special type of class that consists of only abstract methods. |
long | An array of whole numbers ranging from -9223372036854775808 to 9223372036854775808. |
module | Define a module. The Java keywords module has been updated in Java 9. |
native | Specifies that a method is not implemented in the same Java source file (but is implemented in another language instead). |
new | Creates new objects. |
package | Creates a package. |
private | Access modifiers are used for attributes, methods, and constructors, limiting their accessibility to the declared class only. |
protected | Ensures that attributes, methods, and constructors are accessible within a package and subclass only. |
public | An access modifier used for classes, attributes, methods and constructors, making them accessible by any other class. |
requires | Specifies required libraries inside a module. New in Java 9. |
return | Finished the execution of a method, and can be used to return a value from a method in Java keywords. |
short | A data type that can store whole numbers from -32768 to 32767. |
static | A non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class. |
strictfp | Restrict the precision and rounding of floating point calculations. |
super | Refers to superclass (parent) objects. |
switch | Selects one of many code blocks to be executed. |
synchronized | A non-access modifier, which specifies that methods can only be accessed by one thread at a time. |
this | Refers to the current object in a method or constructor. |
throw | Creates a custom error in Java keywords. |
throws | Indicates what exceptions may be thrown by a method. |
transient | A non-accesss modifier, which specifies that an attribute is not part of an object’s persistent state. |
try | Creates a try-catch statement. |
var | Java 10 introduces new features – Defines a variable. |
void | This declares that a method should not have a return value. |
volatile | Attributes are not cached thread-locally, but are always read from main memory. |
while | It sets up a while loop. |
Abstract Keyword In Java
In Java keywords, the abstract keyword acts as a non-access modifier for both classes and methods.
Abstract class: Abstract classes cannot generate objects (they must inherit from another class to be accessed).
Abstract Method: Abstract methods are only usable in abstract classes. Such methods do not contain a body. The body is provided by subclasses (inherited from the Abstract class).
When talking abstract keyword in Java, these methods belong to the abstract class, and their bodies are empty.
Instead, the subclasses provide the body to it.
The following example shows the use of Abstract Method and Abstract Class in a more efficient way:
// Code from filename: Main.java
// abstract class is initiated below
abstract class Main {
public String studnet_Name = "Mike";
public int student_Age = 21;
public abstract void admission_Eligibility_Check(); // abstract method is declared here
}// Subclass (inherit from Main)
class Student_Detail extends Main {
public int Convocation_Year = 2005;
public void student_Character() { // the body of the abstract method is provided here
System.out.println("Mike as a student is passionate,hardworking and highly motivated. He has volunteered in many projects in the Last School he attended.");
}
public void admission_Eligibility_Check(){
System.out.println("Student is Eligible to be a part of this university ");
}
}
// End code from filename: Main.java// Code from filename: First.javapublic class First {
public static void main(String[] args) {Student_Detail mrx=new Student_Detail();System.out.println("Name of Student: " + mrx.studnet_Name);
System.out.println("Age of Student: " + mrx.student_Age);
System.out.println("Graduation Year: " + mrx.Convocation_Year);
mrx.admission_Eligibility_Check(); // An abstract is called here
mrx.student_Character();}
}
Similarly, To learn about abstract classes more clearly, refer to the given example:
// Code from filename: Main.java
// abstract class is initiated below
abstract class Main {public int number1=67;
public int number2=12;
public abstract void product_Numbers(); // abstract method is declared here
}// Subclass (inherit from Main)
class Mathematical_Operation extends Main {
public int mrx=20;public int ample=50;public void product_Numbers(){ // the body of the abstract method is provided hereSystem.out.println(number1+" x "+number2+" = "+(number1*number2));
}
public void add_Numbers() {
System.out.println(mrx+" + "+ample+" = "+(ample+mrx));
}}
// End code from filename: Main.java// Code from filename: First.javapublic class First {
public static void main(String[] args) {Mathematical_Operation mrx_obj=new Mathematical_Operation();System.out.println("\nUsing Abstract Product method: \n");
System.out.println("Value of Number 1: "+mrx_obj.number1);
System.out.println("Value of Number 2: "+mrx_obj.number2);
mrx_obj.product_Numbers();System.out.println("\nUsing Addition Method from the class Mathematical_Operations: \n");
System.out.println("Value of Number 1: "+mrx_obj.mrx);
System.out.println("Value of Number 2: "+mrx_obj.ample);
mrx_obj.add_Numbers();
}
}
Boolean Keyword In Java
Java Boolean keyword denotes a data type that can take only 2 types of values either true or false.
Usually, Boolean values are utilized for testing conditions.
Keep in mind when it comes to Java Keyword Boolean, the boolean data type has either true or false values.
The given code shows the use of boolean variables:
public class Main {
public static void main(String[] args) {boolean isItFunLearningJava=true;
boolean isJavaDifficultToUnderstand=false;System.out.println("Is it Fun to Learn Java ? ");
System.out.println("Answer: "+isItFunLearningJava);
System.out.println("\nIs Java Difficult to Understand ? ");
System.out.println("Answer: "+isJavaDifficultToUnderstand);
}
}
The following programme shows the views of people regarding America. The answers to their responses are given, creating the boolean variables using the boolean keyword:
public class Main {
public static void main(String[] args) {boolean isAmericaTheMostDesiredPlaceToLive=true;
boolean areAmericansArrogant=false;System.out.println("Is American The Most Desired place to live in? ");
System.out.println("Answer: "+isAmericaTheMostDesiredPlaceToLive);
System.out.println("\nSome people term American citizens as arrogant. Is this true? ");
System.out.println("Answer: "+areAmericansArrogant);
}
}
Break Keyword In Java
As we are talking about Java keyword break, we are referring to the keyword that is used to break out of a loop like a for loop, while loop or switch block.
When the value of mrx equals 7, the loop should be terminated as follows:
public class Main {
public static void main(String[] args) {for(int mrx=1;mrx <=100;mrx++){
if(mrx==7){
break;
}
System.out.println(mrx);
}
}
}
Although the loop is assigned 100 cycles but because of the break keyword it stops the iteration when mrx becomes 7.
Similarly, the break keyword can also be used while traversing through a string array:
public class Main {
public static void main(String[] args) {String programming_Languages[]= {
"1. Javascript\n",
"2. Python\n",
"3. Go\n",
"4. Java\n",
"5. Kotlin\n" ,
"6. PHP\n" ,
"7. C#\n" ,
"8. Swift\n" ,
"9. R\n" ,
"10. Ruby\n" ,
"11. C and C,,\n" ,
"12. Matlab\n" ,
"13. TypeScript\n" ,
"14. Scala\n" ,
"15. SQL\n" ,
"16. HTML\n" ,
"17. CSS\n" ,
"18. NoSQL\n" ,
"19. Rust\n" ,
"20. Perl" };for(int ample=0;ample<=19;ample++){
if (ample==8){
break;
}
System.out.println(programming_Languages[ample]);
}
}
}
In the above example, despite the fact that the array contained 20 elements but because of the existence of the break keyword it did not print anything anymore when it reached the index number (8) of the Array.
We can also use the break keyword in a while loop.
The while loop is terminated when the value of mrx becomes 9:
public class Main {
public static void main(String[] args) {int mrx=1;while(mrx <= 200){
System.out.println(mrx);
mrx++;
if(mrx==9){
break;
}
}
}
}
Similarly, the break keyword in Java can also be used while traversing through an array.
As in the given example out of 10 teams,only 4 teams names are printed as the break keyword breaks the while loop when index (ample) reaches 4 (fifth element of the array american_Football_Club_Teams )
public class Main {
public static void main(String[] args) {String american_Football_Club_Teams[]={"Baltimore Ravens","Buffalo Bills","Cincinnati Bengals","Cleveland Browns","Denver Broncos","Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Kansas City Chiefs","Las Vegas Raiders"};int ample=0;while(ample < american_Football_Club_Teams.length){
System.out.println(american_Football_Club_Teams[ample]);
ample++;
if(ample==4){
break;
}
}
}
}
Byte Keyword In Java
With the byte keyword, you can store whole numbers between -128 and 127.
The given example shows the use of byte datatype to store a value of 89 to the the variable named mrx_Number;
public class Main {
public static void main(String[] args) {byte mrx_Number=89;
System.out.println("Byte Value: "+mrx_Number);
}
}
public class Main {
public static void main(String[] args) {byte ample_Numbers=19;
byte mrx_Numbers=78;
System.out.println(ample_Numbers+ "+" +mrx_Numbers+" = "+(ample_Numbers+mrx_Numbers));
}
}
Case Keyword In Java
When we talk about Java keyword Case, the keyword case traces a code block enclosed in a switch statement.
The following examples shows the use of Case Keyword :
public class Main {
public static void main(String[] args) {int american_football_team=6;
switch (american_football_team){case 1:
System.out.println("Arizona Cardinals");
break;
case 2:
System.out.println("Atlanta Falcons");
break;
case 3:
System.out.println("Baltimore Ravens");
break;
case 4:
System.out.println("Buffalo Bills");
break;
case 5:
System.out.println("Chicago Bears");
break;
case 6:
System.out.println("Carolina Panthers");
break;
case 7:
System.out.println("Cleveland Browns");
break;
case 8:
System.out.println("Cincinnati Bengals");
break;
}
}
}
public class Main {
public static void main(String[] args) {char mrx_vowels='I' ;
switch (mrx_vowels){case 'A':
System.out.println("This is a vowel A");
break;
case 'E':
System.out.println("This is a vowel E");
break;
case 'I':
System.out.println("This is a vowel I");
break;
case 'O':
System.out.println("This is a vowel O");
break;
case 'U':
System.out.println("This is a vowel U");
break;
case 6:
System.out.println("Carolina Panthers");
break;}
}
}
Catch Keyword In Java
In the case of Catch Keyword in Java, the catch keyword captures the exceptions produced by try statements.
In case of an error in the try block, the catch statement executes a block of code.
Whenever an error occurs, you should use try-catch to catch the error and execute some code to deal with it in the following way:
public class Main {
public static void main(String[] args) {try {
String [] billionaires = {"Elon Musk","Bernard Arnault","Jeff Bezos","Gautam Adani","Bill Gates"};
System.out.println(billionaires[5]);
} catch (Exception e) {
System.out.println("There is no such index number in the billionaires array, enter the correct index number");
}
}
}
public class Main {
public static void main(String[] args) {int [] prime={2,3,5,7,11,13,17,19,21,23,27};
try {
int mrx;
for(mrx=0;mrx<=13;mrx++){
System.out.println("Number "+mrx+" = "+prime[mrx]);
}} catch (Exception e) {
System.out.println("All the elements of the array are printed successfully and the array does not any element at index number 11 or more ");
}
}
}
Char Keyword In Java
Each character is stored in the char data type.
You must surround char values with single quotes, like ‘B’ or ‘e’.
public class Main {
public static void main(String[] args) {char mrx_alpha='K';System.out.println("The given variable is : "+mrx_alpha);
}
}
public class Main {
public static void main(String[] args) {char mrx_alpha1='M';
char ample_alpha2='r';
char mrx_alpha3='E';
char ample_alpha4='x';
char mrx_alpha5='a';
char ample_alpha6='m';
char mrx_alpha7='p';
char ample_alpha8='l';
char mrx_alpha9='e';
char ample_alpha10='s';System.out.println("\nYou are Learning Char Keyword from: \n");
System.out.println(mrx_alpha1);
System.out.println(ample_alpha2+"\n");
System.out.println(mrx_alpha3);
System.out.println(ample_alpha4);
System.out.println(mrx_alpha5);
System.out.println(ample_alpha6);
System.out.println(mrx_alpha7);
System.out.println(ample_alpha8);
System.out.println(mrx_alpha9);
System.out.println(ample_alpha10);}
}
Class Keyword In Java
When it comes to Java Keyword Classes, the class keyword generates a class.
Java requires every line of code to be inside a class.
There should always be an uppercase first letter in the class name, and the Java file name should be the same as the class name.
An object’s constructor is analogous to a class.
Below is an example of how it can be implemented in order to declare an object:
public class MyFirstClass {
public static void main(String[] args) {
System.out.println("Greetings ! We are learning here how to create a class in Java");
}
}
Correspondingly, it is possible to create as many classes as we want, by assigning different names to them:
public class MyAnotherClass {
public static void main(String[] args) {
System.out.println("In this way multiple classes can be created using distinct names");
}
}
In the example below, we declare an object of the MyFirstClass class and name it “mrx_Obj” which prints the value of ample (String):
public class MyFirstClass {String ample="Mr Examples";
public static void main(String[] args) {MyFirstClass mrx_Obj=new MyFirstClass();
System.out.println("Hey ! You are currently on : "+mrx_Obj.ample);
}
}
public class MyFirstClass {String ample="Java";
String mrx="Class";String txt="Keyword";
public static void main(String[] args) {MyFirstClass mrx_Obj=new MyFirstClass();
System.out.println("You are learning about "+mrx_Obj.ample+" "+mrx_Obj.mrx+" "+mrx_Obj.txt);
}
}
Continue Keyword In Java
In the case of the keyword continue, while using a for loop (or a while loop), the continue keyword terminates the current iteration, and the next iteration proceeds.
In the case of mrx = 2, skip this iteration and continue with the next:
public class MyFirstClass {public static void main(String[] args) {for(int mrx=1;mrx<=20;mrx++){
if (mrx ==2){
continue;
}
System.out.println(mrx);
}
}
}
public class MyFirstClass {// Currency Codes// USD = United States Dollar
// EUR = Euro
// AUD = Australian Dollar
// CAD = Canadian Dollar
// DKK = Danish Krone
// MVR = Maldivian Ruffian
// CNY = Chinese Yen
public static void main(String[] args) {String currency_Codes[]={"USD","EUR","AUD","CAD","DKK","MVR","CNY"};
for(int mrx=0;mrx<=6;mrx++){
if (mrx ==3){
continue;
}
System.out.println(currency_Codes[mrx]);
}
}
}
Using a while loop, we can also implement the continue keyword:
public class MyFirstClass {public static void main(String[] args) {int mrx=1;while (mrx <= 15){
if (mrx==4){
mrx++;
continue;
}
System.out.println(mrx);
mrx++;
}
}
}
After the execution of the while loop you will notice that all numbers are printed except 4 which satisfies the working of continue keyword.
Correspondingly, We can also use the continue keyword while traversing through an array named : popular_Destination_Of_America:
public class MyFirstClass {
public static void main(String[] args) {String popular_Destinations_Of_America[]={"New York","Chicago","Los Angeles","Washington D.C","San Francisco"};int ample=0;while (ample <= 4){
if(ample==2){
ample++;
continue;
}
System.out.println(popular_Destinations_Of_America[ample]);
ample++;
}
}
}
Default Keyword In Java
When it comes to the keyword default in Java, the default keyword is the default block of code in a switch statement.
In the case that a switch does not match the case, the default keyword specifies some code to run.
In addition: In the case of the default keyword being used as the last statement in a switch block, you do not need to put a break keyword to it.
Here we have used 5 cases of the switch statement, hence upon entering 6 as the case value the default code is executed:
public class MyFirstClass {
public static void main(String[] args) {int america_Famous_Foods=6;switch (america_Famous_Foods){case 1:
System.out.println("Fajitas");
break;case 2:
System.out.println("Jerky");
break;case 3:
System.out.println("Twinkies");
break;case 4:
System.out.println("Pot roast");
break;case 5:
System.out.println("Cobb salad");
break;default:
System.out.println("There is no dish name at "+america_Famous_Foods+" hence they default keyword statement is executed");}}
}
Correspondingly, the given example indicates if a number is even or odd :
public class MyFirstClass {
public static void main(String[] args) {int case_Value=11;int mrx_Result=case_Value%2;switch (mrx_Result){case 0:
System.out.println(case_Value+" is an Even Number");
break;default:
System.out.println(case_Value+" is an Odd Number");}}
}
Since, 11 % 2 = 1 (not 0) hence the default statement executes.
Do Keyword In Java
When it comes to Java Keyword Do, the do keyword is used together with the while keyword in order to generate a do-while loop.
In a while loop, a block of code is repeatedly executed until a specified condition is achieved.
A Do/while loop is an extension of the while loop.
In this loop, the code block will be executed once, before checking if the condition is true, and then the loop will be repeated if the condition is true.
Remember: Make sure the condition variable is increased, otherwise the loop will never terminate.
Despite the condition being false, the following loop will always run at least once since the code block is executed before the condition is evaluated:
public class Main{
public static void main(String[] args) {int ample=1;
do{
System.out.println(ample);
ample++;
}
while (ample<=4);
}
}
This prints all the natural numbers from 1 to 4, as the condition is checked after printing the code.
The Given example shows the use of Do While Loop while traversing through the elements of the array:
public class Main{
public static void main(String[] args) {String it_Companies_America[]={"Hyperlink InfoSystem","Apex Systems","Kin+Carta","Cognizant","Apexon"};
int mrx=0;
do{
System.out.println(it_Companies_America[mrx]);
mrx++;
}
while (mrx<=4);
}
}
As a result, all the elements of the array are printed because of prior printing of the elements than the condition.
Double Keyword In Java
The double keyword generates a double data type that is capable of holding decimal numbers within a range of 1.7 x 10^-308 to 1.7 x 10^308.
It is important to keep in mind that when specifying a value for the double data type, it should be suffixed with the letter “d”.
The following example shows how to print the value of a double variable (mrx):
public class Main{
public static void main(String[] args) {double mrx=52.3243245423412d;
System.out.println("Value of Double variable mrx= "+mrx);
}
}
Here we get the product of two double data type variables (mrx and ample):
public class Main{
public static void main(String[] args) {double mrx=16.35423452523525423d;
double ample=76.233212312312321d;System.out.println("Product of two double values (Ample and mrx)= "+mrx+" x "+ample);
System.out.println("Result: "+(mrx*ample));}
}
Else Keyword In Java
The else keyword in Java is used in conjunction with an if statement to specify a block of code to be executed if the condition specified in the if statement is false.
In addition to the else statement, Java also offers other conditional statements such as:
- The if statement, which is used to specify a block of code to be executed if a specified condition is true.
- The else statement in Java is used to specify a block of code to be executed if the condition specified in the corresponding if statement is false. It allows for the execution of an alternative block of code in case the condition evaluated in the if statement is not met.
- The else if statement, which is used to specify a new condition to test if the first condition is false.
- The switch statement, which is used to specify multiple alternative blocks of code to be executed based on the value of an expression.
We can use the else if statement and assign it with a new testing condition in case the if condition gets false.
By using if else statements we can design a programme to calculate specific amounts of discounts at different ranges of bill as shown in the example below:
public class Main{
public static void main(String[] args) {float total_Bill_In_Dollars=76;
float discount;
float new_Bill;if (total_Bill_In_Dollars >= 100) {
discount = (float) (total_Bill_In_Dollars * 10 / 100);
System.out.println("New Bill after 10% Discount: " + total_Bill_In_Dollars+" $" + " – " + discount+" $" + " = " + (total_Bill_In_Dollars – discount)+"$");
}
else if (total_Bill_In_Dollars>= 50) {
discount=(float)(total_Bill_In_Dollars*5/100);
System.out.println("New Bill after 5% Discount: "+total_Bill_In_Dollars+" $"+" – "+discount+" $"+" = "+(total_Bill_In_Dollars-discount)+" $");
}
else {
System.out.println("No Discount is Available Total Bill is: "+total_Bill_In_Dollars+" $");
}
}
}
Correspondingly, the following program takes the time range as an string input and displays a message accordingly :
public class Main{
public static void main(String[] args) {// Time ranges// 1) Morning
// 2) AfterNoon
// 3) Evening
// 4) NightString time_Range="Evening";if(time_Range=="Morning"){
System.out.println("Good Morning Dear User !! Have a good day ");
}
else if(time_Range=="AfterNoon"){
System.out.println("Hello Dear! Its time to eat something for lunch");
}
else if(time_Range=="Evening"){
System.out.println("The cold winds and the pleasant weather !! how good could these evening be !");
}
else{
System.out.println("GoodNight Dear User ! Its time to sleep ! Have good dreams");
}
}
}
Enum Keyword In Java
While discussing the Java keyword enum, the enum keyword declares an enum (immutable) type.
An enum is a distinct “class” that symbolizes a collection of constants (unchangeable variables, similar to final variables).
Use the enum keyword to build groups of constants, separate them with commas, and make sure they are all uppercase.
The given example shows the creation of an enum named genders with non-modifiable values:
public class Main {
public static void main(String[] args) {enum mrx_genders{
MALE,
FEMALE,
TRANSGENDER
}mrx_genders ample=mrx_genders.MALE;
System.out.println(ample);
}
}
We can also create the enum of football field positions as shown below:
public class Main {
public static void main(String[] args) {enum mrx_Football_Positions{
FORWARD,
MID_FIELD,
DEFENSE,
GOAL_KEEPING
}mrx_Football_Positions ample=mrx_Football_Positions.DEFENSE;
System.out.println("Position: "+ample);
}
}
Enum vs Classes
Enums can have attributes and methods just like classes do. Enum constants are static, public, and final (i.e., they cannot be changed and cannot be overridden), this is the only property which makes them unique from the classes.
As enums are incapable of extending from other classes , hence object creation is impossible in them, on the contrary they can implement interfaces to perform respective operations.
You can implement enums while declaring values that will remain the same forever such as month days, days, colors, deck of cards, etc.
Extends Keyword In Java
When it comes to Ref Keyword Extends, the extends keyword expands a class (which indicates that a class is inherited from another class).
An attribute or method can be inherited from one class to the other in Java. As a result, we can classify the “inheritance concept” into two types:
A subclass (also known as a child class) – a class that has been inherited from another class
A superclass (also known as parent class) – this is the class from which we are inheriting
The extends keyword is used when you want to inherit from a class.
The given example shows the way to inherit methods and attributes to a child class from a parent class:
class Parent_Ample{int parent_mrx1=2;
int parent_mrx2=6;
int product_mrx=(parent_mrx1*parent_mrx2);void parent_method(){
System.out.println("This is a (Parent Class / Super Class / Base class) method");
}}
class Child_Mrx extends Parent_Ample{public static void main(String[] args) {Child_Mrx new_object=new Child_Mrx();System.out.println("The Product of "+new_object.parent_mrx1+" and "+new_object.parent_mrx2+" is = "+new_object.parent_mrx1+" x "+ new_object.parent_mrx2+" = "+(new_object.product_mrx));
new_object.parent_method();
}}
The following example shows the use of attributes and methods of the base class using the derived class object:
class BloodGroups{String type1="A";
String type2="B";
String type3="O";
String type4="AB";
void blood_groups_bio(){
System.out.println("Blood types (also known as blood groups) are a classification system for blood,\nbased on the presence or absence of antibodies and antigenic substances\ninherited from an individual and present on the surface of red blood cells (RBCs) on the surface of the cells.");
}}
class BloodGroup_types extends BloodGroups{void types_of_blood_groups(){
System.out.println("\nGenerally speaking, there are four main blood types (blood types) – A, B, AB, and O.\nThe genes that your parents pass on to you are responsible for determining your blood group.");
}
public static void main(String[] args) {BloodGroup_types obj=new BloodGroup_types();obj.blood_groups_bio();
obj.types_of_blood_groups();
System.out.println("\nType 1: "+obj.type1);
System.out.println("Type 2: "+obj.type2);
System.out.println("Type 3: "+obj.type4);
System.out.println("Type 4: "+obj.type3);}}
Final Keyword In Java
When it comes to Final Keyword in Java, it is not possible to inherit or override a class, attribute or method using this non-access modifier.
A variable that always stores the same value should be declared with the final keyword, such as the PI variable (3.14159).
The final keyword is also referred as a “modifier”.
To prevent a variable from being overridden or modified, set it to the final state:
public class Main {
public static void main(String[] args) {
final String united_States_President ="Joe Biden";System.out.println(united_States_President+" is the president of United States Since January 20, 2021");united_States_President="Donald J. Trump";
System.out.println("New President of United States is: "+united_States_President);// Hence the value of the final keyword can not be modified hence this code generates as error}
}
Below given programme shows the modification of a variable that was made constant using the final keyword, hence upon execution an error will be generated:
public class Main {
public static void main(String[] args) {
final int hours_a_day=24;System.out.println("There are "+hours_a_day+" hours a day");hours_a_day=25;
System.out.println("We changed the fixed number of hours from 24 to "+hours_a_day);// In this case, it is not able to modify the value of the final keyword, which leads to this code generating an error.}
}
Finally Keyword In Java
The finally keyword executes code regardless of whether there is an exception (used in try-catch statements).
Regardless of the outcome, they are responsible to run code after try-catch.
import java.io.IOException;
public class Main {
public static void main(String[] args) {String united_States_Landmarks[]={"Statue of Liberty","Golden Gate Bridge","Mount Rushmore National Memorial","Empire State Building","Lincoln Memorial","The Gateway Arch","Space Needle"};
try {
System.out.println("Famous Landmarks of United States: \n");
for (String mrx : united_States_Landmarks) {
System.out.println(mrx);
}
}
catch (Exception e){
System.out.println("An error Occurred during code execution");
}
finally {
System.out.println("\nThe try-catch is executed and the rest of the code can be executed from the next line");
}
}
}
The try-catch is executed and the rest of the code can be executed from the next line
The given example shows the execution of the finally block even if the code generates an error in the try catch statement:
import java.io.IOException;
public class Main {
public static void main(String[] args) {String united_States_Innovations[]={"Transistors","Internet","The hearing aid","Chocolate chip cookies","Kevlar"};
try {
System.out.println("Innovations of United States: \n");
for(int mrx=0;mrx<6;mrx++){
System.out.println(united_States_Innovations[mrx]);
}
}
catch (Exception e){
System.out.println("\nAll indexes upto 4 from the Array are executed, and traversing array further generates an error");
}
finally {
System.out.println("\nAfter executing the try-catch, we can continue with the rest of the code from here.");
}
}
}
All indexes upto 4 from the Array are executed, and traversing array further generates an error
After executing the try-catch, we can continue with the rest of the code from here.
Float Keyword In Java
The float keyword used with a variable enables a special data type called float which can store fractional numbers that fall within the range 3.4e’038 to 3.4e+038.
It is important to note that you should end the value with an “f” or “F”:
public class Main {
public static void main(String[] args) {float java_compiler_version=17.0F;System.out.println("The Compiler on which you are executing the codes is java "+java_compiler_version);
}
}
The following programe shows the conversion of temperature from centigrade to Fahrenheit:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Temperature in Celsius: ");
float celsius=input.nextFloat();float fahrenheit= ((celsius*9)/5)+32;System.out.println("Temperature in Fahrenheit is: "+fahrenheit);
}
}
For Keyword In Java
Using the Java Keyword For, we can initialize a for loop that can iterate as many times as the condition is declared.
The following example shows the working of the for loop.
Here we print all the English language alphabets using their Ascii Codes:
public class Main {
public static void main(String[] args) {for (char ample=65;ample<=90;ample++){
System.out.println(ample);
}
}
}
Similarly, all the even numbers up to the user limit can be printed using the for loop as shown below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner mrx_obj=new Scanner(System.in);System.out.println("Enter Limit of Even Numbers here: ");
int user_Input=mrx_obj.nextInt();for (int ample=0;ample<=user_Input;ample++){
if(ample % 2==0){
System.out.println(ample);
}
}
}
}
From the example above:
- The first statement sets a variable before the loop begins (int ample = 0).
- The condition in statement 2 is that ample must be less than user_Input in order for the loop to run. The loop will restart if the condition is true, and it will end if it is false.
- The if condition checks the modulus of the number with respect to 2 if it shows 0, then it prints else it skips the iteration.
- Statement 3 increases a value (ample++) each time the code block in the loop has been executed.
A “for-each” loop is also available, which is primarily used to loop through the elements of an array one by one.
The following example shows the method of printing the names of top 6 brands of united states:
public class Main {
public static void main(String[] args) {
String united_States_Top_6_Brands[]={"Google", "Walmart", "Coca-Cola", "Apple", "Microsoft", "McDonald's"};System.out.println("The following are 6 Top brands of United States: \n");
for(String mrx:united_States_Top_6_Brands){
System.out.println(mrx);
}
}
}
Below example shows the method of taking 5 names as an user input and printing them back with the help of for each loop:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);
String names_5[]=new String[5];System.out.println("\nEnter Names here: ");
for (int mrx = 0; mrx < 5; mrx++) {names_5[mrx]=input.next();
}
System.out.println("\nNames You entered :\n");
for(String name:names_5){
System.out.println(name);
}
}}
If Keyword In Java
When it comes to Java Keyword If, the if statement indicates that a block of Java code will be executed if a certain condition is met.
The following conditional statements are available in Java:
- If a condition is met, use if to execute a block of code.
- In the case of a false condition, else is used to specify a block of code to execute.
- When the first condition isn’t true, specify an else if condition to test instead.
- Switches can be used to specify many alternative execution blocks.
Here we use string .equals() method to compare if two strings are exactly similar to each other or not:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Word1: ");
String mrx_text1=input.next();
System.out.println("Enter Word2: ");
String mrx_text2=input.next();if( mrx_text1.equals(mrx_text2)){
System.out.println("\n Exact Match");
}}
}
Correspondingly, the following programme takes a sentence and a word as user input and shows if the word is the part of the sentence or not:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Sentence here: ");
String mrx_sentence=input.nextLine();System.out.println("Enter Word to match: ");
String mrx_text2=input.next();if (mrx_sentence.contains(mrx_text2)){
System.out.println("The Sentence contains the word: "+mrx_text2);
}
}
}
Test variables with the if statement:
The following program shows the output only if the mrx is greater than ample:
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx = input.nextInt();System.out.println("Enter Number 2 here: ");
int ample = input.nextInt();if (Math.max(mrx, ample) == mrx) {
System.out.println("Mrx: " + mrx + " is greater than Ample: " + ample);
}
}
}
Similarly, if ample is greater than mrx we get the output otherwise nothing is printed:
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx = input.nextInt();System.out.println("Enter Number 2 here: ");
int ample = input.nextInt();if (Math.max(mrx, ample) == ample) {
System.out.println("Ample: " + ample+ " is greater than mrx: " +mrx);
}
}
}
When the condition is false, an else statement is used to specify a block of code that should be executed.
Considering the example we created above, here we use the else statement along with if to get outputs in both conditions (either condition is met or not) :
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx = input.nextInt();System.out.println("Enter Number 2 here: ");
int ample = input.nextInt();if (Math.max(mrx, ample) == mrx) {
System.out.println("Mrx: " + mrx + " is greater than Ample: " + ample);
}
else{
System.out.println("ample: " + ample+ " is greater than mrx: " + mrx);
}
}
}
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx = input.nextInt();System.out.println("Enter Number 2 here: ");
int ample = input.nextInt();if (Math.max(mrx, ample) == ample) {
System.out.println("Ample: " + ample+ " is greater than mrx: " +mrx);
}
else {
System.out.println("mrx: " +mrx+ " is greater than ample: " +ample);
}
}
}
else if statements can be utilized to generate a new condition can be specified if the first condition isn’t true.
Here we use the else if condition to check if the numbers used in the examples above are equal:
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx = input.nextInt();System.out.println("Enter Number 2 here: ");
int ample = input.nextInt();if (ample>mrx) {
System.out.println("Ample: " + ample+ " is greater than mrx: " +mrx);
}
else if(ample==mrx){
System.out.println("Both Numbers "+ample+" and "+mrx+" are equal to each other");
}
else{ System.out.println("Number 1: " +mrx+ " is greater than Number 2: " +ample);
}
}
}
The following programme shows the mechanism of working of an Atm machine using the java conditions and while loop:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);final String password="1225";System.out.println("Enter Password to match: ");
String enter_code=input.next();if(enter_code.length()==4){
while(enter_code.equals(password)==false) {
System.out.println("Enter Password Again to match: ");
enter_code = input.next();
if(enter_code.equals(password)){
System.out.println("Exact Password Match !!");
break;
}
}
}
else if(enter_code.equals(password)){
System.out.println("Exact Password Match !!");
}
else{
System.out.println("Wrong Input of Digits !!");
}
}
}
Interface Keyword In Java
When talking about the Java Keyword Interface, the interface keyword is used to define a special type of abstract class that only comprises abstract methods.
When using an interface, its methods must be implemented by a class through the ‘implements‘ keyword, instead of ‘extends‘.
This class is responsible for providing the body of the given method.
The following example shows the working of interface keyword:
interface First_Interface{
void method();
}
class First_Interface_Subclass implements First_Interface{
public void method(){
System.out.println("This method is declared in the First_Interface interface");
}
}
public class Main {
public static void main(String[] args) {First_Interface_Subclass mrx_obj=new First_Interface_Subclass();
mrx_obj.method();
}
}
Similarly, following the example below we create another interface named My_Second_Interface:
interface My_Second_Interface{
void addition();
}
class My_Second_Interface_Subclass implements My_Second_Interface{
public void addition(){
System.out.println("Result : "+(91+412));
}
}
public class Main {
public static void main(String[] args) {My_Second_Interface_Subclass mrx=new My_Second_Interface_Subclass();
mrx.addition();
}
}
Similarly, we can also create multiple interfaces in java:
interface My_First_Interface{
void method1();
}
interface My_Second_Interface {void method2();
}class Interfaces implements My_First_Interface,My_Second_Interface{
public void method1(){
System.out.println("This method is taken from the Interface 1");
}
public void method2() {
System.out.println("This method is taken from the Interface 2");
}
}
public class Main {
public static void main(String[] args) {
Interfaces mrx=new Interfaces();
mrx.method1();
mrx.method2();
}
}
Interfaces Key Points:
- It cannot be used to create objects (in the example above, it is not possible to create an “Mr_Examples” object in the Facts_and_Figures class).
- An interface method does not contain a body – its body is defined in the “implement” class.
- You must override all methods of an interface during implementation.
- In general, interface methods are abstract and public by default.
- By default, the attributes of an interface are public, static, and final.
- When it comes to Java keyword implements, there is no constructor in an interface (since an interface cannot create objects).
Interfaces Uses – Why And When?
In order to ensure security, certain details should be hidden or only shown when they are relevant to the operation of the object (interface).
It is not possible to inherit from more than one superclass in Java (each child class can have only one parent class).
Yet, with interfaces, this is possible, as a class can implement multiple interfaces when using the Java Keyword Implements.
Please note: When implementing multiple interfaces, place a comma between them (see example above).
Multiple Interfaces:
// interface
interface Mr_Examples_1{public void method1();}interface Mr_Examples_2{public void method2();}class Mr_Examples_Main implements Mr_Examples_1,Mr_Examples_2{
public void method1(){
System.out.println("This is body of the method 1 from Interface named Mr_Examples_1");
}public void method2(){
System.out.println("This is body of the method 2 from Interface named Mr_Examples_2");
}}class Mr_Examples{
public static void main(String[] args) {Mr_Examples_Main obj=new Mr_Examples_Main();
obj.method1();
obj.method2();
}
}
Another example shows the working phenomenon of multiple interfaces:
// interface
interface Addition{public void addition(int mrx,int ample);}interface Subtraction{public void subtraction(int mrx,int ample);}interface Multiplication{public void multiplication(int mrx,int ample);}interface Division{public void division(int mrx,int ample);}class Mathematical_Operations implements Addition,Subtraction,Multiplication,Division{public void addition(int mrx,int ample){
System.out.println(mrx+" + "+ample+" = "+(mrx+ample));
}
public void subtraction(int mrx,int ample){
System.out.println(mrx+" – "+ample+" = "+(mrx-ample));
}
public void multiplication(int mrx,int ample){
System.out.println(mrx+" x "+ample+" = "+(mrx*ample));
}
public void division(int mrx,int ample){
float result=(float)mrx/ample;
System.out.println(mrx+" / "+ample+" = "+result);
}
}class Mr_Examples{
public static void main(String[] args) {Mathematical_Operations mrx_obj=new Mathematical_Operations();
mrx_obj.addition(2,5);
mrx_obj.subtraction(8,3);
mrx_obj.multiplication(7,2);
mrx_obj.division(6,4);
}
}
Import Keyword In Java
Packages, classes, and interfaces can be imported using the import keyword.
The Java API provides a ArrayList class, which can be imported as follows:
import java.util.ArrayList;public class Main {
public static void main(String[] args) {ArrayList in_Demand_Programming_Languages=new ArrayList();
in_Demand_Programming_Languages.add("Java Script");
in_Demand_Programming_Languages.add("Python");
in_Demand_Programming_Languages.add("Css");
in_Demand_Programming_Languages.add("Java");
in_Demand_Programming_Languages.add("Html");for(String mrx:in_Demand_Programming_Languages){
System.out.println(mrx);
}
}
}
Similarly, we can also utilize the Scanner class from java.util package as shown below:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner mrx=new Scanner(System.in);System.out.println("Enter First word here:");
String word1=mrx.next();System.out.println("Enter Second word here:");
String word2=mrx.next();if(word1.equals(word2)){
System.out.println("Exact Match");
}
else{
System.out.println("Not Matched");
}
}
}
Instanceof Keyword In Java
While discussing Java Keyword Instanceof, instance of allows you to check if an object belongs to a certain class or interface.
When using the “instanceof” keyword, a boolean value of either true or false is given in exchange for comparing the instance with its particular type.
The example below shows its working:
public class Main {
public static void main(String[] args) {Main mrx_obj=new Main();
boolean result=mrx_obj instanceof Main;
System.out.println("Result= "+result);
}
}
Correspondingly, it shows the results as true when multiple objects are an instance of the Main class as shown below:
public class Main {
public static void main(String[] args) {Main mrx_obj=new Main();
Main mrx_obj1=new Main();boolean result1=mrx_obj instanceof Main;
boolean result2=mrx_obj1 instanceof Main;System.out.println("Result 1= "+result1);System.out.println("Result 2= "+result1);
}
}
Int Keyword In Java
The int data type can hold integers ranging from -2147483648 to 2147483647.
public class Main {
public static void main(String[] args) {int mrx_Int_Limit= 2147483647;System.out.println("The maximum positive limit of the integer data type is:"+mrx_Int_Limit);}
}
Similarly, we can take two int inputs from the user and can find the modulus operator of them. For more clarification follow the example below:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Number 1 here: ");
int mrx=input.nextInt();System.out.println("Enter Number 2 here: ");
int ample=input.nextInt();int result=mrx%ample;System.out.println(mrx+" % "+ample+" = "+result);}
}
Long Keyword In Java
The long data type is capable of storing whole numbers between -9223372036854775808 and 9223372036854775808.
Remember to end the value with an uppercase or lowercase “L”.
public class Main {
public static void main(String[] args) {
long mrx_Long=-9223372036854775808l;System.out.println("The last Negative value an Long data type can hold is: "+mrx_Long);
}
}
public class Main {
public static void main(String[] args) {
Long mrx=1234322312333123123l;
Long ample=2354242423423423431l;System.out.println("The product of two long data type variables is: "+(mrx*ample));
}
}
New Keyword In Java
Creating new objects is accomplished using the new keyword.
The following example shows the creation of an object using the new keyword:
public class Main {String topic="New keyword";
public static void main(String[] args) {Main mrx=new Main();System.out.println("Today the topic of our discussion is: "+mrx.topic);
}
}
public class Main {String mrx="Mr";
String ample="Examples";
public static void main(String[] args) {Main mrx_obj=new Main();
System.out.println("Greetings ! You are learning Java Programming Language from : "+mrx_obj.mrx+". "+mrx_obj.ample);
}
}
Package Keyword In Java
Packages are created using the package keyword.
Firstly, we create a package named “myfirstpackage” using the keyword package:
package myfirstpackage;
public class Main {
public static void main(String[] args) {System.out.println("We have successfully created our first package");
}
}
Similarly, we can create another package using the package keyword:
package mysecondpackage;public class Main {
public static void main(String[] args) {System.out.println("We have successfully created our Second package");
}
}
Private Keyword In Java
An attribute, method, or constructor declared as private can only be accessed within the declared class using the private keyword.
The following example shows the use of private keyword inside a class:
public class Main {
private String user_Name ="Mr.Example";
private String user_Email ="https://mrexamples.com";
private int user_Age = 26;public static void main(String[] args) {
Main myObj = new Main();System.out.println("( User Information )");
System.out.println("\nUser Name: "+myObj.user_Name);
System.out.println("\nUser Email: "+myObj.user_Email);
System.out.println("\nUser Age: "+myObj.user_Age);
}
}
Here, we create the private method and access it within the class using the object:
public class Main {private void mrx_method(){
System.out.println("This is a private method of the Main class");
}
public static void main(String[] args) {Main obj=new Main();obj.mrx_method();}
}
Protected Keyword In Java
Access modifiers such as protected make attributes, methods, and constructors accessible within packages or subclasses.
When it comes to Java Keyword Protected, here the User_Details subclass is capable of accessing a User class’s protected attributes such as:
class User{protected String user_Name ="Mr. Example";
protected String site_Name ="https://mrexamples.com";
protected int user_Age = 26;
}class User_Details extends User{public static void main(String[] args) {
User_Details ample_object=new User_Details();System.out.println("( User Information )");System.out.println("\nUser Name: "+ample_object.user_Name);
System.out.println("\nWebsite Address: "+ample_object.site_Name);
System.out.println("\nUser Age: "+ample_object.user_Age);
}
}
class User{protected void method(){
System.out.println("We are learning about Ref Keyword Protected in Java.");
}
}class User_Details extends User{public static void main(String[] args) {
User_Details ample_object=new User_Details();ample_object.method();
}
}
Public Keyword In Java
When it comes to Keyword Public, the public keyword specifies an access modifier for classes, attributes, methods, and constructors, that makes them reachable by any other class.
Here we access multiple public attributes from one class to the other without extending the class:
class User{public String user_Name ="Mr. Example";
public String site_Name ="https://mrexamples.com";
public int user_Age = 26;}class User_Details {public static void main(String[] args) {User mrx_obj=new User();System.out.println("( User Information )");System.out.println("\nUser Name: "+mrx_obj.user_Name);
System.out.println("\nWebsite Address: "+mrx_obj.site_Name);
System.out.println("\nUser Age: "+mrx_obj.user_Age);
}
}
Similar way can be utilized in order to access a method:
class User{public void method(){
System.out.println("The topic of Discussion is Ref Keyword Public.");
}
}class User_Details {public static void main(String[] args) {User mrx_obj=new User();mrx_obj.method();
}
}
Return Keyword In Java
Return represents the end of the execution of a method, and can be used to return a value from a method after the execution has been completed.
The following method returns the product of 2 numbers:
public class Main {int product(int mrx,int ample){
return mrx*ample;
}
public static void main(String[] args) {Main obj=new Main();int result=obj.product(5,7);
System.out.println("The Result is given as follow: "+result);}
}
The given programme take user input as an integer and calculates the factorial of it:
Such as: Factorial of 5 is: 5 * 4 * 3 * 2 * 1
import java.util.Scanner;public class Main {
public static int calculate_Factorial(int n) {
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}public static void main(String[] args) {Scanner input=new Scanner(System.in);
System.out.println("Enter Number here: ");
int number=input.nextInt();int result = calculate_Factorial(number);
System.out.println("The factorial of " + number + " is: " + result);
}
}
Note: When void is used, the method does not have a return value.
The given example shows void methods that means that they do not have a return type:
public class Main {
static void my_Void_Method() {
System.out.println("Greetings ! We are learning about void methods (No return type)");
}public static void main(String[] args) {
my_Void_Method();
}
}
Here is another example of using void method in order to divide variable mrx value by ample value:
import java.util.Scanner;public class Main {
static void divide_Values(int mrx, int ample) {float result=(float) mrx/ample;
System.out.println(mrx+" / "+ample+" = "+result);}public static void main(String[] args) {
Main obj=new Main();
Scanner input=new Scanner(System.in);System.out.println("Enter value of mrx here: ");
int mrx=input.nextInt();System.out.println("Enter value of ample here: ");
int ample=input.nextInt();divide_Values(mrx,ample);
}
}
Short Keyword In Java
In Java, the short keyword is the type of data type that can store whole numbers ranging from -32768 to 32767.
We can use a short variable if we want to store integers between -32768 to 32767:
public class Main {
public static void main(String[] args) {
short lower_Range=-32768;
short upper_Range=32767;System.out.println("The short data type has an uppermost value as : "+upper_Range+" where are it can store "+lower_Range+" as the lowest storing element");
}
}
Correspondingly, we can also find the sum of two short datatypes variables:
public class Main {
public static void main(String[] args) {
short mrx=2324;
short ample=1514;System.out.println("Sum of mrx and ample is: "+(mrx+ample));
}
}
Static Keyword In Java
Static methods and attributes have a non-access modifier called static.
When using Java keyword static, static methods/attributes can be accessed without creating an object of the class.
In the example below we used the static attributes and accessed them without using the object:
public class Main {
static String user_Name ="Mr. Example";
static String site_Name ="https://mrexamples.com";
static int user_Age = 26;public static void main(String[] args) {System.out.println("( User Information )");System.out.println("\nUser Name: "+user_Name);
System.out.println("\nWebsite Address: "+site_Name);
System.out.println("\nUser Age: "+user_Age);}
}
Likewise, we can access the methods having static modifier without instantiating it with any object:
public class Main {
static void method_static(){
System.out.println("This is a static method which can be accessed without an object");
}
public void method_public(){
System.out.println("This is a public method which requires an object to call itself");
}public static void main(String[] args) {// Here we called the static method without an instance with an object
method_static();Main obj=new Main(); // Object of Main class is created hereobj.method_public(); // the public method is accessible now}
}
Super Keyword In Java
In the case of Java Keyword Super, super refers to superclass objects (parent class / base class).
In addition to accessing the superclass constructor, it is also intended to call superclass methods.
It is commonly used to avoid confusion between subclasses and superclasses that have the same method names.
A basic understanding of inheritance and polymorphism is required to understand the super keyword.
The following programme shows the use of super keyword() to access the methods of the parent class in child class method named information() :
class Marts{ // Superclass (parent)
public void information() {
System.out.println("There are approximately 67,167 marts in United States");
}
}class Walmart extends Marts { // Subclass (child)
public void information() {
super.information(); // Call the superclass method
System.out.println("Among all the marts, Walmart is the largest supermarket chain in america having more than 10,500 stores and an expected revenue of $ 385.73 Billions");
}
}public class Main {
public static void main(String args[]) {
Marts marts = new Walmart(); // Create an object of Walmart class
marts.information();
}
}
We can also use a super() keyword to access a parent class constructor inside a child class constructor:
class Parent{ // Superclass (parent)
Parent(){
System.out.println("This is a Base / Parent class constructor used in child class constructor");
}
}class Child extends Parent { // Subclass (child)Child(){
super();
System.out.println("This is a child class constructor");
}
}public class Main {
public static void main(String args[]) {
Parent obj = new Child(); // Create an object of parent class
}
}
Switch Keyword In Java
When it comes to Java Keyword Switch, the switch keyword decides which one out of several code blocks to execute.
In the example below, it works as follows:
- Switch expressions are evaluated once.
- Each case’s value is compared with the expression’s value.
- When a match is found, the associated code block is executed.
- As soon as a match is found, the break keyword is used to terminate the switch block
We can learn how to use the switch statement by following the example below:
import java.util.Scanner;public class Main {public static void main(String[] args) {System.out.println("\n \t\t( Menu )");
System.out.println("1) Hot Chocolate 8$ ");
System.out.println("2) Cappuccino 6$");
System.out.println("3) Tea 4$");
System.out.println("4) Frappuccino 9$");
System.out.println("5) Latte 5$");Scanner input=new Scanner(System.in);System.out.println("\nEnter the Correct Item Number from the menu list to place an order: ");
int choice=input.nextInt();switch (choice){case 1:
System.out.println("\nHot Chocolate Selected");
System.out.println("Total Bill= 8$");
System.out.println("The order will take 20 minutes. Thank you for the patience !!");
break;
case 2:
System.out.println("\nCappuccino Selected");
System.out.println("Total Bill= 6$");
System.out.println("The order will take 20 minutes. Thank you for the patience !!");
break;
case 3:
System.out.println("\nTea Selected");
System.out.println("Total Bill= 4$");
System.out.println("The order will take 20 minutes. Thank you for the patience !!");
break;case 4:
System.out.println("\nFrappuccino Selected");
System.out.println("Total Bill= 9$");
System.out.println("The order will take 20 minutes. Thank you for your patience !!");
break;
case 5:
System.out.println("\nLatte Selected");
System.out.println("Total Bill= 5$");
System.out.println("The order will take 20 minutes. Thank you for your patience !!");
break;
default:
System.out.println("Wrong input !! Try again");
}
}
}
Here we can created a calculator in Java using switch case:
import java.util.Scanner;public class Main {public static void main(String[] args) {System.out.println("\n \t\t( ———————- C A L C U L A T O R ————————– )");System.out.println("\n\n1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Modulus");Scanner input=new Scanner(System.in);System.out.println("\n\nEnter Number 1: ");
int mrx=input.nextInt();System.out.println("\nEnter Number 2: ");
int ample=input.nextInt();System.out.println("\nEnter Choice Number as per list given above: ");
int choice=input.nextInt();switch (choice){case 1:
System.out.println("\n\nOutput: ");
System.out.println("\n"+mrx+" + "+ample+" = "+(mrx+ample));
System.out.println("Addition Operation Successfully executed !! Thank you for using the calculator!!");
break;
case 2:
System.out.println("\n\nOutput: ");
System.out.println("\n"+mrx+" – "+ample+" = "+(mrx-ample));
System.out.println("Subtraction Operation Successfully executed !! Thank you for using the calculator!!");
break;
case 3:
System.out.println("\n\nOutput: ");
System.out.println("\n"+mrx+" x "+ample+" = "+(mrx*ample));
System.out.println("Multiplication Operation Successfully executed !! Thank you for using the calculator!!");
break;case 4:
System.out.println("\n\nOutput: ");
float result=(float)mrx/ample;
System.out.println("\n"+mrx+" / "+ample+" = "+result);
System.out.println("Division Operation Successfully executed !! Thank you for using the calculator!!");
break;
case 5:
System.out.println("\n\nOutput: ");
System.out.println("\n"+mrx+" % "+ample+" = "+(mrx%ample));
System.out.println("Modulus Operation Successfully executed !! Thank you for using the calculator!!");
break;
default:
System.out.println("Wrong input !! Try again");
}
}
}
This Keyword In Java
When it comes to Java Keyword This, this refers to the object in a method or constructor.
This keyword is most commonly used to distinguish class attributes from parameters with the same name (due to the shadowing effect of a method or constructor parameter on a class attribute).
In the example below, without this keyword, the output would be “0” instead of “Java This keyword “.
In addition to this, it can also be used for:
- Call the constructor of the current class.
- Method of the current class is invoked.
- Get the object of the current class.
- When calling a method, pass an argument.
- Call the constructor with an argument.
Accessing a class attribute mrx with this keyword:
public class Main {
String mrx;// Here we create a constructor with an argument
public Main(String mrx) {
this.mrx = mrx;
}// Here we call the constructor of the main class:
public static void main(String[] args) {
Main myObj = new Main("Java This Keyword");
System.out.println("Topic = " + myObj.mrx);
}
}
public class Main {
float ample;// Here we create a constructor with an argument
public Main(float ample) {
this.ample = ample;
}// Here we call the constructor of the main class:
public static void main(String[] args) {
Main myObj = new Main(5.32f);
System.out.println("Float Value = " + myObj.ample);
}
}
Throw Keyword In Java
When it comes to Ref Keyword Throw, the throw keyword generates a personalized error.
An exception type is used with the throw statement. ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and so on are all exception types available in Java.
Like in the example below, exception types are often associated with custom methods.
Throw versus Throws
Throw:
- Method exceptions are thrown using this method.
- Exceptions can only be thrown once.
Throws:
- Indicates the type of exception that can be thrown by a method.
- It is possible to list multiple exceptions in Java Keyword Throw.
The following programme matches the number of digits as the ATM pin number entered by the user, and shows exception if the entered digits length is greater or less than 4:
import java.util.Scanner;public class Main {
static void atm_pin_Security() {
Scanner input=new Scanner(System.in);System.out.println("Enter Your Atm Pin here: ");
String atm_pin=input.next();if (atm_pin.length() != 4) {
throw new ArithmeticException("Access denied – The ATM pin should contain exactly 4 digits");
}
else {
System.out.println("Pin Limit Successfully Achieved ");
}
}public static void main(String[] args) {atm_pin_Security();
}
}
And the following example shows the programme that takes two user inputs, compares them and shows an exception if they are not equal:
import java.util.Scanner;public class Main {
static void match_2_Numbers() {
Scanner input=new Scanner(System.in);System.out.println("Enter Your First Number here: ");
int mrx=input.nextInt();System.out.println("Enter Your Second Number here: ");
int ample=input.nextInt();if (mrx!=ample) {
throw new ArithmeticException(mrx+" and "+ample+" are two different numbers !!");}
else {
System.out.println(mrx+" and "+ample+" are the same numbers !!");
}
}public static void main(String[] args) {match_2_Numbers();
}
}
Throws Keyword In Java
The throws keyword specifies what exception types can be thrown by a method.
The exceptions thrown during this process are the same as what we discussed in the throw keyword.
From the example given above, we can clearly understand the working of the keyword throws:
import java.util.Scanner;public class Main {
static void match_2_Numbers() throws ArithmeticException {
Scanner input=new Scanner(System.in);System.out.println("Enter Your First Number here: ");
int mrx=input.nextInt();System.out.println("Enter Your Second Number here: ");
int ample=input.nextInt();if (mrx!=ample) {
throw new ArithmeticException(mrx+" and "+ample+" are two different numbers !!");}
else {
System.out.println(mrx+" and "+ample+" are the same numbers !!");
}
}public static void main(String[] args) {match_2_Numbers();
}
}
Similarly, consider an array that contains 5 famous clothing brands of the United States. If we print more than the given number of brands it will generate an exception “ArrayIndexOutOfBoundsException” as shown below:
public class Main {
static void united_States_Clothing_Brands() throws ArrayIndexOutOfBoundsException {String clothing_Brands[]={"Patagonia","BODE","Carhartt","Alpha Industries","Rick Owens"};for(int mrx=0;mrx <=7;mrx++){if (mrx > clothing_Brands.length) {
throw new ArrayIndexOutOfBoundsException("The array does not contain elements more than 5");
}
else {
System.out.println(clothing_Brands[mrx]);
}
}
System.out.println("All the elements are printed upto the limit of the Array ");
}public static void main(String[] args) {united_States_Clothing_Brands();
}
}
Try Keyword In Java
With reference to the Java keyword try, try-catch statement is produced.
You can use the try statement to test a block of code for errors while it is being executed.
Catch statements allow you to define a block of code that will be processed if the try block fails.
Try-catch is used to catch errors and then execute a piece of code to deal with them. Go through the examples below to understand its working more clearly:
public class Main {
public static void main(String[] args) {try {
int[] prime_Numbers = {2,3,5,7,11,13,17};
System.out.println(prime_Numbers[11]);
} catch (Exception e) {
System.out.println("Array of Prime Numbers Do not have any element at such index ");
}
}
}
The given example shows the exception if user enters data of other data types than int:
import java.util.Scanner;public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
try {
System.out.println("Enter Number here: ");
int mrx_num=input.nextInt();
System.out.println("Integer Entered: "+mrx_num);} catch (Exception e) {
System.out.println("User Entered data is of another data type than int !!");
}
}
}
Void Keyword In Java
When we talk about Java Keyword Void, it specifies that a method with the void keyword should not return anything.
Similarly, the method in the example below does not return anything:
public class Main {static void topic_under_Discussion(){
System.out.println("The topic under Discussion is Java Keyword Void");
}
public static void main(String[] args) {topic_under_Discussion();
}
}
Corresponding, the following shows the working of a void method that takes user height in feet and converts it to feets:
import java.util.Scanner;public class Main {static void feet_To_Centimeter_height_convertor(){Scanner input=new Scanner(System.in);System.out.println("Enter Height in Feet here: ");
float mrx=input.nextFloat();System.out.println("————- Feet To Centimeter Height Converter ——————-");
System.out.println("\nHeight in Feet: "+mrx);float height_centimeters=mrx*30.48f;System.out.println("\nHeight in Centimeters: "+height_centimeters+" cm");
}
public static void main(String[] args) {feet_To_Centimeter_height_convertor();
}
}
Hint: It is possible to make a method return a value by using a primitive data type (such as an int, char, etc.) rather than void. To do this, use the return keyword as follows. The following programme shows the method of evaluating a string, to see if it ends with “a”.
import java.util.Scanner;public class Main {public static int Strings_Compare_Method() {Scanner input = new Scanner(System.in);System.out.println("Enter String 1 here: ");
String mrx = input.next();boolean result=mrx.endsWith("s");
if(result==true){
return 0;
}
else{
return 1;
}}public static void main(String[] args) {Main obj=new Main();int ample_result2=Strings_Compare_Method();if(ample_result2 == 0){
System.out.println("\nThe user given String ends with s");
}
else{
System.out.println("\nUser given String Do not Ends with s");
}}
}
The following programme returns 0 if the character is a vowel and 1 if it is a consonant and shows the results accordingly:
import java.util.Scanner;public class Main {public static char vowel_checker() {Scanner input = new Scanner(System.in);System.out.println("Enter an Alphabet here: ");
char ample=input.next().charAt(0);if(ample=='a'||ample=='e'||ample=='i'||ample=='o'||ample=='u'){
return 0;
}
else{
return 1;
}
}public static void main(String[] args) {int ample_result=vowel_checker();if(ample_result==0){
System.out.println("Character is a Vowel ");
}
else{
System.out.println("Character is a Consonant");
}}
}
While Keyword In Java
When it comes to Java Keyword While, the while loop will loop through a block of code as long as a certain condition holds true.
Make sure to increase the variable assigned in the condition, otherwise the loop will never terminate.
The given examples shows all the even numbers starting from 0 to the user’s limit:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Range here: ");
int mrx=input.nextInt();int ample=0;
System.out.println("\nEven Numbers upto the limit "+mrx+" are: \n");
while(ample <= mrx){
if(ample % 2==0){
System.out.println(ample);
}
ample++;
}}
}
Correspondingly, the squares of numbers till the user’s limit can be calculated in the given way:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Limit here: ");
int mrx=input.nextInt();System.out.println("\nThe squares of numbers till the limit "+mrx+" are : \n");int ample=1;
int result;
while(ample <= mrx){
{
result=ample*ample;
}
System.out.println("The square of "+ample+" is: "+result);
ample++;
}}
}
There is a variation of the while loop which can be referred to as the do/while loop. During the execution of this loop, the code block will be executed once, before it checks if the condition is true, and then it will repeat the loop as long as the condition is true:
The given example shows the sum of numbers up to the user’s limit by using the do/while loop:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Limit here: ");
int mrx = input.nextInt();System.out.println("\nThe squares of numbers till the limit " + mrx + " are : \n");int ample = 0;
int sum = 0;
do {
sum = sum + ample;
System.out.println("The Sum of Numbers upto "+ample+" the limit is: " + sum);
ample++;
}while (ample <= mrx);
}
}
Similarly, a while loop can be used to print the natural numbers up to the user limit:
import java.util.Scanner;public class Main {
public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter Limit here: ");
int mrx = input.nextInt();System.out.println("\nThe squares of numbers till the limit " + mrx + " are : \n");int ample = 1;do {System.out.println(ample);
ample++;
}while (ample <= mrx);
}
}