Wednesday, September 29, 2021

Oracle Certified Java Associate (OCA) Exam Preparation

Oracle Certified Java Associate (OCA) Exam Preparation, OCA Certification, OCA Preparation, OCA Guides, Oracle Java Tutorial and Materials, Oracle Java Certified

Friends! I recently appeared for OCA exam and scored 95%. Here i am sharing few techniques and exam question patterns which must be helping you while appearing for OCA test. This exam guarantee to ask question on the below topics or we can say statements.

Exam code: 1Z0-808

1. Must practice the differences between str1 == str2 and str1.equals(str2).

Example-1.1:

class Test {

public static void main(String[] args)

{

String s = new String("hello");

String s2 = "hello";

if (s == s2) {

System.out.println("==");

}

if (s.equals(s2)) {

System.out.println("equals");

}

}

}

Output:

equals

Reason: Because String class equals method compare objects, but == operator only compares references. If both the references are pointing to the same object then only == operator returns true.

Example-1.2:

class Test {
public static void main(String[] args)
{
String s = new String("hello");
String s2 = s;

if (s == s2) {
System.out.println("==");
}

if (s.equals(s2)) {
System.out.println("equals");
}
}
}

Output:

==
equals

Reason: Because both the references are pointing to the same object so “==” printed and If both the reference are pointing to the same object so by default they the equal so “equals” printed.

2. Study ternary operator and its compile time errors.


Example-2.1:

class Test {
public static void main(String[] args)
{
int marks = 90;
String result = marks > 35 ? "Pass" : "Fail";
System.out.println(result);
}
}

Output:

Pass

Example-2.2:

class Test {
public static void main(String[] args)
{
int marks = 90;
String result = marks > 60 ? "Pass with 1st div."
: marks < 50 ? "Pass with 2nd div." :
marks < 40 ? "Pass with 3nd div.";
System.out.println(result);
}
}

OUTPUT: Compile Time Error
Reason: marks < 40 ? "Pass with 3nd div." is not completed.
Correction: marks < 40 ? "Pass with 3nd div.":”Fail” .

3. Study the rule “String objects are Immutable” .


Example-3.1:

class Test {
public static void main(String[] args)
{
String ta = "A ";
ta = ta.concat("B ");
String tb = "C ";
ta = ta.concat(tb);
ta.replace('C', 'D');
ta = ta.concat(tb);
System.out.println(ta);
}
}

Output:

A B C C

4. Lambda expression and its simplified forms.


Java Lambda Expression Syntax:
(argument-list) -> {body}

4.1 Lambda Expression Example: No Parameter

// This a java method
void printHello()
{
System.out.println("Hello World");
}

Or

// As lambda the above method can be written as below
() -> { System.out.println("Hello World"); };

Or

// {} is optional for single line statement
() -> System.out.println("Hello World");

4.2 Lambda Expression Example: Single Parameter

// This a java method
void sayHello(String name)
{
System.out.println("Hello " + name);
}

Or

(name) -> { System.out.println("Hello " + name); };

Or

// {} optional
(name) -> System.out.println("Hello " + name);

Or
// () optional for single input parameter.
name -> System.out.println("Hello " + name);

4.3 Lambda Expression Example:Multiple Parameter

// This a java method
int add(int num1, int num2)
{
return num1 + num2;
}

Or

(int num1, int num2) -> {return num1 + num2; };

Or

(int num1, int num2) -> num1 + num2;

Or

// () mandatory for more than one input parameter.
(num1, num2) -> num1 + num2;

5. Study the difference between &(Bitwise AND) and &&(Logical AND) Operator.


Example-5.1:

class Test {
public static void main(String[] args)
{
int a = 10;
int b = 20;

if (++a <= 10 && --b < 20) {}
System.out.println("Output of && operator: "
+ "a = " + a + " b = " + b);
System.out.println("-------------");

a = 10;
b = 20;
if (++a <= 10 & --b < 20) {}
System.out.println("Output of & operator: "
+ "a = " + a + " b = " + b);
}
}

Output:

Output of && operator: a = 11 b = 20
-------------
Output of & operator: a = 11 b = 19

Reason: Because ‘&&’ operator doesn’t check second operand if value for the first operand is ‘false’. But ‘&’ must check both the operands.

Note: These concept definitely covers 10 – 12 questions in OCA Exam.

Source: geeksforgeeks.org

Monday, September 27, 2021

Java – Lambda Expressions Parameters

Java – Lambda Expressions Parameters, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Java Guides

Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface.

Lambda expressions implement only one abstract function and therefore implement functional interfaces. Predicate interface is an example of a functional interface that has only one abstract method called test().

Illustration:

interface Predicate

{

    ......

    abstract boolean test(T t)

}

