Enumeration in Java
By Enumeration, we mean a set of named constants that has its data type. If you can sort out the type of the variable while curating a program, you find it simple while defining them. Hence, Enum applies when you know all the values at the compile time. And we are going to discuss the Enumeration in Java through a list of examples. The topics covered in this article are like what is Enumeration in Java, what its definition is, how we can create enumeration using switch case, what are Values () and ValueOf() method, what are the Enumeration and constructor, instance variable, and method. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training.
What is Enumeration in Java?
Enumeration happens to be a named constant. When we talk of it in Java, it is a class type and comes with Constructors. We create it through the Enum keyword. And by default, each of the enumeration constant happens to be static, public, and final. The enumeration is a class type and comes with the constructors, you don’t need to instantiate the Enum through the Enum variable. And we define the Enum variable in the same manner like we define the primitive variable.
Now let’s have the details of the Enumeration, and know the syntax and the declaration of Enum.
Defining Enumeration in Java
We can declare the Enum outside the class or within the class as well. However, we cannot do its declaration within the method. Below is an example of the declaration. Let’s however, first understand how we can declare an Enum outside the class.
How to declare an enumeration in Java from outside the class.
enum DaysOfWeek{ // we use the enum keyword rather than class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
public class Enum_Declare {
public static void main(String[] args) {
DaysOfWeek a = DaysOfWeek.Monday; // we do not need new keyword for the object reference
System.out.println(a);
}
}
Output:
Monday
Declaring the Enumeration in Java from within the class:
public class Enum_Declare {
enum DaysOfWeek{ // we use the Enum keyword rather than the class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
public static void main(String[] args) {
DaysOfWeek a = DaysOfWeek.Monday; // we do not need new keyword for the object reference
System.out.println(a);
}
}
Output:
Monday
The first line within the Enum type must be the list of constants. And then we make use of the methods, constructor, and variable. And basically, the Enum is the representation of the group of constants and variables.
Please note:
Through Enum, the type safety is improved.
It can be used diversely through the switch case example
We can easily traverse the Enum
The Enum comes with fields, methods, and constructors.
It in general implements the interface, though you cannot extend any of the class as it extends the Enum class internally.
And now you know how the Enum is declared in a program. Let’s now find out how we can implement it through the switch case statements.
Enumeration using switch case
The Enumeration value can be used for controlling the switch statement. And it’s required that each of the case statements should apply the constants from one Enum as being used by the switch statement. And the below example demonstrates the same.
package NareshIT;
import java.util.*;
enum DaysOfWeek{ // we use the enum keyword rather than class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
public class SwitchTest{
public static void main(String[] args) {
Switch a= DaysOfWeek.Sunday;
switch(a) { //The enumeration constants names are being used without their enumeration
case Sunday: //you can only make use of the constant defined under the Enum
System.out.println("Sunday is the Day");
break;
case Monday:
System.out.println("Monday is the day");
break;
case Tuesday:
System.out.println("Tuesday is the day");
break;
case Friday:
System.out.println("Friday is the day");
break;
}
Output:
Sunday is the Day
Hope you now have got the switch statement, and how it is used in the case of the Enum. And lets now move ahead and find out what Values() and ValueOf() method are meant for, and what is the difference between them.
Values( ) and ValueOf( ) method
Values(): When we make an Enum, the Java compiler adds to it the values() method internally. And this method returns an array that contains all the enum values.
Syntax:
public static enum-type[ ] values()
Now let’s return the enumeration constant that has the value equal to the string that is passed as an argument as we call the method.
Syntax:
public static enum-type valueOf (String str)
Let's now have the program for understanding the methods more elaborately
enum DaysWeek{ // we use the enum keyword rather than class keyword
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
class DaysOfWeek {
public static void main(String args[]) {
DaysWeek a;
System.out.println("All constants of DaysWeek:");
DaysWeek A[] = DaysWeek.values(); //returns the array of constants of Enum type DaysWeek
for(DaysWeek b : A) //making use of foreach loop
System.out.println(b);
a = DaysWeek.valueOf("Sunday");
System.out.println("Its the best day:" + a);
}
}
Output:
All constants of DaysWeek:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
It’s the best day: Sunday
And this the way how we can make use of the Values() for returning the array which contains all the enum in the method and the Valueof() for returning the enumeration constant. Hope you now have the concept.
Now, let's move ahead and find out how the Enumeration is implemented in Java together with the constructor, method, and instance variable.
Enumeration with Constructor, instance variable, and Method
Generally, the Enumeration contains the constructor, and it gets executed separately for every Enum constant while the Enum class is loaded. And not merely that, an Enum can make concrete methods as well. Let’s now do the coding for understanding the implementation of the Enumeration through Constructor, instance variable, and the method.
enum inWords
{
One, Two, three, four;
public String getinWord()
{
switch(this) {
case One:
return "1";
case Two:
return "2";
case three:
return "3";
case four:
return "4";
default:
return null;
}
}
}
class Main
{
public static void main(String[] args)
{
// call getSize()
// using the object One
System.out.println("You have entered:"+inWords.One.getinWord());
}
}
Output:
You have entered: 1
The above program needs explanation.
Enum and Constructors: The Enum can have their constructors, and they execute separately for each of the Enum constants while the Enum class loads. And we cannot create explicitly the Enum object, and therefore we cannot directly invoke the Enum constructor.
Enum and methods:
We can have within the Enum both concrete methods as well as abstract methods as well. If certain Enum has an abstract method, then each of the instances of the Enum class should implement that. Remember the concrete method has a complete definition, and it can be overridden in an inherited class. If we declare it final, then it cannot be overridden. However, do not get confused with it here, as we will have a detailed blog on the methods and classes soon. You need to keep reading our blog. And for the best results, please join our java classes. You can join on-premises as well as online. So, feel free to contact us for your Java classes.
The above Java program explains that Enum can keep up with a constructor as well as concrete methods. And an Enum keyword is used rather than a class keyword. And each of the constants in Enum calls these constructors and methods separately. And that we can see in the above program.
Enum and Inheritance:
You need to know that Enums extends implicitly java. lang.Enum class. In java, a class extends only one parent. Hence, the same is the case with Enum.
And toString() method gets overridden in java.lang.Enum class that fetches the Enum constant name.
And Enum can have any number of interfaces.
An order does count in Enum. Through the use of the ordinal () method, we can find the index of each of the constant, just as we find the array index.
And that completes our article on the Enum. We have seen almost all the nitty-gritty of the Enum. Hope all the concepts discussed are now clear to you. Make use of the Enum whenever you have a set of constants, and you want to enumerate them and assign them index for later use inside other classes and methods.
Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:
You need to pay a nominal fee.
You can choose any Java certification, as per your skills and interest.
You have the option to select from online and classroom training.
A chance to study at one of the best Java training institutes in India
We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
Naresh I technologies cater to one of the best Java training in India.
And a lot more is waiting for you.
Contact us anytime for your complete Java online training.
Components of Java Architecture
Through Java Architecture we have the compilation and the interpretation both combined. And the architecture details all the processes executed while we formulate the Java Program. And before we proceed with the article, let's have a brief on what we are going to cover. We are going to cover what Java architecture is, what are the components of Java, why Java is platform-independent, and what is JIT in Java. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training.
So, what is the Java Architecture?
It’s the compilation and interpretation joined together. We write the code in Java, convert it into Byte code, and it is done by Java Compiler. The JVM converts the byte code to the machine code. The machine code is platform-independent, and its executed by the machine. However, the JDK must be installed on the machine. Post Java 10, the JRE is included within the JDK. And you will not find the JRE separately now. And the JVM is included in the JRE.
Hence, the javac compiles the source code, which we write in Java in the IDE or any editor. Now the javac generates the .class file. And this class file is the byte code. The bytecode is the set of instructions to the JVM. The JVM is the part of JRE, and it contains both the compiler and the interpreter. The interpreter interprets the byte code into machine code, and the CPU can then execute the machine code for the final output.
Remember,
The interpreter is the part of the JVM, and JVM is machine-independent. However, JRE is machine-dependent. Also, the JDK is machine-dependent. Now the JRE is included in JDK since post-Java 10. JVM is part of JRE. And JVM is machine-independent.
Hence, Java is platform-independent because of the JVM and not because of JRE or JDK. And that is why we say Java supports the WORA.
Also, remember:
The bytecode contains the .class file for each class separately.
The .exe files of C++/C can be executed directly, and hence are not secure. However, the .class files or the bytecode cannot be executed directly, and hence Java is secure.
The .exe files of C++/C are platform-dependent, and the .class files or the bytecode are platform-independent.
Also, the .exe files cannot be converted back to source code. However, the bytecode can be converted back to the source code.
Let’s have a look at the java architecture more deeply, and let’s look at the components of Java.
Various components of the Java Architecture
We have three components of the Java language: JRE, JVM, and JDK. And we already know their full form by now, and hence I am not including it here. However, we are going to discuss them deeply one by one below.
Java Virtual Machine
The Java applications support the WORA as we can run the Java code on any platform. And this is due to the JVM. It’s the component of Java that caters to us an environment for Java program execution. The JVM has an interpreter that interprets the bytecode into machine code. And this is executed in the machine where the Java program runs.
And in a nutshell, the JVM does the following functions: It loads the code, does the verification of the code, executes it, and provides the runtime environment.
Now, let's have a look at the JVM architecture now. The classes are loaded by the Classloader into the JVM memory, which has four parts, the method area, the stack, the heap, and the native stack. The execution engine is formed of the JIT compiler and the Garbage collector, there is a native interface that acts as the interface between the JVM memory, execution engine, and the native libraries.
Explanation:
ClassLoader: The Classloader happens to be the subsystem of the JVM. Java uses it to load the .class files. And when we run the Java program, the class files are loaded first.
Class Method area: This is the Data Area in the JVM, and the class data is stored there. The static variables, static methods, static blocks, and instance methods are being stored here.
Heap: This is made when the JVM starts. And it can decrease as well as increase in size while the application runs.
Stack: The JVM stack is the thread stack. This is the data area in the JVM memory made for a single execution thread. This is used by the thread for storing various elements like partial results, local variables, and the data for invoking the method and returns.
Native stack: This subsumes all of the native methods in the application.
Execution Engine:
JIT compiler
Garbage collector
JIT compiler: The JIT is a section of the runtime environment. And it betters the performance of the Java applications as it compiles the bytecode into machine code at run time. By default, it is enabled. And when we compile a method, the JVM directly fetches the compiled code of the method. The JIT compiler compiles the bytecode into machine code and compiles it JIT for running.
Garbage collector: It is used for collecting unused content. It’s a part of JVM. And it keeps a record of each object in the JVM, and it removes all that is unwanted. It follows two steps for working, which are Mark and Sweep.
Mark: This is where the garbage collector finds which memory is in use and which is not in use.
Sweep: This removes the object which is found during the Mark stage.
Java Runtime Environment:
The JRE software develops the runtime environment, where the Java programs can be executed. It is the on-disk system that picks the Java code, combines it with all the libraries required, and then finally JVM executes it. The JVM has all the libraries as well as the software required for running the Java program. It is a part of the JDK; however, it can be downloaded separately also.
JDK or the Java Development Kit:
This is the software development environment that is made use of for developing the applets and the Java Applications. It has the JRE and various development tools, like loader/interpreter, archiver like a jar, javac (compiler), a document generator like Javadoc, as well as various other tools.
So the JDK means JRE + development tools. And the JRE means JVM + library files.
java: This is the launcher of the java application.
javac: this compiles the Java source code.
javadoc: This generates the API documentation.
jar: This creates as well as manages the JAR files.
And we can now have a look because Java is platform-independent.
So how the Java is Platform Independent?
A programming language that runs on all the operating systems when we talk of the development and compilation.
And Java is platform-independent due to the bytecode, and we have already discussed this. However, let's repeat what it is. It is the code instruction to the JVM which is machine-independent.
Below, we are briefing the complete step again in detail. The source code is compiled, and the javac generates the Bytecode, and the JIT compiler in JVM converts the bytecode into native machine code at run time.
Hence java source code or .java ? javac (.class), JVM (sample.obj) ? final output.
Hence, the source code is converted into a .class file by the java compiler. And the .class file is converted to the byte code by the javac. The JVM converts it to the object file. And that is seen as the final output, which you see over the screen
Now, let's understand the JIT in java.
JIT in Java
This deals with the performance optimization of the Java-based applications at run time. And the performance depends upon the compiler. And we have already seen the whole process, and how JIT does the magic.
The JIT compiler does the compilation of the byte code and converts it into machine code, and it compiles Just in Time for running. When JVM compiles the method, it calls directly the compiled code of the method.
Let’s have a broader look.
The bytecode requires interpretation or compilation to a well-defined machine instruction which depends upon the instruction set passed. And execution can be direct if the instruction architecture is based on bytecode. The bytecode interpretation takes time, and hence the execution speed gets affected.
For better performance, the JIT compiler does the communication with the JVM at run time and it compiles the appropriate bytecode categorization into a native machine code. And through the JIT compiler, the hardware executes the native code, and not like JVM interpreting the same bytecode sequence again and again. That can incur overhead on the translation procedure.
And that brings us to the end of this article. Hope you now have the complete detail of the Java architecture. And we will be coming up with more on Java. Hence, do keep reading our blog.
Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:
You need to pay a nominal fee.
You can choose any Java certification, as per your skills and interest.
You have the option to select from online and classroom training.
A chance to study at one of the best Java training institutes in India
We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
Naresh I technologies cater to one of the best Java training in India.
And a lot more is waiting for you.
Contact us anytime for your complete Java online training.
Coupling in Java and its different types
Java happens to be an Object-oriented programming language. Coupling is quite essential in Java while you deal with Java Classes and Objects. It generally refers to what level one class is dependent on the other class. In this article, you will learn all about coupling. Coupling is essential for all programming languages, and here you will find various examples in detail explaining what is coupling. The topics covered in this article are what is coupling in Java, various types of coupling, tight and loose coupling and the difference between these two types of coupling. You should know that coupling is the extent to which a class knows about some other class. And, It's a very important feature of any programming language. So let's begin this article. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training.
Coupling in Java
Coupling is a scenario where an object can be used by another object. It ensures collaboration and doing the task for each other. And in a nutshell. It is the calculation that explains to what level an object needs another for completing its task. It’s the usage of an object by some other object, and thus a low coupling will mean a low level of dependency of one module over the other. We know hence couping as a collaboration of one class on the logic of another class. Hence, you can easily understand that for a better module-based programming experience the programming language needs to ensure low coupling. That means the modules are not dependent on one another and hence programmers can work on them separately without bothering about the other modules. And this is because the modules are independent of each other, as the programming language is ensuring low coupling.
Types of coupling
We have two types of coupling in Java, and they are as follows:
Tight coupling
Low coupling
Let's have a look at each of them separately.
Tight coupling
We see tight coupling in conditions where a group of classes is extensively dependent on each other. And this happens when there are so many responsibilities in the classes, or when one liability is on various classes, and not merely one class. And this scenario when one object creates another object for its purpose is known as Tight coupling. And the parent object knows a lot about the other child object, and that’s why there is high coupling between the two. The dependency level, and the fact that anybody cannot change the object, make them support tight coupling.
Now, let's have some examples related to tight coupling. Keep in mind that Java supports both tight coupling and loose coupling. However, for good architecture, a software design should support loose coupling. It's one of the prime features of a good software design.
Example: Just think of a situation when we have two classes. The first class is the class with parameters for the area, and the second class has the methods for calculating the area of the rectangle. However, it inherits the parameters from the first class. Hence, these classes are loosely coupled to some extent as the change in one class does affect the other class to a low level however. However, suppose the first-class make use of the method for calculating the area that is defined in the second class. See below, and then you will find that the two classes are more tightly coupled, as the first class has the dependency in the form of the second class. If we remove the second class then we cannot just execute the first classes, more in second case, and to lesser extent in first case. And hence, the two classes are tightly coupled in both cases. In first case, we will not get the output that we need without the second class. And in the second case, an exception will be thrown, like the method definition missing. It's not good for the software design, and hence we make use of the interfaces. We will see that later in some in this blog. Please just keep reading this article on coupling.
Class parameters
{
public int len=10;
public int breath=10;
public static void main(String[] args)
{
Area b=new Area();
int a = b.area(this.len, this.breath);
System.out.printlin(“ Area=”, +a);
}
Class Area{
public void area(int a, int b)
{
return(a*b);
}
}
Output:
Area = 100
Above we see that the two classes are being bound together, and they work like a one unit, and one part does not work without the other part. It’s one of the simplest examples in Java of tight coupling. Let's have one more example explaining tight coupling. And we repeat that tight coupling is not good for a proper software design.
Example 2:
package CalculateArea;
public class A {
public static void main(String args[]) {
Area x = new Area();
x.PrintA();
}
}
class Area {
LenBreath y;
public Area() {
y = new LenBreath();
}
public void PrintA() {
System.out.println("Area");
y.PrintArea();
}
}
class LenBreath {
public int a;
public int b;
public LenBreath() {
a=12;
b=12;
}
public void PrintArea() {
System.out.println(this.a * this.b);
}
}
Output
Area
144
Above we see even more tight coupling and this is not good for a good software design. Also, you can understand that different programmer in a software development team code different module. And If there is tight coupling, then they cannot work independently. Let's now see what is the loose coupling in detail. And we will find that it is better for a good software design than to
Loose coupling
When a certain object gets the object from any external source, then we term it as loose coupling. This implies that the objects are loosely coupled and are independent. If the objects are loosely coupled, then the maintenance becomes easier, and that means less effort is required. And you should know that it’s the heavy maintenance effort required, which Is the disadvantage of the tight coupling. And this has been removed through the implementation of loose coupling. Let's have a look at two code examples, explaining the loose coupling. And you will find that we make use of the interface. And if you want to learn these in detail, please join our Java training classes. It will cost you a nominal fee, and by the end, you will be a complete Java developer. Please be assured. Contact us now, or anytime.
Example 1:
package loose_coupling;
class Area {
public static void main(String args[]) {
Rectangle r = new Rectangle(15, 15);
System.out.println(r.getArea());
}
}
final class Rectangle {
private int area;
Rectangle(int length, int breath) {
this.area = length * breath;
}
public int getArea() {
return area;
}
}
Output:
225
Example 2:
package loose_coupling;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
PrintShape x = new Square();
PrintShape y = new Rectangle();
Master a = new Master(x);
a.PrintResult();
Master a2 = new Master(y);
a2.PrintResult();
}
}
interface PrintShape {
public void Printshape();
}
class Master {
PrintShape s;
public Master(PrintShape s) {
this.s = s;
}
public void PrintResult() {
System.out.println("Master");
s.Printshape();
}
}
class Square implements PrintShape {
public Square() {
}
public void Printshape() {
System.out.println("Square");
}
}
class Rectangle implements PrintShape {
public Rectangle() {
}
public void Printshape() {
System.out.println("Rectangle");
}
}
Output:
Master
Square
Master
Rectangle
Explanation:
Through the use of coupling, we have ensured above the loose coupling. We see above that the Square and Rectangle classes can exist without each other. Hence, they are independent of each other. If there is no Rectangle class then as well the Square class can exist. And this has been made possible through the use of an interface. Hence, an interface concept plays an important role in ensuring the Loose coupling. And this is not true only for Java. But in fact, this true for all object-oriented programming languages.
What a tight coupling and loose coupling differ in between each other
Differences between the tight coupling and the loose coupling are as below:
Tight coupling leads to more interdependency, and loose coupling leads to low dependency and it supports more test-ability.
The loose coupling follows the GOF program of the interface and not the implementations. And the tight coupling does not cater to us the interface concept
There is more information from tight coupling, and there is less information flow in loose coupling.
There is less coordination in loose coupling and more coordination in tight coupling.
It’s easier to code in the loose coupling, and quite complex to code in tight coupling.
Hence, loose coupling is always better than tight coupling. And with this, we come to the end of this tutorial on the Java coupling concept. We hope you now have understood what coupling is all about. If you will learn software project management then you will find that loose coupling is always better than tight coupling for software development. And you have seen it here as well.
Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:
You need to pay a nominal fee.
You can choose any Java certification, as per your skills and interest.
You have the option to select from online and classroom training.
A chance to study at one of the best Java training institutes in India
We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
Naresh I technologies cater to one of the best Java training in India.
And a lot more is waiting for you.
Contact us anytime for your complete Java online training.