Search Logic Blocks

Friday, October 23, 2020

Java: Packages and Its Uses

We already have discussed about what is the package? And how to import the packages into the classes out from the package. We have also learnt about the access modifiers and their scopes of visibility in the package itself and outside from the package. Let's revise few points and go deeper into to learn more about the packages.

Why packages are so important?
Packages are actually directories in which the classes are stored. So, the packages provide structure and organize all the related classes, interfaces and other components. Packages give the programmers to have flexibility to have the same names as other programmers and provide the way to reuse other programmers' and built-in Java APIs. Packages are one important part of Java's feature encapsulation. So packages are, essentially the containers of related classes and interfaces.

How the package can be used by other packages?
Let's see the same example in the earlier post about package. Here is the package named as cards and there are four classes in the package cards - spade, club, diamond, and heart

Here in the following example, I use directly the package name and classes's names to access the class constructors.
// Class spade in package logicblocks.cards
package logicblocks.cards;

public class spade {
public spade() {
System.out.println("Spade card created");
}
}
// Class heart in package logicblocks.cards
package logicblocks.cards;

public class heart {
public heart() {
System.out.println("Heart card created");
}
}
// Class club in package logicblocks.cards
package logicblocks.cards;

public class club {
public club() {
System.out.println("Club card created");
}
}
// Class diamond in package logicblocks.cards
package logicblocks.cards;

public class diamond {
public diamond() {
System.out.println("Diamond card created");
}
}
// Class cardsdemo in package logicblocks outside from package cards
package logicblocks;

public class cardsdemo {
public static void main(String args[]) {
// Classes in the package cards are accessed directly using pacakge path, name and class names
logicblocks.cards.spade sp = new logicblocks.cards.spade();
logicblocks.cards.heart hr = new logicblocks.cards.heart();
logicblocks.cards.club cl = new logicblocks.cards.club();
logicblocks.cards.diamond dm = new logicblocks.cards.diamond();
}
}
To avoid the typing repeatedly or redundantly, the package can be imported in the start of the program itself like in below example. It saves repeated code, avoiding writing wrong names and also makes more convenient for the programmers. The individual classes can be imported by using the individual class names after the package name.
// Class cardsdemo in package logicblocks outside from package cards
package logicblocks;

// Individual classes in the package cards are imported using pacakge path and name
import logicblocks.cards.spade;
import logicblocks.cards.heart;
import logicblocks.cards.club;
import logicblocks.cards.diamond;

public class cardsdemo {
public static void main(String args[]) {
spade sp = new spade();
heart hr = new heart();
club cl = new club();
diamond dm = new diamond();
}
}
Or all the classes can be imported in one import statement by using * after the package name.
// Class cardsdemo in package logicblocks outside from package cards
package logicblocks;

// All the classes in the package cards are imported using pacakge path and name
// * means all the classes and interfaces in the package cards can be accessed through the program
import logicblocks.cards.*;

public class cardsdemo {
public static void main(String args[]) {
spade sp = new spade();
heart hr = new heart();
club cl = new club();
diamond dm = new diamond();
}
}
Java's Standard Packages
Java's built-in API (Application Program Interface) or class library is contained in the packages. There are a large number of standard classes that are available to all the programs. The package java is at the top of the packages hierarchy. There are few packages which are used commonly, as I have mentioned in my earlier post about the package -

Package NameDescription
java.langProvides classes that are fundamental to the design of the Java programming language.
java.ioProvides for system input and output through data streams, serialization and the file system.
java.netProvides the classes for implementing networking applications.
java.appletProvides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
java.awtContains all of the classes for creating user interfaces and for painting graphics and images.
java.utilContains the collections framework, some internationalization support classes, a service loader, properties, random number generation, string parsing and scanning classes, base64 encoding and decoding, a bit array, and several miscellaneous utility classes.
java.timeThe main API for dates, times, instants, and durations.
java.textProvides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages.
java.mathProvides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).

Tuesday, October 20, 2020

Java: Access Modifiers

We already discuss about the classes and objects, and packages. We already have discussed also about all three access modifiers (public, private and protected) and their scopes in the classes and packages. Let's revise all the access modifiers and default modifier (means when there is no modifier specified) in the table below:


Visibility InDefaultPublicProtectedPrivate
Same ClassYesYesYesYes
Same Package SubclassYesYesYesNo
Same package non-subclassYesYesYesNo
Different Package SubclassNoYesYesNo
Different Package non-subclassNoYesNoNo

Java: final keyword