The above is a functional interface that has one abstract method test receiving only one parameter of type T and returns a boolean value. This method is a generic method that takes a type parameter. This interface can be implemented anywhere in a program using a lambda expression instead of creating classes with multiple functions. For eg, to implement a runnable interface used only for multithreading one needs to implement only a run() method. Then there is the comparable interface which can be implemented using compare() method.

Important points:

Java – Lambda Expressions Parameters, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Java Guides

◉ The body of a lambda expression can contain zero, one, or more statements.

◉ When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

◉ When there is more than one statement, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

These are for single–line lambda expressions having void return type.

Type 1: No Parameter.

Syntax:

() -> System.out.println("Hello");
It takes interface of the following form:

interface Test1
{
    void print()
}

Type 2: Single Parameter.

Syntax:

(p) -> System.out.println(p);

It is not mandatory to use parentheses if the type of that variable can be inferred from the context

It takes interface of the following form:

interface Test2
{
    void print(Integer p)
}

The type and return type of the lamdas are automatically inferred.

Type 3: Multi parameters

(p1, p2) -> System.out.println(p1 + " " + p2);

It is not mandatory to use parentheses if the type of that variable can be inferred from the context

It takes interface of the following form:

interface Test3
{
    void print(Integer p1, Integer p2)
}

The type and return type of the lamdas are automatically inferred.

Now, we are done with discussing out the theoretical concept, now let us come up with the implementation part. So here primarily we will be discussing out the codes for the above three types as discussed above:

Note: forEach() method is of Iterable interface that is used to iterate through a collection. Here it takes an argument of Consumer type interface. This is a functional interface having only one abstract method called accept(). Since it is a functional interface, a lambda expression can be passed.

Hence, if we do conclude out the above 

Example 1: Lambda expression with no parameters

// Java code to illustrate lambda expression
// without parameters

// functional interface
// without parameters
interface Test1 {
void print();
}

class OJC {
// functional interface parameter is passed
static void fun(Test1 t) { t.print(); }
public static void main(String[] args)
{
// lambda expression is passed
// without parameter to functional interface t
fun(() -> System.out.println("Hello"));
}
}

Output

Hello

Example 2: Type 2 Lambda expression with a single parameter

// Java code to illustrate lambda expression
// with single parameter

// functional interface
// with one parameter of Integer type
interface Test2 {
// The void type and the Integer type
// is automatically inferred from here
// and assigned to the lambda expression
void print(Integer p);
}

class OJC {
// takes lambda expression and a variable of
// Integer type as arguments
static void fun(Test2 t, Integer p)
{
// calls the print function
t.print(p);
}
public static void main(String[] args)
{
// lambda expression is passed
// with a single parameter
// lambda expression is mapped to the
// single argument abstract function in the
// functional interface Test2
fun(p -> System.out.println(p), 10);
}
}

Output

10

Example 3: Type 3 Lambda expression with multi parameters

// Java code to illustrate lambda expression
// with multi parameters

// functional interface Test3
// with 2 parameter of Integer type
interface Test3 {
// The void type and the Integer type
// is automatically inferred from here
// and assigned to the lambda expression
void print(Integer p1, Integer p2);
}

class OJC {
// takes parameter of Test3 type followed
// by 2 integer parameters p1 and p2
static void fun(Test3 t, Integer p1, Integer p2)
{
// calls the print function
t.print(p1, p2);
}
public static void main(String[] args)
{
// lambda expression is passed
// with two parameters
// lambda expression is mapped to the
// double argument abstract function in the
// functional interface Test3
fun((p1, p2)
-> System.out.println(p1 + " " + p2),
10, 20);
}
}

Output

10 20

Source: geeksforgeeks.org

Friday, September 24, 2021

How to Use Regular Expression as a Substitute of endsWith() Method in Java?

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Guides, Core Java, Java Learning

So primarily discuss what is endsWith() method is, so it is a method of String class that checks whether the string ends with a specified suffix. This method returns a boolean value true or false.

Syntax:

public boolean endsWith(String suff)      

Parameter: specified suffix part  

Return: Boolean value, here in java we only have true and false.

Methods:

We can use Regular Expression / Matches as a substitute for startWith() method in Java

1. Using Regular Expression

2. Using Matches 

Method 1: Using Regular Expression

Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package primarily consists of the following three classes as depicted below in tabular format as follows:

◉ Pattern

◉ Matcher

◉ PatternSyntaxException

Example

// Java Program to Illustrate use of Regular Expression

// as substitute of endsWith() method

// Importing required classes

import java.util.regex.Matcher;

import java.util.regex.Pattern;

// Main class

