You are reading the article Encapsulation In Java Oops With Example updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Encapsulation In Java Oops With Example
What is Encapsulation in Java?
Encapsulation in Java is a mechanism to wrap up variables(data) and methods(code) together as a single unit. It is the process of hiding information details and protecting data and behavior of the object. It is one of the four important OOP concepts. The encapsulate class is easy to test, so it is also better for unit testing.
In this tutorial, you will learn-
Learn Encapsulation with an ExampleTo understand what is encapsulation in detail consider the following bank account class with deposit and show balance methods
class Account { private int account_number; private int account_balance; public void show Data() { } public void deposit(int a) { if (a < 0) { } else account_balance = account_balance + a; } }Suppose a hacker managed to gain access to the code of your bank account. Now, he tries to deposit amount -100 into your account by two ways. Let see his first method or approach.
Approach 1: He tries to deposit an invalid amount (say -100) into your bank account by manipulating the code.
Now, the question is – Is that possible? Let investigate.
Usually, a variable in a class are set as “private” as shown below. It can only be accessed with the methods defined in the class. No other class or object can access them.
If a data member is private, it means it can only be accessed within the same class. No outside class can access private data member or variable of other class.
So in our case hacker cannot deposit amount -100 to your account.
Approach 2: Hacker’s first approach failed to deposit the amount. Next, he tries to do deposit a amount -100 by using “deposit” method.
But method implementation has a check for negative values. So the second approach also fails.
Thus, you never expose your data to an external party. Which makes your application secure.
The entire code can be thought of a capsule, and you can only communicate through the messages. Hence the name encapsulation.
Data Hiding in JavaData Hiding in Java is hiding the variables of a class from other classes. It can only be accessed through the method of their current class. It hides the implementation details from the users. But more than data hiding, it is meant for better management or grouping of related data.
To achieve a lesser degree of encapsulation in Java, you can use modifiers like “protected” or “public”. With encapsulation, developers can change one part of the code easily without affecting other.
Getter and Setter in JavaGetter and Setter in Java are two conventional methods used to retrieve and update values of a variable. They are mainly used to create, modify, delete and view the variable values. The setter method is used for updating values and the getter method is used for reading or retrieving the values. They are also known as an accessor and mutator.
The following code is an example of getter and setter methods:
class Account{ private int account_number; private int account_balance; public int getBalance() { return this.account_balance; } public void setNumber(int num) { this.account_number = num; } }Abstraction vs. Encapsulation
Often encapsulation is misunderstood with Abstraction. Lets study-
Encapsulation is more about “How” to achieve a functionality
Abstraction is more about “What” a class can do.
A simple example to understand this difference is a mobile phone. Where the complex logic in the circuit board is encapsulated in a touch screen, and the interface is provided to abstract it out.
Advantages of Encapsulation in Java
Encapsulation is binding the data with its related functionalities. Here functionalities mean “methods” and data means “variables”
So we keep variable and methods in one place. That place is “class.” Class is the base for encapsulation.
With Java Encapsulation, you can hide (restrict access) to critical data members in your code, which improves security
As we discussed earlier, if a data member is declared “private”, then it can only be accessed within the same class. No outside class can access data member (variable) of other class.
However, if you need to access these variables, you have to use public “getter” and “setter” methods.
You're reading Encapsulation In Java Oops With Example
What Is Abstraction In Oops? Java Abstract Class & Method
What is Abstraction in OOP?
Abstraction is the concept of object-oriented programming that “shows” only essential attributes and “hides” unnecessary information. The main purpose of abstraction is hiding the unnecessary details from the users. Abstraction is selecting data from a larger pool to show only relevant details of the object to the user. It helps in reducing programming complexity and efforts. It is one of the most important concepts of OOPs.
Let’s Study Abstraction in OOPs with example:Suppose you want to create a banking application and you are asked to collect all the information about your customer. There are chances that you will come up with following information about the customer
Abstraction in Java
So, you need to select only the useful information for your banking application from that pool. Data like name, address, tax information, etc. make sense for a banking application which is an Abstraction example in OOPs
Since we have fetched/removed/selected the customer information from a larger pool, the process is referred as Abstraction in OOPs.
Difference between Abstraction and EncapsulationAbstraction Encapsulation
Abstraction in Object Oriented Programming solves the issues at the design level. Encapsulation solves it implementation level.
Abstraction in Programming is about hiding unwanted details while showing most essential information. Encapsulation means binding the code and data into a single unit.
Data Abstraction in Java allows focussing on what the information object must contain Encapsulation means hiding the internal details or mechanics of how an object does something for security reasons.
Difference between Abstract Class and InterfaceAbstract Class Interface
An abstract class can have both abstract and non-abstract methods. The interface can have only abstract methods.
It does not support multiple inheritances. It supports multiple inheritances.
It can provide the implementation of the interface. It can not provide the implementation of the abstract class.
An abstract class can have protected and abstract public methods. An interface can have only have public abstract methods.
An abstract class can have final, static, or static final variable with any access specifier. The interface can only have a public static final variable.
What is Abstract Class?Abstract Class is a type of class in OOPs, that declare one or more abstract methods. These classes can have abstract methods as well as concrete methods. A normal class cannot have abstract methods. An abstract class is a class that contains at least one abstract method.
What are Abstract Methods?Abstract Method is a method that has just the method definition but does not contain implementation. A method without a body is known as an Abstract Method. It must be declared in an abstract class. The abstract method will never be final because the abstract class must implement all the abstract methods.
Advantages of Abstraction
The main benefit of using an Abstraction in Programming is that it allows you to group several related classes as siblings.
Abstraction in Object Oriented Programming helps to reduce the complexity of the design and implementation process of software.
When to use Abstract Methods & Abstract Class?Abstract methods are mostly declared where two or more subclasses are also doing the same thing in different ways through different implementations. It also extends the same Abstract class and offers different implementations of the abstract methods.
Abstract classes help to describe generic types of behaviors and object-oriented programming class hierarchy. It also describes subclasses to offer implementation details of the abstract class.
Summary:
Abstraction in Programming is the process of selecting important data sets for an Object in your software and leaving out the insignificant ones.
Once you have modeled your object using Data Abstraction in Java, the same set of data could be used in different applications.
Stack In C++ Stl With Example
What is std::stack?
A stack is a data structure that operates based on LIFO (Last In First Out) technique. The std::stack allows elements to be added and removed from one end only.
The std::stack class is a container adapter. Container objects hold data of a similar data type. You can create a stack from various sequence containers. If no container is provided, the deque containe will be used by default. Container adapters don’t support iterators, so it can’t be used to manipulate data.
In this C++ tutorial, you will learn
Stack Syntax
Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.
Container – is the Type of underlying container object.
Member TypesHere are stack member types:
value_type- The first template parameter, T. It denotes the element types.
container_type- The second template parameter, Container. It denotes the underlying container type.
size_type- Unsigned integral type.
Operations in StackA C++ stack supports the following basic operations:
push – It adds/pushes an item into the stack.
pop – It removes/pops an item from the stack.
peek – Returns the top item of the stack without removing it.
isFull – Checks whether a stack is full.
isEmpty – Checks whether a stack is empty.
Stack Implementation
Step 1) We initially have an empty stack. The top of an empty stack is set to -1.
Step 2) Next, we have pushed the element 5 into the stack. The top of the stack will points to the element 5.
Step 3) Next, we have pushed the element 50 into the stack. The top of the stack shifts and points to the element 50.
Step 4) We have then performed a pop operation, removing the top element from the stack. The element 50 is popped from the stack. The top of the stack now points to the element 5.
push() and pop()The stack::push() functions adds new item to the top of stack. The stack size is increased by a 1 after the insertion. The function takes this syntax:
stack.push(value)The value is the item to insert into the stack.
The stack:: pop() function removes the top element of the stack. This is the newest item of the stack. The stack size is reduced by 1 after the removal. Here is the function syntax:
stack.pop()The function takes no parameters.
Example 1:using namespace std; int main() { st.push(10); st.push(20); st.push(30); st.push(40);
st.pop(); st.pop();
while (!st.empty()) { cout << ‘ ‘ << st.top(); st.pop(); } }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic should be added within this function.
Create a stack st to store integer values.
Use the push() function to insert the value 10 into the stack.
Use the push() function to insert the value 20 into the stack.
Use the push() function to insert the value 30 into the stack.
Use the push() function to insert the value 40 into the stack.
Use the pop() function to remove the top element from the stack, that is, 40. The top element now becomes 30.
Use the pop() function to remove the top element from the stack, that is, 30. The top element now becomes 20.
Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.
Printing the current contents of the stack on the console.
Call the pop() function on the stack.
End of the body of the while loop.
End of the main() function body.
Stacks have inbuilt functions that you can use to play around with the stack and its values. These include:
empty()- checks whether a stack is empty or not.
size()- returns the size of stack, that is, number of elements in a stack.
top()- accesses stack element at the top.
Example 2:using namespace std; { while (!ms.empty()) { cout << ‘t’ << ms.top(); ms.pop(); } cout << ‘n’; } int main() { st.push(32); st.push(21); st.push(39); st.push(89); st.push(25);
cout << “The stack st is: “; createStack(st); cout << “n st.size() : ” << st.size(); cout << “n st.top() : ” << st.top(); cout << “n st.pop() : “; st.pop(); createStack(st); return 0; }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code in order to use its functions.
Include the stack header file in our code in order to use its functions.
Include the std namespace in our program in order to use its classes without calling it.
Create the function createStack that we can use to create the stack mystack. The stack will hold a set of integers.
The beginning of the body of the createStack function.
Create an instance of the mystack datatype and giving it the name ms.
Use the while loop and the empty() function to check whether the stack is empty.
The start of the body of the while loop.
Use the top() function stored at the top of the stack. The t character will create a new tab.
Use the pop() function to delete the element at the top of the stack.
End of the body of the while loop.
Print a blank line on the console.
End of the body of the createStack function.
Call the main() function. The program logic should be added within the body of the main() function.
The start of the body of function main().
Create a stack object st.
Use the push() function to insert the element 32 into the stack.
Use the push() function to insert the element 21 into the stack.
Use the push() function to insert the element 39 into the stack.
Use the push() function to insert the element 89 into the stack.
Use the push() function to insert the element 25 into the stack.
Print some text on the console.
Call the createStack function to execute the above insert operations into the stack.
Print the size of the stack on the console alongside other text.
Print the element at the top of the stack on the console.
Print some text on the console.
Delete the element at the top of the stack. It will then return the elements remaining in the stack.
Call the createStack function to execute the above operations.
The program must return value upon successful completion.
End of the body of function main().
emplace() and swap()These are other inbuilt stack functions:
emplace()- constructs then inserts new element to top of stack.
swap()- exchanges stack contents with another stack’s contents.
Example 3:using namespace std; int main() {
st1.emplace(12); st1.emplace(19);
st2.emplace(20); st2.emplace(23);
st1.swap(st2);
cout << “st1 = “; while (!st1.empty()) { cout << st1.top() << ” “; st1.pop(); }
cout << endl << “st2 = “; while (!st2.empty()) { cout << st2.top() << ” “; st2.pop(); } }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the cstdlib header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic will be added within the body of this function.
Declare a stack named st1 to store integer values.
Declare a stack named st2 to store integer values.
Use the emplace() function to insert the integer 12 into the stack named st1.
Use the emplace() function to insert the integer 19 into the stack named st1.
Use the emplace() function to insert the integer 20 into the stack named st2.
Use the emplace() function to insert the integer 23 into the stack named st2.
Use the swap() function to swap the contents of the two stacks, st1 and st2. The contents of the stack st1 should be moved to the stack st2. The contents of the stack st2 should be moved to the stack st1.
Print some text on the console.
Use the while statement and the empty() function to check whether the stack st1 is not empty.
Print the contents of the stack st1 on the console. The ” ” adds space between the stack elements when printing them on the console.
Execute the pop() function on the stack st1 to remove the top element.
End of the body of the while statement.
Print some text on the console. The endl is a C++ keyword for end line. It moves the mouse cursor to the next line to begin printing from there.
Use the while statement and the empty() function to check whether the stack st2 is not empty.
Print the contents of the stack st2 on the console. The ” ” adds space between the stack elements when printing them on the console.
Execute the pop() function on the stack st2 to remove the top element.
End of the body of the while statement.
End of the body of the main() function.
Stack in STLThe STL (Standard Template Library) comes with template classes that provide common C++ data structures. Therefore, a stack can also be implemented in STL. We simply include this library in our code and use it to define a stack.
The above syntax declares a stack st to elements of data type T.
Example 3:using namespace std; int main() { st.push(12); st.push(19); st.push(20); cout << st.top(); cout << st.size(); }
Output:
Here is a screenshot of the code:
Code Explanation:
Include the iostream header file in our code to use its functions.
Include the stack header file in our code to use its functions.
Include the cstdlib header file in our code to use its functions.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic should be added within the body of this function.
Declare a stack st to store integer data.
Add the element 12 to the stack.
Add the element 19 to the stack.
Add the element 20 to the stack.
Print the element at the top of the stack on the console.
Print the size of the stack on the console.
End of the body of the function main().
Summary:
A stack is a data structure that operates based on the LIFO (Last In first Out) technique.
The std::stack only allows items to be added and removed from one end.
The std::stack class is a container adapter, holding items of a similar data type.
A stack can be created from various sequence containers.
If you don’t provide a container, the deque container will be used by default.
The push() function is for inserting items into the stack.
The pop() function is for removing the top item from the step.
The empty() function is for checking whether a stack is empty or not.
Calculator (Example With Excel Template)
Cost-Benefit Analysis Formula (Table of Contents)
Start Your Free Investment Banking Course
Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others
What is the Cost-Benefit Analysis Formula?The term “cost-benefit analysis” refers to the analytical technique that compares the benefits of a project with its associated costs. In other words, all the expected benefits out a project are placed on one side of the balance and the costs that have to be incurred are placed on the other side. The cost-benefit analysis can be executed either using “benefit-cost ratio” or “net present value”.
The formula for a benefit-cost ratio can be derived by dividing the aggregate of the present value of all the expected benefits by an aggregate of the present value of all the associated costs, which is represented as,
Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs
The formula for net present value can be derived by deducting the sum of the present value of all the associated costs from the sum of the present value of all the expected benefits, which is represented as,
Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs
Example of Cost-Benefit Analysis Formula (With Excel Template)Let’s take an example to understand the calculation of Cost-Benefit Analysis in a better manner.
You can download this Cost-Benefit Analysis Excel Template here – Cost-Benefit Analysis Excel Template
Cost-Benefit Analysis Formula – Example #1Let us take the example of a financial technology start-up which is contemplating on hiring two new programmers. The promoter expects the programmers to increase the revenue by 25% while incurring an additional cost of $45,000 in the next one year. The help promoter decides whether to go ahead with the recruitment based on cost-benefit analysis if the revenue of the company in the current year is $220,000 and the relevant discount rate is 5%.
Solution:
PV of Benefit is Calculated as:
PV of Benefit= $55,000 / (1 + 5%)
PV of Benefit = $52,380.95
PV of Cost is Calculated as:
PV of Cost = $35,000 / (1 + 5%)
PV of Cost = $33,333.33
Benefit-Cost Ratio is calculated using the formula given below
Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs
Benefit-Cost Ratio = $52,380.95 / $33,333.33
Benefit-Cost Ratio = 1.57x
Net Present Value is calculated using the formula given below
Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs
Net Present Value = $52,380.95 – $33,333.33
Net Present Value = $19,047.62
Therefore, both the method of cost-benefit analysis suggests that the promoter should go ahead with the recruitment.
Cost-Benefit Analysis Formula – Example #2Let us take the example of two projects to illustrate the use of cost-benefit analysis. The sum of the present value of expected benefits from Project 1 is $50 million with the sum of the present value of associated costs of $30 million. On the other hand, the sum of the present value of expected benefits from Project 2 is $10 million with the sum of the present value of associated costs of $5 million. Discuss which project is better based on cost-benefit analysis.
Solution:
Benefit-Cost Ratio is calculated using the formula given below
Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs
For Project 1
Benefit-Cost Ratio = $50,000,000 / $30,000,000
Benefit-Cost Ratio = 1.67x
For Project 2
Benefit-Cost Ratio = $10,000,000 / $5,000,000
Benefit-Cost Ratio = 2.00x
Net Present Value is calculated using the formula given below
Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs
For Project 1
Net Present Value = $50,000,000 – $30,000,000
Net Present Value = $20,000,000
For Project 2
Net Present Value = $10,000,000 – $5,000,000
Net Present Value = $5,000,000
ExplanationThe formula for cost-benefit analysis can be calculated by using the following steps:
Step 1: Firstly, Calculate all the cash inflow from the subject project, which is either revenue generation or savings due to operational efficiency.
Step 2: Next, Calculate all the cash outflow into the project, which are the costs incurred in order to maintain and keep the project up and running.
Step 3: Next, Calculate the discounting factor based on the current pricing of assets with a similar risk profile.
Step 4: Next, based on the discounting factor, calculate the present value of all the cash inflow and outflow. Then, add up the present value of all the cash inflow as ∑PV of all the expected benefits and outflow as ∑PV of all the associated costs.
Step 5: Now, the formula for a benefit-cost ratio can be derived by dividing aggregate of the present value of all the expected benefits (step 4) by aggregate of the present value of all the associated costs (step 4) as shown below.
Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs
Step 6: Now, the formula for net present value can be derived by deducting the sum of the present value of all the associated costs (step 4) from the sum of the present value of all the expected benefits (step 4) as shown below.
Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs
Relevance and Use of Cost-Benefit Analysis FormulaThe importance of cost-benefit analysis lies in the fact that it is used for assessing the feasibility of an opportunity, comparing projects, appraising opportunity cost and building real-life scenario-based sensitivity testing. In this way, this technique helps in ascertaining the accuracy of an investment decision and provides a platform for its comparison with similar proposals.
Cost-Benefit Analysis Formula CalculatorYou can use the following Cost-Benefit Analysis Formula Calculator
∑PV of all the Expected Benefits ∑PV of all the Associated Costs Benefit-Cost Ratio Benefit-Cost Ratio = ∑PV of all the Expected Benefits =
∑PV of all the Associated Costs
0
= 0
0
Recommended Articles
This is a guide to Cost-Benefit Analysis Formula. Here we discuss how to calculate the Cost-Benefit Analysis Formula along with practical examples. We also provide a Cost-Benefit Analysis calculator with a downloadable excel template. You may also look at the following articles to learn more –
Junit Errorcollector @Rule With Example
In a normal scenario, whenever you identify any error during test execution, you would stop the test, fix the error and re-run the test.
But JUnit has a slightly different approach. With JUnit error collector, you can still continue with the test execution even after an issue is found or test fails. Error collector collects all error objects and reports it only once after the test execution is over.
In this tutorial, you will learn-
Why use Error Collector?While writing a test script, you want to execute all the tests even if any line of code fails due to network failure, assertion failure, or any other reason. In that situation, you can still continue executing test script using a special feature provided by JUnit known as “error collector.”
For this, JUnit uses @Rule annotation which is used to create an object of error collector. Once the object for error collector is created, you can easily add all the errors into the object using method addError (Throwable error). As you know, that Throwable is the super class of Exception and Error class in Java. When you add errors in this way, these errors will be logged in JUnit test result .
The benefit of adding all errors in an Error Collector is that you can verify all the errors at once. Also, if the script fails in the middle, it can still continue executing it
Note: In the case of using simple assert or try/catch block , using error collector method won’t be possible.
Sample code
To understand more on Error Collector, see below code example which demonstrates how to create an Error Collector object and add all the errors in that object to track the issue :
package guru99.junit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class ErrorCollectorExample { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("There is an error in first line")); collector.addError(new Throwable("There is an error in second line")); collector.checkThat(getResults(), not(containsString("here is an error"))); be logged in. } } What is @Rule in jUnit?JUnit provides special kind of handling of tests, Test Case or test suite by using @rule annotation. Using @rule, you can easily add or redefine the behaviour of the test.
There are several built-in rules provided by JUnit API that a tester can use, or even you can write our own rule.
See below line of code, which shows how to use @rule annotation along with Error Collector:
@Rule public ErrorCollector collector= new ErrorCollector(); Example using ErrorCollectorTo understand error collector, let’s create a class and a rule to collect all the errors. You will add all the errors using addError(throwable) here.
See below code which simply creates a rule which is nothing but creating “Error Collector object.” Which is further used to add all the errors in order to report the issue at the end:
ErrorCollectorExample.java
package guru99.junit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class ErrorCollectorExample { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("There is an error in first line")); collector.addError(new Throwable("There is an error in second line")); System.out.println("Hello"); try { Assert.assertTrue("A " == "B"); } catch (Throwable t) { collector.addError(t); } System.out.println("World!!!!"); } }TestRunner.java
Let’s add above test class in a test runner and execute it to collect all errors. See below code:
package guru99.junit; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(ErrorCollectorExample.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println("Result=="+result.wasSuccessful()); } }Output:
See the failure trace which traces all the errors in one place:
Benefits of JUnit ErrorCollector
You can use JUnit assertion for functional or GUI validation e.g.
assertEquals(String message, Object expected, Object actual) which compare that two objects are equals.
Similarly, assertTrue(Boolean condition) asserts that a condition is true.
Using assertion, validation test becomes easy. But one major issue is that test execution will stop even if a single assertion fails.
Test continuity and recovery handling is crucial to test automation success. Error Collector is the best way to handle such kind of scenarios.
Summary:
Junit error collector allows a test to continue even after the first issue is found and test fails at the end
Error collector collects all error objects and reports it only, after all, the test execution over
The benefit of adding all errors in an Error Collector is that you can verify all the errors at once
Error collector simply adds errors using method addError(throwable err) provided by ErrorCollector.java.
How Does Do While Loop Work In Java With Examples
Introduction to do while loop in Java
Looping in any programming language has been used ever since. Loops and iterations form an essential component of the programming language, Be it Java or Python; One such looping construct is the do-while loop in the language of Java which is also popularly known as a post-incremental loop, i.e. where the looping construct runs for one time for sure and then the condition is matched for it to run the next time and so on. The condition, in this case, is put in the end. In other words, the condition blocks keep on executing continuously unless and until a specific set of conditions is termed as true.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
do { } while (expression);The expression which is mentioned right after the while block is used to return a Boolean value, i.e. either a true value or a false value. If either of the values could not be found, then the compiler throws a compile-time error. The do command in this syntax ensures that the code is executed at least once, even when the expression is not executed, or the condition is not checked. The block of statements is the set of statements that are executed inside the do-while looping construct. This consists of the program body. The while statement, in the end, is used to evaluate the expression and then apply a postcondition to check whether the intended case is meeting the requirements and should be further looped.
How does a do-while loop work in Java?Following is the explanation for how does do-while loop work in Java:
For a do-while loop to work, the condition is not necessary to be met as this loop also works well for the first time even when the condition is not met. The compiler executor then enters the function execution block executes whatever is there within the block of statements, and then comes out to check the expression part where the condition is compared. If the condition is met, then the loop is reiterated; otherwise, the loop is exited from the block. The basic difference between the while and the do-while loop is that while the former one looks for the pre-conditions, the latter one targets the postconditions.
The basic difference between a do-while and a very well-known loop is that the number of iterations is needed to be known in the loop and the initial value and the value which is being incremented. This is more often used when the iterations and their count are fixed in number, whereas in the case of the do-while loop, the number of iterations is not known before-hand but can change dynamically.
Flow Diagram:
Examples for do-while loop in JavaBelow are the examples of all the numbers till 10:
Example #1Printing all the Numbers less than equal to 10.
Code:
public class Main { public static void main(String args []) { int c=1; System.out.println("printing all the numbers till 10:"); do { System.out.println(c); ++c; } while(c<11); } }Output:
Example #2Iterating an Array by making use of do-while loop in Java.
Code:
public class Main { public static void main(String args []) { int arr[]= {1, 6, 7, 514, 4, 98}; System.out.println("Printing the list of arrays: "); int i=0; do { System.out.println(arr[i]); ++i; } while (arr[i]<=6); } } Example #3Writing a program for an Infinite do-while loop.
Code:
public class Main { public static void main(String[] args) { do { System.out.println("infinite do while loop"); } while(true); } }Output:
This program will run infinitely until the code block is explicitly broken as the infinite loop hits the condition of the while loop is true, which is a true condition and will always be met. Therefore, these types of loops and programming constructs are not encouraged. They can confuse the compiler and hang your system if it doesn’t contain appropriate RAM and other memory requirements.
Example #4Printing all the Numbers from 10 till 1 in Reverse order.
Code:
public class Main { public static void main(String args []) { int c=10; System.out.println("Printing all the numbers from 10 till 1"); do { System.out.println(c); --c; } } Example #5Printing all the numbers less than Equal to 10 without using the Increment operator.
Code:
public class Main { public static void main(String args []) { int c=1; System.out.println("printing all the numbers till 10"); do { System.out.println(c); c+=1; } while(c<11); } }Output:
The basic difference between this example and the first example was the use of shorthand operators in this case and the use of a pre-incremental counter in the case of example number 1. Both of them will produce the same result; it is just a matter of your choice of which operator you wish to choose for the do-while loop.
ConclusionIn this post, we saw the basic level of introduction to do while loop. We also saw the working of the do-while loop in detail. We saw the intricacies and the major differences and the do-while loop applications over other looping constructs such as while or for loops. We studied the flowchart of the do-while loop, which helped us in understanding it more deeply. We read about the syntax and a huge list of various examples to understand the do-while loop clear.
Recommended ArticlesThis is a guide to do while loop in Java. Here we discuss how does do while loop work in Java, with a flow diagram and top 5 examples in it. You can also go through our other related articles to learn more –
Update the detailed information about Encapsulation In Java Oops With Example on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!