A Java stream represents potentially an infinite sequence of data. This is a simple post that will go into the mechanics involved in generating a simple stream of Fibonacci numbers.
Friday, January 29, 2021
Generating a stream of Fibonacci numbers
Wednesday, January 27, 2021
The Temporary Test Property
It may be seen in languages such as JavaScript where there’s a master let setting up some useful variables for various tests to use to assign values to. I’ve more seen it in Java though, where there can be a sort of phobia of creating temporary variables inside tests, so instead all the variables are declared in the parent class.
Let’s look at a quick example:
class ParagraphAnalyzerTest {
private String analyzed;
private ParagraphAnalyzer analyzer = new ParagraphAnalyzer();
@Test
void nouns() {
analyzed = analyzer.justNouns("This is a word");
assertThat(analyzed).isEqualTo("word");
}
@Test
void verbs() {
analyzed = analyzer.justVerbs("This is a word");
assertThat(analyzed).isEqualTo("is");
}
@Test
void ends() {
analyzed = analyzer.first("This is a word");
assertThat(analyzed).isEqualTo("This");
analyzed = analyzer.last("This is a word");
assertThat(analyzed).isEqualTo("words");
}
}
In the above simple, fictional example, the test class has two members. There’s ParagraphAnalyzer which is the code under test and which it seems to make sense to have as a member of the fixture. Then there’s analyzed which seems to have a different value in each test.
The fact that each test gives its own value to the analyzed is a smell that analyzed is not being managed by the test fixture and so does not belong as a property of it.
We’re saving a repeated declaration of a String every time… which is so very not worth the baggage of this risky shared property.
Now, the risk is probably nothing, because the above test will create a new instance of the class for each test case, so there’s no bleed between states… but that’s only true if I don’t change the test instance lifecycle. JUnit 5 will let me do this differently. Plus, if I’m in the habit of using members for temp variables, what’s to stop me doing that with static members as well?
There’s no justification for this temp variable being promoted somewhere higher up the food chain.
You may also notice another test anti-pattern in the last unit test, above. The value of analyzed is being reassigned. Another awkward move. This is the Two For the Price of One test smell, where a single test case is executing two independent use cases.
When To Use What?
Consider each test case as having its own state. The test case inherits any commonly set up or torn down state from the test fixture. This approach avoids code repetition, and other difficulties with setting up expensive resources for each test.But… as soon as the common set up is done, each test case should do its own thing, clearly and without littering the test fixture with its problems.
Storing what is essentially request scope in the instance state of an object is an anti pattern outside of testing and should be considered on inside it too!
Monday, January 25, 2021
Extends vs Implements in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. There are two main keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between extends and implements is discussed.
Before getting into the differences, lets first understand in what scenarios each of the keywords are used.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.
Example:
class One {
public void methodOne()
{
// Some Functionality
}
}
class Two extends One {
public static void main(String args[])
{
Two t = new Two();
// Calls the method one
// of the above class
t.methodOne();
}
}
Extends | Implements |
By using “extends” keyword a class can inherit another class, or an interface can inherit other interfaces | By using “implements” keyword a class can implement an interface |
It is not compulsory that subclass that extends a superclass override all the methods in a superclass. | It is compulsory that class implementing an interface has to implement all the methods of that interface. |
Only one superclass can be extended by a class. | A class can implement any number of an interface at a time |
Any number of interfaces can be extended by interface. | An interface can never implement any other interface |
Friday, January 22, 2021
Testing Logging Output in Java
Testing that the logged output is as expected seems to be on the cusp of a good/bad idea. Is the logged output the intended behavior of the application? or is it an implementation detail that you’re just mirroring in a test?
Arguably, it’s sometimes the former… logging is the sort of thing that matters when it matters.
I’d argue that it’s often too low level a thing to be testing, but it’s a critical thing to test when:
◉ You’re writing a logging framework that centralises the logging logic
◉ You have some exceptional case that MUST be logged differently and need to lock down the behaviour
◉ Logging IS the logic for some reason
Note, I like to think of tests as locking down the logic – we wrote the code this way today, hopefully using TDD, to achieve something observable by a test. The test keeps that observable behaviour from disappearing by going red if someone breaks it. So the test locks down some spec.
Logging in the Modern World
These days we deliberately log to the System console, rather than log files. This works well when we’re containerising our application, or writing an AWS Lambda, and we want the hosting environment’s log scraper to pull the logs from stdout rather than mine log files as we write them.
Spooling log messages to the console, while once thought of as a no-no, is essentially a lot cleaner than telling a logging agent to go and read a file as we write it.
Can’t We Just Watch System.out Then?
Well, indeed we can. No need to register a listener into the logging framework. Let’s just look at what appears on the console. We can configure our logger to write to the console – in fact it probably does already!
Enter System Stubs
I will write more about it in due course, but System Stubs is a testing library I’ve worked hard on in recent weeks. It started life as a different project that I forked, and then I essentially reworked it to fit in with the sort of tests I’ve been writing. As such, it’s available as a JUnit 5 extension (as well as in other forms).
Let’s imagine we have some code under test that’s going to do some logging, and we want to see if a certain message appears.
Here’s a test:
@ExtendWith(SystemStubsExtension.class)
class TheOneAboutTheLoggingTest {
@SystemStub
private SystemOut systemOut;
@Test
void youKnow_ForLogging() {
doTheThingThatShouldLog();
assertThat(systemOut.getLines())
.anyMatch(line -> line.contains("ERROR This is bad!"));
}
}
Let’s just unpack a few of the elements in the above.
There’s the JUnit 5 extension – SystemStubsExtension. No big deal. Then there’s a SystemOut object, which is used to capture System.out while the object is active. The object is created by the extension and is activated just before the test, then cleared up afterwards.While the test is running, System.out is not appearing in the console, it’s being stored in the memory of the SystemOut object’s TapStream.
At any point we can expect the lines of text that have appeared on System.out. The getLines function provides a Stream<String> which we inspect here using AssertJ.
Given logging output usually contains timestamps, this method requires us to do some sort of substring checking to avoid having to predict the timestamp. Perhaps a future library might help parse the output a little more.
It’s also worth noting that NOT seeing the logging output on the console is a little annoying during this sort of test. In due course, I’m planning to release version 1.2.0 of SystemStubs which will allow a multiplex where the output appears on the console AND is also tapped.
So is Tapping System.out the Future of Log Testing?
Yes and no.
It’s enormously convenient and easy to do. So, I’m inclined to default to it.
However, for fine-grained testing of exactly what is being sent to the logging library, the reading of strings from a console is a bit messy.
Source: javacodegeeks.com
Wednesday, January 20, 2021
How to get current date time with Java 8
In this quick tutorial, we will see, how to get current date time using Java 8.
Java 8 had come up with new set of classes for date and time under java.time package, which are:
– java.time.Instant
– java.time.ZonedDateTime
– java.time.OffSetDateTime
– java.time.LocalDateTime
Let us see how we can get current date and time using these classes and how they are different from each other.
Using Instant
Instant represents a moment. For example, if World cup is starting at certain moment, it is exact that moment for everyone living in any part of world. If world cup is in Australia, then people in India can say that ,world cup started at different time than what what was time in Australia but it started at exact same moment on timeline for people of Australia as well as India.
Using Instant, we can get the exact moment on timeline which is independent from time zones.
which in other words means that if two Instant objects are created at the same moment in any part of world, they will have exactly same value.
Instant represents date time in UTC(coordinated universal time), so it does not consider specific Zone and it is number of nanoseconds elapsed since epoch or since 1970-01-01T00:00:00Z. It is similar to GMT(Greenwich mean time).
All date times for specific Zones are calculated relative to UTC.
For example:
– A time in UTC (zone) itself, UTC + 0 is indicated by a Z( Z from Zulu time)
– Countries like Ireland, Portugal, Ghana follows UTC time zone, which means UTC + 0
– Japan follows UTC+9
– Barbados follows UTC-4
For complete list for all countries, you can check List of Countries with UTC time offsets
For our back end calculations in Java, we use Instant. For example, If we are running a job and want to calculate the time for next run we would use Instant.Now coming back to current date-time using Instant, we need to use now() method as below:
Instant instant = Instant.now();
System.out.println("Current Date Time using Instant:" + instant);
Output:
Current Date Time using Instant:2021-01-09T22:25:06.385917300Z
Using ZonedDateTime
If you want to know date time, in your time zone, at a particular moment( represented by Instant) you can use ZonedDateTime.
You can either adjust the instant created above to get the ZonedDateTime like below:
Adjusting Instant object
System.out.println("Using instant.atZone():" + instant.atZone(ZoneId.of("Europe/Amsterdam")));
Output:
Using instant.atZone():2021-01-09T23:25:06.385917300+01:00[Europe/Amsterdam]
This gives me exact date time in Amsterdam.
Using now(ZoneId zoneId):
Alternatively you can use factory method now(ZoneId zoneId) defined in ZonedDateTime class itself like below:
System.out.println("Using ZonedDateTime.now(zoneId):" + ZonedDateTime.now(ZoneId.of("Europe/Amsterdam")));
Output:
Using ZonedDateTime.now(zoneId):2021-01-09T23:25:06.408922700+01:00[Europe/Amsterdam]
Using now():
And there is one more option where in you can use factory method now() of ZonedDateTime class. However you must know that now() uses the default time zone of your JVM, which is subject to change, so better always pass zoneId.
System.out.println("ZonedDateTime with now():" + ZonedDateTime.now());
Output:
Using ZonedDateTime.now():2021-01-09T23:25:06.414919900+01:00[Europe/Berlin]
Another variant of now() is like below for using default time zone using ZoneId.systemDefault() as ZoneId.
System.out.println("Using ZonedDateTime.now(ZoneId.systemDefault())" + ZonedDateTime.now(ZoneId.systemDefault()));
Output:
Using ZonedDateTime.now(ZoneId.systemDefault()):2021-01-09T23:25:06.414919900+01:00[Europe/Berlin]
ZonedDateTime supports Day Light Savings
ZonedDateTime uses ZoneRules to determine how an offset varies for a particular time zone in case of Day light saving.
Lets take an example. Day light saving in Netherlands in 2021 is going to start from March 28, 2:00 AM and will end on October 31, 3:00 AM
Let us first try to see date time before(by 1 hour) Day light saving starts, i.e. at 1 AM
System.out.println("ZonedDateTime.of() before DLS: " + ZonedDateTime.of(2021, 3, 28, 1, 0, 0,0, ZoneId.of("Europe/Amsterdam")));
Output:
ZonedDateTime.of() before DLS: 2021-03-28T01:00+01:00[Europe/Amsterdam]
As you can see, it returned the time which we have asked for i.e. 1 AM and offset is of +1:00
Now let us try to see date time at the time when Day light saving is going to start i.e. at 2 AM.
System.out.println("ZonedDateTime.of() DLS start: " + ZonedDateTime.of(2021, 3, 28, 2, 0, 0,0, ZoneId.of("Europe/Amsterdam")));
Output:
ZonedDateTime.of() DLS start: 2021-03-28T03:00+02:00[Europe/Amsterdam]
As you can see , ZonedDateTime API automatically adjusted the time and returned time which is 1 hour ahead i.e. 3 AM instead of 2 AM and also now Offset is set to +2:00.
Using OffsetDateTime
OffsetDateTime represents a moment in date time which is some duration ahead(+) or behind(-) the UTC or in other words with offset from UTC without a Time ZoneId such as “Europe/Amsterdam”.
You can use ZoneOffset class to represent offset in hours, hours: minutes or hours: minutes: seconds.
So if the OffSet is zero, then OffsetDatTime represents Instant, which is in UTC.
System.out.println("Using OffsetDateTime.now():" + OffsetDateTime.now());
Output:
Using OffsetDateTime.now():2021-01-09T23:25:06.415920100+01:00
Monday, January 18, 2021
Static Nested Classes Java
In Java, it is possible to define a class within another class. Class defined within another Class is called a Nested Class.
Nested class is treated as a member of the Outer class because it is also defined within the Outer class like its other members(variables or methods).
public class OuterClass {
class NestedClass {
}
}
Static Nested Class:
Rules for static nested class as a static member of Outer class
What is the use of Static nested Classes ?
Friday, January 15, 2021
Difference between Java and C language
Here are some of the differences between Java and C language.
C is much faster than Java
Java is slower than C due to overhead.
C | JAVA |
C was developed by Dennis M. Ritchie between 1969 and 1973. | Java was developed by James Gosling in 1995. |
C is a Procedural Programming Language. | Java is Object-Oriented language. |
C is more procedure-oriented. | Java is more data-oriented. |
C is a middle-level language because binding of the gaps takes place between machine level language and high-level languages. | Java is a high-level language because translation of code takes place into machine language using compiler or interpreter. |
C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system. | Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine). |
C generally breaks down to functions. | Java breaks down to Objects. |
C programming language can be used for system programming as well as Application programming. | This is not the case in Java. |
C does not contain the property called Inheritance because it does not support OOPS, which is very useful for code reusability. Thus C is not suited when one has to relate the things according to the real world. | Java contains the property of Inheritance which is very useful in code reuseability. |
Memory allocation can be done by malloc in C | Memory allocation can be done by a new keyword in Java. |
C is a low-level language. It has difficult interpretation for the user but it has a closer significance to the machine-level code. | Java is a high-level language because translation of code takes place into machine language using compiler or interpreter. |
In C89 declaration of variables is at the beginning of the block but in the latest version of C that is C99 we can also declare variables anywhere. | We can declare variables anywhere. |
free is used for freeing the memory in C. | A compiler will free up the memory internally by calling the garbage collector. |
C does not supports Threading. | Java supports the concept of threading. |
C supports pointers. | Java does not supports pointers. |
It is not portable. | It is portable. |
Call by value and call by reference is supported in C. | It only supports a call by value. |
C is platform dependent. | Java is a platform independent. |
It supports user-based memory management. | It internally manages the memory. |
C is not robust that is strict type checking does not takes place while compile and run time. | Java is robust. |
Exception handling cannot be directly achieved in C and thus it lacks the maintenance of normal flow of the program. | Exception Handling is supported in Java. |
It follows a top-down approach. | Java follows a bottom-up approach. |
Overloading functionality is not supported by C. | Java supports method overloading which helps in code readability. |
C supports Preprocessors. | Java does not support Preprocessors. |
C does not supports OOPS concept. | Java supports OOPS concept. |
Union and structure datatypes are supported by C. | Java does not supports union and structures. |
C supports the storage classes. | Whereas Java does not suport the storage classes. |
It has 32 keywords. | It has 50 keywords. |
Go-to statements are supported in C language. | Java does not supports go-to statements. |
Virtual keywords are supported by C. | Virtual keywords are not supported by Java. |
Overloading functionality is not supported by C. | Java supports method overloading which helps in code readability. |
Default members of C are public. | Default members of Java are private. |
Data hiding is done by using static in C. | Data hiding is done by using private in Java. |
Wednesday, January 13, 2021
Builder Design Pattern
We will discuss Builder design pattern.
Key topics we are going to discuss are :
– Which category Builder Design Pattern falls in ?
– What problem builder Pattern is solving or when to use Builder pattern?
– Builder Pattern
– Builder Pattern Example
– Advantages of Builder Pattern
– Disadvantages of Builder Pattern
Which category Builder Design Pattern falls in ?
Builder pattern falls under Creational design patterns category, as it deals with the creation of object(s).Please note that Builder design pattern that I am going to describe here is not GOF design pattern but the one suggested by Joshua block in
Effective Java, as I personally see this pattern used for more often or more practical than the one suggested by GOF.
What problem builder Pattern is solving or when to use Builder pattern?
In nutshell, you should use Builder design pattern when :
– You have a class, which has some mandatory fields and some optional fields, which in other words means that your object can be constructed in various ways as per requirements. Although you are free to use it with a class with all mandatory fields as well when number of fields are too many(usually more than four is a good candidate).
– You want objects of your class to be immutable, which means once objects are instantiated there state can not be changed after that.
Now lets discuss these points in more detail.
You have a class with some mandatory and some optional fields :
What is the problem with having optional fields.
Let us say you have below Student class with mandatory and optional fields and have a constructor with all the fields.
package com.blogspot.oraclejavacertified;
public class Student {
//mandatory fields
private final String id;
private String firstName;
private String lastName; //optional fields
private String age;
private String houseNumber;
private String streetNumber;
public Student(String id, String firstName, String lastName, String age, String houseNumber, String streetNumber) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.houseNumber = houseNumber;
this.streetNumber = streetNumber;
}
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAge() {
return age;
}
public String getHouseNumber() {
return houseNumber;
}
public String getStreetNumber() {
return streetNumber;
}
}
Now, say the client of this code might want to create instance of Student with
– Only Mandatory fields
– All the Mandatory as well as optional fields
– Mandatory fields and one or more of the optional fields
Then the constructors for above scenarios will look like as below :
//Only Mandatory fields Student student2 = new Student("201", "firstName2", "surName2", null, null, null);
//All the Mandatory as well as optional fields Student student1 = new Student("101", "firstName1", "surName1", "16", "11", "2");
//Mandatory fields and one or more optional fields Student student3 = new Student("301", "firstName3", "surName3", "20", null, null);
Student student4 = new Student("301", "firstName4", "surName4", "20", "22", null);
Now, what is the problem with the above constructors?
Actually, there are multiple problems, like
– Client code has to unnecessarily pass null for all optional fields.
– Code readability is not good. As the number of parameters grow, it becomes difficult and error prone for client code to understand what needs to be passed at which position and later to read for the person who is going to maintain the code.
– When adjacent parameters are of same data type, you might accidently exchange their values which will go unnoticed at compile time but create some severe bug at run time. For example, developer can accidently interchange values for age and houseNumber.
So What can you do to solve these problems ?
Probably we can have look at the Telescoping constructor pattern.
In Telescoping constructor pattern, we create multiple constructor overloads starting with one with all mandatory fields and then with one optional field and then with two optional fields and so on until we have constructor with all fields.Each constructor calls another constructor with one more optional field and passes the default value for the optional field(can be null or any other default you want to set) until the last constructor with all optional fields is called.
package com.blogspot.oraclejavacertified;
public class Student {
//Mandatory fields
private String id;
private String firstName;
private String lastName;
//Optional fields
private String age;
private String houseNumber;
private String streetNumber;
public Student(String id, String firstName, String lastName) {
this(id, firstName, lastName, "0");
}
public Student(String id, String firstName, String lastName, String age) {
this(id, firstName, lastName, age, "0");
}
public Student(String id, String firstName, String lastName, String age, String houseNumber) {
this(id, firstName, lastName, age, houseNumber, "0");
}
public Student(String id, String firstName, String lastName, String age, String houseNumber, String streetNumber) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.houseNumber = houseNumber;
this.streetNumber = streetNumber;
}
}
Now let us see which problems telescoping constructor solved :
– Client code no longer has to pass null for all the optional fields as well.
– From client code perspective, readability is better.
But telescoping constructors comes with its own problems:
– What if more optional fields are added in Student class in future, then for each new field another constructor needs to be introduced.
– Still you need to carefully see all overloads of the constructor and choose the one which suits your requirement.
– Still if you have say age and streetNumber but houseNumber is not available, then you need to instantiate Student class like below, so still client need to pass in null value for optional field.
Student student = new Student("101", "firstName", "lastName", "35", null, "3");
– And still there is possibility of getting exchange of values of same data type, when the number of optional fields are too many.
We will see how builder pattern solves these problems later but for now let us discuss the other aspect which makes a case for using builder pattern.
You want objects of your class to be immutable :
If you don’t want state of your object to get changed once it has been created(and of course it has lots of fields), you can use build pattern, as builder pattern makes sure your object is immutable once it is created.
Advantages of Immutable classes :
– They are more reliable as it is known that their state is not going to change after creation.
– They are inherently thread safe and don’t need any synchronization.
– They make great candidates to be used as a key of a HashMap or to be put in a HashSet.
Now let us see implementation of Builder pattern by taking example of our Student class.
Builder pattern
– In builder pattern , you leave the responsibility of creating object or instantiating your class to Builder which is another class which has exactly same number of fields as your class whose objects builder is going to build.
– As your builder class is going to be used only for creating objects of your class and is not going to be used elsewhere, it is defined as static nested class within your class.
– You provide a builder’s constructor with only mandatory fields and then you provide methods(mutators) in builder to set the remaining optional fields. You can chain these methods as each of these method again returns Builder. Note that till now we are talking only about using builder constructor and using methods to set other optional fields and all these are still part of Builder object and we have not yet created actual Student object, so we are not concerned about immutability yet.
So in terms of code, we are here :
Student.StudentBuilder studentBuilder2 = ("2", "Sachin", "Tendulkar").withAge("47");
Now all we need to do is call build() method of our builder on the created builder instance like below :
studentBuilder2.build()
Builder pattern example
Advantages of Builder Pattern :
Disadvantages of Builder Pattern :
Tuesday, January 12, 2021
Why Java is not a purely Object-Oriented Language?
Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented Language which supports or have features which treats everything inside program as objects. It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
1. Encapsulation/Data Hiding
2. Inheritance
3. Polymorphism
4. Abstraction
5. All predefined types are objects
6. All user defined types are objects
7. All operations performed on objects must be only through methods exposed at the objects.
Example: Smalltalk
Why Java is not a Pure Object Oriented Language?
Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java language is not a Pure Object Oriented Language as it contain these properties:
◉ Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-oriented programming language unlike Java and C++ as there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects.
In Java, we have predefined types as non-objects (primitive types).
int a = 5;
System.out.print(a);
◉ The static keyword: When we declares a class as static then it can be used without the use of an object in Java. If we are using static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented feature.
◉ Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.
String s1 = "ABC" + "A" ;
Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.
public class BoxingExample
{
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
Integer k = new Integer(i.intValue() + j.intValue());
System.out.println("Output: "+ k);
}
}
Monday, January 11, 2021
enum in Java
Enumerations serve the purpose of representing a group of named constants in a programming language. For example the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.
In Java (from 1.5), enums are represented using enum data type. In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).
Declaration of enum in java :
◉ Enum declaration can be done outside a Class or inside a Class but not inside a Method.
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}
public class Test
{
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Important points of enum :
Enum and Inheritance :
values(), ordinal() and valueOf() methods :
enum and constructor :
enum and methods :
Sunday, January 10, 2021
Generating random numbers in Java
Java provides three ways to generate random numbers using some built-in methods and classes as listed below:
◉ java.util.Random class
◉ Math.random method : Can Generate Random Numbers of double type.
◉ ThreadLocalRandom class
1) java.util.Random
◉ For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance.
◉ We can generate random numbers of types integers, float, double, long, booleans using this class.
◉ We can pass arguments to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive.
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;
public class generateRandom{
public static void main(String args[])
{
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
int rand_int2 = rand.nextInt(1000);
// Print random integers
System.out.println("Random Integers: "+rand_int1);
System.out.println("Random Integers: "+rand_int2);
// Generate Random doubles
double rand_dub1 = rand.nextDouble();
double rand_dub2 = rand.nextDouble();
// Print random doubles
System.out.println("Random Doubles: "+rand_dub1);
System.out.println("Random Doubles: "+rand_dub2);
}
}