public class Java {

// Main driver method

public static void main(String args[])

{

// Declaring and initialising string

String Str = new String("Welcome to oraclejavacertified");

// Display message

System.out.print(

"Check whether string ends with Welcome using endsWith : ");

// Using endWith() method

System.out.println(Str.endsWith("Java"));

// Creating Pattern and matcher classes object

Pattern pattern = Pattern.compile(".*Java");

Matcher m = pattern.matcher(Str);

// Checking whether string ends with specific word

// or nor and returning the boolean value

// using ? operator and find() method

System.out.print(

"Check whether string ends with Welcome using Regex: ");

System.out.println(m.find() ? "true" : "false");

}

}

Output

Check whether string ends with Welcome using endsWith : true
Check whether string ends with Welcome using Regex: true

Method 2: Using Matches

String.matches() method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).

Syntax:

public boolean matches(String regex);

Parameters: The regular expression to which this string is to be matched.

Return Value: This method returns true if, and only if, this string matches the given regular expression.

Example

// Java Program to Illustrate use of Matches
// as substitute of endsWith() method

// Importing all utility classes
import java.util.*;

// Main class
public class Java {

// Main driver method
public static void main(String args[])
{

// Initialising String
String Str = new String("Welcome to oraclejavacertified");

// Display message for better readibility
System.out.print(
"Check whether string starts with Welcome using endsWith : ");
// Using endsWith() to end with specific word
System.out.println(Str.endsWith("Java"));

// Display message for better readibility
System.out.print(
"Check whether string starts with Welcome using Matches: ");
// Now checking whether it matches with
// above defined specific word
System.out.println(Str.matches("(.*)Java"));
}
}

Output

Check whether string starts with Welcome using endsWith : true
Check whether string starts with Welcome using Matches: true

Source: geeksforgeeks.org

Wednesday, September 22, 2021

7 Best Games Written in Java

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Guides, Oracle Java Career

Among one of the most popular and well-known programming languages of the 21st century, Java is a household name.

Created in 1995, the programming language prides itself on the mantra write once, run anywhere (WORA), making it incredibly useful in a world awash with different devices each running on differing architectures.

Read More: 1Z0-900: Java EE 7 Application Developer

While we’re all used to Java applications—from Spotify servers to the Android operating system—Java has also been used for creating a variety of games since its creation. Let’s run down some of our favourites.

1. Wakfu

As a colourful, tactical turn-based MMORPG, Wakfu is quite a unique gem. Crafted by Ankama Games for Windows, Mac and Linux, players take control of one of 16 classes as they explore a variety of dungeons.

Beyond turn-based combat, the game also includes some quite unique political features, allowing players to elect a player-Governor of each of the four nations every two weeks.

Beloved by many, the world of Wakfu was also turned into an animated series by Ankama Animations, released in France to great fanfare. It is currently in its third season.

2. Worms: A Space Oddity

Adapting the classic Worms turn-based formula to the Nintendo Wii, developer Team17 opted to employ Java.

While the game’s DNA remained much unchanged in this instalment of the franchise, the game mobilised the Wii’s, then, unique gesture controls allowing players to launch attacks in ways they never had done so before.

While the Worms franchise had previously utilised Java one more time for the mobile game Worms Golf, they quickly moved away from Java in the following instalments of the series.

3. Saints Row 2 (Mobile)

Back in the late 2000s, Saints Row was a formidable franchise which took on Grand Theft Auto while turning absurd wit up to eleven.

Alongside THQ’s console game, the company commissioned G5 Entertainment to create a mobile version of the game which was released in 2008.

Following the story of the series, players were given the opportunity to fight and expand gang territory, just like in the full game. Although this version employed an isometric top-down look, highlighting minigames over the open-world shenanigans of the full console game.

Being created for mobile, it’s no surprise that G5 Entertainment chose Java, as thanks to its write once, run anywhere philosophy, Java was among the best bet for mobile developers at the time.

4. SimCity

Created in 1989 SimCity was… not initially built on Java. Seeing as it outdates the programming language itself.

However, Will Wright’s legendary game, produced with Maxis, has lived a life far beyond its years.

After the original release on the Amiga and Macintosh, followed by the Commodore 64 and IBM PC systems, SimCity was continually ported from system to system so that players in the early 90s could experience its wonders.

As the game’s popularity continued throughout the 2000s, the game was eventually open-sourced. Alongside this release, Maxis created a browser-based version of SimCity using JavaScript and HTML5, naming it micropolisJS.

This version was released in 2013 and is still playable today.

5. Spiral Knights

Created by Three Rings Design, Spiral Knights released in 2011 onto a bustling marketplace. However, it set itself apart from other massively multiplayer online titles by being totally free to play which, at the time, was a rarity amongst MMOs.