We have already seen usage of the final keyword in the post related to constants. When the final keyword is used with the variables, the variable value can not be changed.
final double pi = 3.14;
In same way, when the final keyword is used with any method, the method becomes final means the method can not be overridden in subclasses.
final int sum(int a, int b) {
return a+b;
}
And if the final keyword is used with a class, that class can not be inherited or subclassed. Abstract class can not be a final class as abstract class as the object of the abstract class can not be instantiated. Here is the final class Square, which can not be subclassed further -
public final class Square extends Shape{
String
fillColor;
// Square Constructor with no arguments
Square() {
super();
this.fillColor = "Blue";
}

// Square Constructor with one argument
Square(String fillColor) {
super();
this.fillColor = fillColor;
}

// Square Constructor with two arguments
Square(double width, String fillColor) {
super(width, width);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Square";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((width * width) * 100) / 100.0;
}

public void setColor(String color) {
super.setColor(color);
this.fillColor = color;
}

public void setDiffColor(String fillcolor, String bordercolor) {
this.fillColor = fillcolor;
super.setColor(bordercolor);
}
}
So, the final keyword prevents the variables values to be changed, prevents methods from being overridden and also prevents a class from being inherited.

Monday, October 19, 2020

Java: Let's Practice - How to create Fibonacci sequence through recursion

What is the Fibonacci sequence?
Fibonacci sequence is a sequence of numbers generating new number by adding two previous numbers. It starts with 0 and 1.

SequenceLast two nos.
0
1
10+1
21+1
31+2
52+3

0, 1, 1, 2, 3, 5, 8, 13.......

So, to create recursive method to get next number in the sequence, program should use the same method which calculates the previous numbers of the sequence -

fib(0) = 0
fib(1) = 1
fib(2) = fib(1) + fib(0)
fib(3) = fib(2) + fib(1)
........
fib(n) = fib(n-1) + fib(n-2)

Here is the code -
import java.util.Scanner;

public class FibonacciDemo {
static int[] fibnos;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
fibnos = new int[n+1];
int fib = fibonacci(n);
System.out.println(n + "th number in the Fibonacci Sequence (0, 1, 2, ...) is : " + fib);

for(int i = 0; i < fibnos.length; i++) {
System.out.print(fibnos[i] + ", ");
}
}

public static int fibonacci(int n) {
int result = 0;

if(n == 0) {
fibnos[0] = 0;
return 0;
}
if(n == 1) {
fibnos[1] = 1;
return 1;
}
result = fibonacci(n-1) + fibonacci(n-2);
fibnos[n] = result;
return result;
}
}
And here is the output -

Enter the number: 6
6th number in the Fibonacci Sequence (0, 1, 2, ...) is : 8
0, 1, 1, 2, 3, 5, 8, 

And here is the explanation -

The program asks user to enter any number n. It passes the number to calculate the nth number of the sequence. The method calculates the next number recursively and returns the result back. The numbers are added into an array to display the sequence.

Code can be found on the Github.

Sunday, October 11, 2020

Java: Let's Practice - How to calculate factorial through recursion

I have already explained about recursion in earlier post and shown the example Reverse the string. In this post, we will use recursion method to calculate the factorial of a number.

What is factorial of a number?
Factorial of a number is the product of all numbers counting backwards from the given number till number 1. Suppose number is 5, so factorial of number 5 is equal to 5 * 4 * 3 * 2 * 1

f(5) = 5 * 4 * 3 * 2 * 1
f(4) = 4 * 3 * 2 * 1
f(3) = 3 * 2 * 1

We can notice the pattern to calculate the factorial.

f(n) = n * f(n-1)

We will use this pattern for recursion. The program will call the same method recursively till the number is 1 and then it will calculate the backwards and return the result.

Here is the program -
import java.util.Scanner;

public class FactorialDemo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
int fact = factorial(n);
System.out.println("Factorial of the number " + n + " is: " + fact);
}

public static int factorial(int n) {
int result = n;
if(n != 1)
result = result * factorial(n-1);
return result;
}

}
Here is the output - 

Enter the number: 5
Factorial of the number 5 is: 120

The program asks user to enter any number. It passes the number to a method factorial() which calculates the factorial of the number. 
  • The method factorial() method calls itself recursively by decreasing the number by 1 till the number is 1. It returns 1 when the number is 1. 
  • Then it multiplies by 2 and then returns result back to the calling method. 
  • Multiplies by 3 and then returns result back to the calling method.
  • And so on till it reaches the original number
  • When it reaches the original number, multiplies and it returns the final result back to main method.
Code can be found here on Github.