In the game, players control a knight of the spiral order. After crash-landing on a mysterious planet, Knights cooperatively battle monsters throughout dungeons in order to progress the story and, of course, get their hands on that glorious loot.

Just over a year after its release this hack and slash had amassed three million accounts, marking it as one of the most popular games in the history of Java gaming.

6. RuneScape

Created by Jagex—standing for Java Gaming Experts—RuneScape is, of course, one of the most famous examples of a game created in Java.

Initially launched in 2001 and quickly becoming a defining game of 2000s gaming, RuneScape immersed players in the world of Gielinor, a medieval fantasy realm divided into different kingdoms.

Giving players the opportunity to customise their avatar—both cosmetically and in terms of stats—RuneScape quickly became a foundational MMORPG known for its combat, PvP and iconic gameplay.

While Jagex slowly migrated away from Java in order to produce the more recently released RuneScape 3, they rolled back the clock releasing Old School RuneScape.

If you’re a fan of OSRS or RuneScape 3, head over to Eldorado.gg to get ahead. There you can get your hands on plenty of OSRS gp or even some boosting and a fresh account. Whatever you need to get ahead, Eldorado has it.

7. Minecraft

While there are some well known games on this list, there is no game as well-known as Minecraft—meaning that the most popular game in the world is a Java game… Sort of.

While Minecraft was originally written in Java by Markus Persson and Jens Bergensten, the game was later recreated outside of Java as the game grew exponentially. With versions such as Minecraft Pocket Edition being written in C++, while the original release came to be known as Minecraft: Java Edition.

Minecraft, of course, needs no introduction. It is the most defining game of the 21st century so far. Meaning that, whether you know it or not, if you played Minecraft in the first few years after release, you will have played the most successful Java game ever made.

Despite its fantastic use cases and widespread general use, Java remains somewhat obscure in game development today. While there are many reasons for this, from popular game engines using other programming languages to many larger studios preferring more purpose-built programming languages, that does not mean it has not left its mark on gaming. And, who knows, the next big game may just be written in Java.

Source: javacodegeeks.com

Monday, September 20, 2021

Differences between Interface and Class in Java

Java Interface, Java Class, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Java Preparation, Java Career

This article highlights the differences between a class and an interface in Java.

Class:

A class is a user-defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 

1. Modifiers: A class can be public or has default access.

2. Class name: The name should begin with a initial letter (capitalized by convention).

3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

5. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.

Example:

// Java program to demonstrate Class

// Class Declaration

public class Dog {

// Instance Variables

String name;

String breed;

int age;

String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

{

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

}

// method 1

public String getName()

{

return name;

}

// method 2

public String getBreed()

{

return breed;

}

// method 3

public int getAge()

{

return age;

}

// method 4

public String getColor()

{

return color;

}

@Override

public String toString()

{

return ("Hi my name is "

+ this.getName()

+ ".\nMy breed, age and color are "

+ this.getBreed() + ", "

+ this.getAge() + ", "

+ this.getColor());

}

public static void main(String[] args)

{

Dog tuffy = new Dog("tuffy", "papillon",

5, "white");

System.out.println(tuffy.toString());

}

}

Output: 

Hi my name is tuffy.
My breed, age and color are papillon, 5, white


Interface: 


Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body).   
 
◉ Interfaces specify what a class must do and not how. It is the blueprint of the class.

◉ An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.

◉ If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract.

◉ A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection.

Syntax : 

interface <interface_name> {
    
    // declare constant fields
    // declare methods that abstract 
    // by default.
}

Example: 

// Java program to demonstrate
// working of interface.

import java.io.*;

// A simple interface
interface in1 {

// public, static and final
final int a = 10;

// public and abstract
void display();
}

// A class that implements the interface.
class testClass implements in1 {

// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Oracle");
}

// Driver Code
public static void main(String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}

Differences between a Class and an Interface:


Class Interface 
The keyword used to create a class is “class” The keyword used to create an interface is “interface”
A class can be instantiated i.e, objects of a class can be created.  An Interface cannot be instantiated i.e, objects cannot be created. 
Classes does not support multiple inheritance.  Interface supports multiple inheritance. 
It can be inherit another class.  It cannot inherit a class. 
It can be inherited by another class using the keyword ‘extends’.  It can be inherited by a class by using the keyword ‘implements’ and it can be inherited by an interface using the keyword ‘extends’. 
It can contain constructors.  It cannot contain constructors. 
It cannot contain abstract methods.  It contains abstract methods only. 
Variables and methods in a class can be declared using any access specifier(public, private, default, protected)  All variables and methods in a interface are declared as public. 
Variables in a class can be static, final or neither.  All variables are static and final. 

Source: geeksforgeeks.org

Friday, September 17, 2021

Java Program to Implement Binomial Heap

Binomial Heap, Oracle Java Exam Prep, Oracle Java Tutorial and Materials, Oracle Java Preparation, Oracle Java Guides, Java Learning, Java Career

A Binomial Heap is a set of Binomial Trees where each Binomial Tree follows Min Heap property. And there can be at most one Binomial Tree of any degree. It is explained to depth in the bellow illustration as follows:

Illustration:

There are 2 binomial heaps been depicted below out here saw follows: 

Read More: 1Z0-819: Oracle Java SE 11 Developer

 BINOMIAL HEAP 1

 12------------10--------------------20

            /  \                 /  | \

          15    50             70  50  40

          |                  / |    |      

          30               80  85  65  

                           |

                          100

A Binomial Heap with 13 nodes. It is a collection of 3  

Binomial Trees of orders 0, 2 and 3 from left to right.  

BINOMIAL HEAP 2 

   10--------------------20

  /  \                 /  | \

15    50             70  50  40

|                  / |    |      

30               80  85  65  

                 |

                100

A Binomial Heap with 12 nodes. It is a collection of 2  

Binomial Trees of orders 2 and 3 from left to right.  

Let us now do discuss the binary representation of a number and binomial heaps. A Binomial Heap with n nodes has the number of Binomial Trees equal to the number of set bits in the binary representation of n. 

For example, let n be 13, there are 3 set bits in the binary representation of n (00001101), hence 3 Binomial Trees. We can also relate the degree of these Binomial Trees with positions of set bits. With this relation, we can conclude that there are O(Logn) Binomial Trees in a Binomial Heap with ‘n’ nodes.  

Operations of the binomial heap are as follows:

1. Insert(K): Insert an element K into the binomial heap

2. Delete(k): Deletes the element k from the heap

3. getSize(): Returns the size of the heap

4. makeEmpty(): Makes the binomial heap empty by deleting all the elements

5. checkEmpty(): Check if the binomial heap is empty or not

6. displayHeap(): Prints the binomial heap

Implementation:

Example

// Java Program to Implement Binomial Heap

// Importing required classes

import java.io.*;

// Class 1

// BinomialHeapNode

class BinomialHeapNode {

int key, degree;

BinomialHeapNode parent;

BinomialHeapNode sibling;

BinomialHeapNode child;

// Constructor of this class

public BinomialHeapNode(int k)

{

key = k;

degree = 0;

parent = null;

sibling = null;

child = null;

}

// Method 1

// To reverse

public BinomialHeapNode reverse(BinomialHeapNode sibl)

{

BinomialHeapNode ret;

if (sibling != null)

ret = sibling.reverse(this);

else

ret = this;

sibling = sibl;

return ret;

}

// Method 2

// To find minimum node

public BinomialHeapNode findMinNode()

{

// this keyword refers to current instance itself

BinomialHeapNode x = this, y = this;

int min = x.key;

while (x != null) {

if (x.key < min) {

y = x;

min = x.key;

}

x = x.sibling;

}

return y;

}

// Method 3

// To find node with key value

public BinomialHeapNode findANodeWithKey(int value)

{

BinomialHeapNode temp = this, node = null;

while (temp != null) {

if (temp.key == value) {

node = temp;

break;

}

if (temp.child == null)

temp = temp.sibling;

else {

node = temp.child.findANodeWithKey(value);

if (node == null)

temp = temp.sibling;

else

break;

}

}

return node;

}

// Method 4

// To get the size

public int getSize()

{

return (

1 + ((child == null) ? 0 : child.getSize())

+ ((sibling == null) ? 0 : sibling.getSize()));

}

}

// Class 2

// BinomialHeap

class BinomialHeap {

// Member variables of this class

private BinomialHeapNode Nodes;

private int size;

// Constructor of this class

public BinomialHeap()

{

Nodes = null;

size = 0;

}

// Checking if heap is empty

public boolean isEmpty() { return Nodes == null; }

// Method 1

// To get the size

public int getSize() { return size; }

// Method 2

// Clear heap

public void makeEmpty()

{

Nodes = null;

size = 0;

}

// Method 3

// To insert

public void insert(int value)

{

if (value > 0) {

BinomialHeapNode temp

= new BinomialHeapNode(value);

if (Nodes == null) {

Nodes = temp;

size = 1;

}

else {

unionNodes(temp);

size++;

}

}

}

// Method 4

// To unite two binomial heaps

private void merge(BinomialHeapNode binHeap)

{

BinomialHeapNode temp1 = Nodes, temp2 = binHeap;

while ((temp1 != null) && (temp2 != null)) {

if (temp1.degree == temp2.degree) {

BinomialHeapNode tmp = temp2;

temp2 = temp2.sibling;

tmp.sibling = temp1.sibling;

temp1.sibling = tmp;

temp1 = tmp.sibling;

}

else {

if (temp1.degree < temp2.degree) {

if ((temp1.sibling == null)

|| (temp1.sibling.degree

> temp2.degree)) {

BinomialHeapNode tmp = temp2;

temp2 = temp2.sibling;

tmp.sibling = temp1.sibling;

temp1.sibling = tmp;

temp1 = tmp.sibling;

}

else {

temp1 = temp1.sibling;

}

}

else {

BinomialHeapNode tmp = temp1;

temp1 = temp2;

temp2 = temp2.sibling;

temp1.sibling = tmp;

if (tmp == Nodes) {

Nodes = temp1;

}

else {

}

}

}

}

if (temp1 == null) {

temp1 = Nodes;

while (temp1.sibling != null) {

temp1 = temp1.sibling;

}

temp1.sibling = temp2;

}

else {

}

}

// Method 5

// For union of nodes

private void unionNodes(BinomialHeapNode binHeap)

{

merge(binHeap);

BinomialHeapNode prevTemp = null, temp = Nodes,

nextTemp = Nodes.sibling;

while (nextTemp != null) {

if ((temp.degree != nextTemp.degree)

|| ((nextTemp.sibling != null)

&& (nextTemp.sibling.degree

== temp.degree))) {

prevTemp = temp;

temp = nextTemp;

}

else {

if (temp.key <= nextTemp.key) {

temp.sibling = nextTemp.sibling;

nextTemp.parent = temp;

nextTemp.sibling = temp.child;

temp.child = nextTemp;

temp.degree++;

}

else {

if (prevTemp == null) {

Nodes = nextTemp;

}

else {

prevTemp.sibling = nextTemp;

}

temp.parent = nextTemp;

temp.sibling = nextTemp.child;

nextTemp.child = temp;

nextTemp.degree++;

temp = nextTemp;

}

}

nextTemp = temp.sibling;

}

}

// Method 6

// To return minimum key

public int findMinimum()

{

return Nodes.findMinNode().key;

}

// Method 7

// To delete a particular element */

public void delete(int value)

{

if ((Nodes != null)

&& (Nodes.findANodeWithKey(value) != null)) {

decreaseKeyValue(value, findMinimum() - 1);

extractMin();

}

}

// Method 8

// To decrease key with a given value */

public void decreaseKeyValue(int old_value,

int new_value)

{

BinomialHeapNode temp

= Nodes.findANodeWithKey(old_value);

if (temp == null)

return;

temp.key = new_value;

BinomialHeapNode tempParent = temp.parent;

while ((tempParent != null)

&& (temp.key < tempParent.key)) {

int z = temp.key;

temp.key = tempParent.key;

tempParent.key = z;

temp = tempParent;

tempParent = tempParent.parent;

}

}

// Method 9

// To extract the node with the minimum key

public int extractMin()

{

if (Nodes == null)

return -1;

BinomialHeapNode temp = Nodes, prevTemp = null;

BinomialHeapNode minNode = Nodes.findMinNode();

while (temp.key != minNode.key) {

prevTemp = temp;

temp = temp.sibling;

}

if (prevTemp == null) {

Nodes = temp.sibling;

}

else {

prevTemp.sibling = temp.sibling;

}

temp = temp.child;

BinomialHeapNode fakeNode = temp;

while (temp != null) {

temp.parent = null;

temp = temp.sibling;

}

if ((Nodes == null) && (fakeNode == null)) {

size = 0;

}

else {

if ((Nodes == null) && (fakeNode != null)) {

Nodes = fakeNode.reverse(null);

size = Nodes.getSize();

}

else {

if ((Nodes != null) && (fakeNode == null)) {

size = Nodes.getSize();

}

else {

unionNodes(fakeNode.reverse(null));

size = Nodes.getSize();

}

}

}

return minNode.key;

}

// Method 10

// To display heap

public void displayHeap()

{

System.out.print("\nHeap : ");

displayHeap(Nodes);

System.out.println("\n");

}

private void displayHeap(BinomialHeapNode r)

{

if (r != null) {

displayHeap(r.child);

System.out.print(r.key + " ");

displayHeap(r.sibling);

}

}

}

// Class 3

// Main class

public class OJC {

public static void main(String[] args)

{

// Make object of BinomialHeap

BinomialHeap binHeap = new BinomialHeap();

// Inserting in the binomial heap

// Custom input integer values

binHeap.insert(12);

binHeap.insert(8);

binHeap.insert(5);

binHeap.insert(15);

binHeap.insert(7);

binHeap.insert(2);

binHeap.insert(9);

// Size of binomial heap

System.out.println("Size of the binomial heap is "

+ binHeap.getSize());

// Displaying the binomial heap

binHeap.displayHeap();

// Deletion in binomial heap

binHeap.delete(15);

binHeap.delete(8);

// Size of binomial heap

System.out.println("Size of the binomial heap is "

+ binHeap.getSize());

// Displaying the binomial heap

binHeap.displayHeap();

// Making the heap empty

binHeap.makeEmpty();

// checking if heap is empty

System.out.println(binHeap.isEmpty());

}

}

Output


Size of the binomial heap is 7

Heap : 9 7 2 12 8 15 5 

Size of the binomial heap is 5

Heap : 7 9 5 12 2 

true

Source: geeksforgeeks.com

Wednesday, September 15, 2021

Convert Stream to Set in Java

Convert Stream to Set in Java, Core Java, Oracle Java, Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Preparation, Java Career

Below given are some methods which can be used to convert Stream to Set in Java.

Method 1: Using Collectors

Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set.

Read More: 1Z0-808: Java SE 8 Programmer I

Stream.collect() method can be used to collect elements of a stream in a container. The Collector which is returned by Collectors.toSet() can be passed that accumulates the elements of stream into a new Set.

// Java code for converting

// Stream to Set using Collectors

import java.util.*;

import java.util.stream.Stream;

import java.util.stream.Collectors;

class OJC {

// Driver code

public static void main(String[] args) {

// Creating a Stream of Integers

Stream<Integer> stream = Stream.of(-2, -1, 0, 1, 2);

// Using Stream.collect() to collect the

// elements of stream in a container.

Set<Integer> streamSet = stream.collect(Collectors.toSet());

// Displaying the elements

streamSet.forEach(num -> System.out.println(num));

}

}

Output:

-1
0
-2
1
2

Method 2 : Converting Stream to Array and then to Set


The problem of converting Stream into Set can be divided into two parts :

1) Convert Stream to an Array
2) Convert Array to a Set

// Java code for converting
// Stream to Set using Divide
// and Conquer
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;

class OJC {
// Driver code
public static void main(String[] args) {
// Creating a Stream of Strings
Stream<String> stream = Stream.of("G", "E", "K", "S");
// Converting Stream into an Array
String[] arr = stream.toArray(String[] :: new);
// Creating a HashSet
Set<String> set = new HashSet<>();
// Converting Array to set
Collections.addAll(set,arr);
// Displaying the elements
set.forEach(str -> System.out.println(str));
}
}

Output:

S
E
G
K

Note : Output is random because HashSet takes input in random order as generated hash value.

Method 3 : Using forEach


Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.add() to add each elements into an empty set.

// Java code for converting
// Stream to Set using forEach
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;

class OJC {
// Driver code
public static void main(String[] args) {
// Creating a Stream of Integers
Stream<Integer> stream = Stream.of(5, 10, 15, 20, 25);

// Creating a HashSet
Set<Integer> set = new HashSet<>();
// using set.add() to add elements
// of stream into empty set
stream.forEach(set::add);
// Displaying the elements
set.forEach(num -> System.out.println(num));
}
}

Output:

20
5
25
10
15

Source: geeksforgeeks.org

Monday, September 13, 2021

Convert String or String Array to HashMap In Java

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Guides, Oracle Java Learning, Core Java, Oracle Java Career

Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object.

In order to convert strings to HashMap, the process is divided into two parts:

◉ The input string is converted to an array of strings as output.

◉ Input as an array of strings is converted to HashMap.

Input string elements as follows:

Input : "Aashish:1, Bina:2, Chintu:3"

Approach : 

Phase 1: The input string is converted to an array of strings as output.

Phase 2: Input as an array of strings is converted to HashMap.

Phase 1:

◉ First, we split the String by a comma and store it in an array parts. After the split we have the following content:

"Aashish:1","Bina:2", "Chintu:3"

◉ And then iterate on parts and split the student data to get the student name and roll number. And set roll no as key and the name as the value of the HashMap.

Phase 2:

We can also convert an array of String to a HashMap. Suppose we have a string array of the student name and an array of roll numbers, and we want to convert it to HashMap so the roll number becomes the key of the HashMap and the name becomes the value of the HashMap.

Note: Both the arrays should be the same size.

Input array of string elements as follows which will be output in phase 1

String stuName[] = {"Aashish","Bina","Chintu"}

Integer stuRollNo[] = {1,2,3}

Approach : 

◉ Iterate over the array and set the roll number as key and the name as values in the HashMap.

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Guides, Oracle Java Learning, Core Java, Oracle Java Career
Phase 1 – String to Array of string

// Convert String or String array to HashMap In Java

// Phase 1: Input- String converted to ArrayofStrings

// Importing java generic libraries

import java.util.*;

class OJC {

// Main driver method

public static void main(String[] args)

{

// String object that contains the student name and

// roll number separated by a comma

String student = "Aashish:1, Bina:2, Chintu:3";

// New HashMap obj

Map<String, String> hashMap

= new HashMap<String, String>();

// split the String by a comma

String parts[] = student.split(",");

// iterate the parts and add them to a HashMap

for (String part : parts) {

// split the student data by colon to get the

// name and roll number

String stuData[] = part.split(":");

String stuRollNo = stuData[0].trim();

String stuName = stuData[1].trim();

// Add to map

hashMap.put(stuRollNo, stuName);

}

// Print hashMap

System.out.println("String to HashMap: " + hashMap);

}

}

Output

String to HashMap: {Chintu=3, Bina=2, Aashish=1}

Phase 2 – String to Array to HashMap

// Convert String or String array to HashMap In Java

// Phase 2: Input- Array of strings converted to HashMap.

// Importing java generic libraries
import java.util.*;

class OJC {

// Main driver method
public static void main(String[] args)
{
// String array that contains the student name
String stuName[] = { "Aashish", "Bina", "Chintu" };

// Integer array that contains roll number of the
// students
Integer stuRollNo[] = { 1, 2, 3 };

// New HashMap obj
Map<Integer, String> hashMap
= new HashMap<Integer, String>();

// Iterating over array of strings
for (int i = 0; i < stuName.length; i++) {

// And set roll no as key and the name as value
hashMap.put(stuRollNo[i], stuName[i]);
}

// Printing HashMap
System.out.println("String to hashmap: " + hashMap);
}
}

Output

String to hashmap: {1=Aashish, 2=Bina, 3=Chintu}

Source: geeksforgeeks.org

Friday, September 10, 2021

Why Constructors are not inherited in Java?

Core Java Tutorial and Material, Oracle Java Certification, Oracle Java Guides, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type.

Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super class but it does not inherit constructor of super class because of following reasons:

◉ Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. For example see the below code:

class Parent {

public Parent()

{

}

public void print()

{

}

}

public class Child extends Parent {

public Parent()

{

}

public void print()

{

}

public static void main(String[] args)

{

Child c1 = new Child(); // allowed

Child c2 = new Parent(); // not allowed

}

}

If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method. But for print method it does not give any compile time error and consider it a overriding method.

◉ Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class.

◉ A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();

◉ A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.

Source: geeksforgeeks.org

Wednesday, September 8, 2021

Getter and Setter in Java

Oracle Java Exam Prep, Oracle Java Preparation, Core Java, Oracle Java Guides, Oracle Java Certification

Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the convenience of the program, getter starts with the word “get” followed by the variable name.

While Setter sets or updates the value (mutators). It sets the value for any variable which is used in the programs of a class. and starts with the word “set” followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital.

Example 1

// Java Program to Illustrate Getter and Setter

// Importing input output classes

import java.io.*;

// Class 1

// Helper class

class GetSet {

// Member variable of this class

private String name;

// Method 1 - Getter

public String getName() { return name; }

// Method 2 - Setter

public void setName(String N)

{

// This keyword refers to current instance itself

this.name = N;

}

}

// Class 2

// Main class

class OJC {

// Main driver method

public static void main(String[] args)

{

// Creating an object of class 1 in main() method

GetSet obj = new GetSet();

// Setting the name by calling setter method

obj.setName("Oracle Java Certified");

// Getting the name by calling geter method

System.out.println(obj.getName());

}

}

Output

Oracle Java Certified

Getter and Setter give you the convenience to enter the value of the variables of any data type as per accordance with the requirement of the code. Getters and setters let you manage how crucial variables in your code are accessed and altered. It can be seen as in the program been discussed below as follows:

Example 2

// Java Program to Illustrate Getter and Setter

// Importing input output classes
import java.io.*;

class GetSet {

// Member variable of this class
private int num;

// Method 1 - Setter
public void setNumber(int number)
{

// Checking if number if between 1 to 10 exclusive
if (number < 1 || number > 10) {

throw new IllegalArgumentException();
}
number = num;
}

// Method 2 - Getter
public int getNumber() { return num; }
}

// Class 2
// MAin class
class OJC {

// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();

// Calling method 1 inside main() method
obj.setNumber(5);

// Printing the number as setted above
System.out.println(obj.getNumber());
}
}

Output

0

Output explanation:

Here we can see that if we take a value greater than 10 then it shows an error, By using the setNumber() method, one can be sure the value of a number is always between 1 and 10. This is much better than updating the number variable directly.

Note: This could be avoided by making the number a private variable and utilizing the setNumber method. Using a getter method, on the other hand, is the sole way to read a number’s value.

Source: geeksforgeeks.org