Search Logic Blocks

Sunday, June 28, 2020

Java: Char Data Type

Traditionally, in most of the computer languages char data type was used to be an unsigned 8-bit ASCII character, whose value ranges from 0 to 127. But the char data type in Java is an unsigned 16-bit character, which represents the Unicode character set and its value ranges from 0 to 65,535. ASCII values are still valid characters and are subset of Unicode characters. Unicode is a standard character set that represents all the world's languages. So, usage of Unicode character set made Java more portable.


There is one more feature of the char data type in Java, it can be treated as an integer and can have arithmetic operations on it. It is clear in the following example -

Class Test (Test.java)
public class Test {
public static void main (String args[]) {
char ch = 'A';
System.
out.println("Character is " + ch); // 'A'

ch++; // increment by 1
System.out.println("Character is " + ch); // 'B'

ch+=5; // increment by 5
System.out.println("Character is " + ch); // 'G'

ch--;
System.
out.println("Character is " + ch); // 'F'

ch-=3;
System.
out.println("Character is " + ch); // 'C'

// ch = ch + 10; doesn't convert implicitly, needs explicit type conversion

// Explicit Type Conversion
ch = (char)(ch + 10);
System.
out.println("Character is " + ch); // 'M'

ch = (char)(ch - 5);
System.
out.println("Character is " + ch); // 'H'

ch = 75;
System.
out.println("Character is " + ch); // 'K'

ch = 225;
System.
out.println("Character is " + ch); // 'á'
}
}
Output:

Character is A
Character is B
Character is G
Character is F
Character is C
Character is M
Character is H
Character is K
Character is á

When the increment operator (++) is used on the char variable ch, implicitly the character is converted to its integer unicode value and then adds it to 1. Then it again converts back to char data type implicitly.
ch++;
Same happens with other shorthand operators --, +=, -= or assigning literal value of an integer like in the following statement -
ch--;
ch+=5;
ch-=3;
ch = 75;
ch = 225;
But, when we do simple arithmetic operations, the integer value of the variable is not converted into char data type implicitly. We need to convert the int value to character value explicitly, When we convert one data type variable to another data type variable, it is called Type Casting. Here are the statements using casting from int to char data type -
ch = (char)(ch + 10);
ch = (char)(ch - 5);
In the above statements, value of character variable ch is converted to an int data type implicitly. Then addition or subtraction happens. But, the result value is an int data type and it can not be assigned directly to a char variable. So, explicit casting is done by adding word (char) to the statement. I have already used Type Casting in my earlier post How to get the character input from console.

NOTE: We will discuss Type Casting in coming posts. 

Friday, June 26, 2020

Java: Errors

When a programmer writes a program with lots of instructions, he / she may have forgotten something or written incorrect statements or some infinite loops or assigned wrong values or something else which creates serious issues in the program, those mistakes are reported as errors. There are two kind of errors - Compile Time Errors and Run Time Errors.

Compile Time Errors
These errors are reported during compilation time and also known as Syntax Errors as they are reported when there is syntactical error like uppercase / lowercase difference (Java is a case-sensitive language), missing parentheses, missing semi-colon or wrong assignment etc. These kind of errors can be spotted and rectified easily as when the program is compiled, the compiler reports the specific error and line no of error code. Here is the example of Compile Time Error -

Class Test1 (Test1.java)
public class Test1 {
public static void main (String args[]) {
int i = 10;

System.out.println("Number is " + i)<== Error (Semi-colon missing)
}
}
Error:(9, 45) java: ';' expected
Above example shows the error of missing semicolon. Error shows the coordinates (line no and column no), where the semi-colon (;) is expected by the compiler. Another example is here, when the wrong value is assigned to the variable (double value is assigned to int data type variable -

Class Test2 (Test2.java)
public class Test2 {
public static void main (String args[]) {
int i = 10.2;<== Error (Double value assigned to int data type variable)

System.out.println("Number is " + i);
}
}
Error:(7, 17) java: incompatible types: possible lossy conversion from double to int
Run Time Errors
These errors are reported during run / execution time and the program stops abruptly in the middle of program. When the program is compiled perfectly by the compiler, but at run-time when some wrong data is entered by the user (entered double value for int value) or wrong data assignment or wrong calculations (like division by 0) or going in an infinite loop (no condition to stop the loop), these errors occur and are detected by the JVM (Java Virtual Machine). These kinds of errors are also called as Exceptions and to handle these errors, the statements should be written in the Try-Catch block and act accordingly. Here is the example of Run Time Error -

Class Test3 (Test3.java)
import java.util.Scanner;

public class Test3 {
public static void main (String args[]) {
int i;

Scanner sc = new Scanner(System.in);
System.out.println("Enter Number");
i = sc.nextInt();
System.out.println("Number is " + i);
}
}
Enter Number
12.5
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at Test.main(Test.java:11)
The above example has no syntactical error, so it compiles perfectly. But when it is run, and the user enters the wrong value, the exception InputMismatchException is thrown and specifies the line no from where the exception is thrown. The programmer can put the statement on the specified line, in the Try-Catch block and whenever the exception occurs, can act accordingly without stopping the program abruptly.

Note: I will discuss Exceptions and Try-Catch block in detail sooner.

Wednesday, June 24, 2020

Java: What is Inheritance?

I have already mentioned about the parent-child relationship between different classes earlier in the last post - Polymorphism, where class Shape was the parent class, and classes Circle, Triangle and Rectangle were the child classes of the class Shape.

Inheritance is basically a hierarchical classification. A parent class is created using all the common properties and behaviors for a set of related things. In Java, the parent class is called as a superclass or base class. Then child classes inherit all the properties and behaviors from the parent class (derived from the base class), and the child classes can have their own properties and behaviors in addition. The child class is also called as a subclass.

Let's examine our classes from last post - Shape, Circle, Triangle and Rectangle. Class Shape is the parent class or superclass and it has three variables (PI, width, height) and two methods (whatShape() and area()).

Class Shape (Shape.java)
// Parent class Shape
import java.lang.Math; // imports Math package
public class Shape {
final static double PI = Math.PI;
double width = 0;
double height = 0;

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

// Returns the area of the shape
public double area() {
return 0.0;
}
}
PI is final static double variable means, the value of variable PI can not be changed and can be accessed directly without creating any instance of the class. Every shape has width and height measurements, and are used to calculate shape's area. whatShape() method tells what shape it is, and area() method calculates the area of the shape.

Classes Circle, Triangle and Rectangle are child classes or subclasses. They are declared as child classes using the key-word extends. The subclasses are inheriting all the variables from the super class, but they have their own methods with the same names as in superclass. Having same name methods as in superclass is called overriding methods and is part of Java's Polymorphism principle as I mentioned in the last post - Polymorphism.

Class Circle (Circle.java)
// Child class Circle inherits from class Shape
public class Circle extends Shape{
// Returns the text telling what shape it is
public String whatShape() {
return "Circle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
double radius = width / 2;
return Math.round(PI * radius * radius * 100) / 100.0;
}
}
Class Triangle (Triangle.java)
// Child class Triangle inherits from class Shape
public class Triangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
Class Rectangle (Rectangle.java)
// Child class Rectangle inherits from class Shape
public class Rectangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Rectangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round(height * width * 100) / 100.0;
}
}
Class ShapesTest (ShapesTest.java)
// class ShapesTest to test class Shape's overridden methods - whatShape() and area()
public class ShapesTest {
public static void main(String args[]) {
// Created an array of 3 shapes
Shape shapes[] = new Shape[3];

// Created 3 instances of 3 child classes
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Rectangle();
System.out.println("Shapes Test");

for(int i = 0; i < shapes.length; i++) {
shapes[i].height = 5;
shapes[i].width = 9;

// Called the methods through parent's reference (Compiler doesn't know which object is called)
// At run-time decision is made, which class method is called
System.out.println("Shape is " + shapes[i].whatShape());
System.out.println("Area is " + shapes[i].area());
System.out.println("");
}
}
}
Output:

Shapes Test
Shape is Circle
Area is 63.62

Shape is Triangle
Area is 22.5

Shape is Rectangle
Area is 45.0

Let's add one more method isEllipse() and modify methods whatShape() and area() in subclass Circle -

Class Circle (Circle.java)
// Child class Circle inherits from class Shape
public class Circle extends Shape{
// Checks whether the circle is an ellipse
private boolean isEllipse() {
if(width != height) return true;
else return false;
}
// Returns the text telling what shape it is
public String whatShape() {
String sh = "";
if(isEllipse()) sh = "Ellipse";
else sh = "Circle";
return sh;
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
double xradius = width / 2;
double yradius = height / 2;
return Math.round(PI * xradius * yradius * 100) / 100.0;
}
}
Output:

Shapes Test
Shape is Ellipse
Area is 35.34

Shape is Triangle
Area is 22.5

Shape is Rectangle
Area is 45.0
isEllipse() method checks whether the height and width are not same. If not, then shape is an ellipse. Accordingly, it shows shape text and calculates area. So, isEllipse() method is an additional method used only in subclass Circle. Superclass and other subclasses can not access the isEllipse() method. You can see the change in the output.

In the post Encapsulation, we discussed about access modifiers. In case of inheritance, if superclass has a variable or method with access modifier as private, the subclasses and any other classes can not access that variable or method. But if superclass has a variable or method with access modifier as protected, the subclasses and non-subclasses in the package and subclasses in other packages can access that variable or method, but non-subclasses which are not in the package, can not access the protected variable or method.

Tuesday, June 23, 2020

Java: What is Polymorphism?

Polymorphism means many forms in Latin / Greek. In java, you can use the same method name but different implementations altogether. Like same action happens, but in different ways for the different objects. The purpose of the method is same but it behaves in different ways depending on passed variables / objects (compile time decision) or method is called by which object (run-time decision). Like when we add two numbers - numbers can be integers, floats, doubles. So, methods will be written differently for all the data types. Here in the following two methods, same action is taken but methods are different for different data types - int and double -
// add method adds two integer numbers and returns an integer number
public int add(int x, int y) {
return x + y;
}

// add method adds two double numbers and returns a double number
public double add(double x, double y) {
return x + y;
}
Polymorphism is of two types - Compile Time Polymorphism (Static Polymorphism) and Run Time Polymorphism (Dynamic Polymorphism)

Static Polymorphism
When we declared two or more methods with the same name but with different signatures (different parameters), it is decided at compiler time that which method will be invoked when called. That's why this type of polymorphism is called the compile time polymorphism. This polymorphism can be achieved by using Method Overloading feature in Java. Here is the example for Method Overloading -

Class MultiplyOverload (MultiplyOverload.java)
// Class MultiplyOverload with four overloaded methods multiply()
public class MultiplyOverload {
// Multiplies two integer numbers
public double multiply(int x, int y) {
int r = x * y;
return r;
}

// Multiplies one double number and one integer number
public double multiply(double x, int y) {
double r = x * y;
return r;
}

// Multiplies two double numbers
public double multiply(double x, double y) {
double r = x * y;
return r;
}

// Multiplies two double numbers and round off decimals if third boolean parameter is true
public double multiply(double x, double y, boolean ro) {
double r = 0.0;
if(ro) r = Math.round(x * y);
else r = x * y;
return r;
}
}
Class MultiplyOverloadTest (MultiplyOverloadTest.java)
// Class MultiplyOverloadTest to test overloaded methods multiply() in class MultiplyOverload
public class MultiplyOverloadTest {
public static void main(String args[]) {
MultiplyOverload mo = new MultiplyOverload();

System.out.println("9 * 8 = " + mo.multiply(9, 8)); // Calls first method
System.out.println("9.25 * 8 = " + mo.multiply(9.25, 8)); // Calls second method
System.out.println("9.25 * 8.75 = " + mo.multiply(9.25, 8.75)); // Calls third method
System.out.println("round(9.25 * 8.75) = " + mo.multiply(9.25, 8.75, true)); // Calls fourth method
}
}
Output:

9 * 8 = 72.0
9.25 * 8 = 74.0
9.25 * 8.75 = 80.9375
round(9.25 * 8.75) = 81.0

Dynamic Polymorphism
When we declare two or more methods with the same name and the same signatures too, the compiler is not able to resolve which method is to be called. So, in this case, decision to call one of the same name methods is made at run-time. That's why this kind of polymorphism is called as the run time polymorphism. This polymorphism can be achieved by using Method Overriding feature in Java.

Method overriding feature is connected with the inheritance principle in Java. (I will cover inheritance in detail in the next post.) In short, it is a parent-child concept. A class can be a parent of other classes and the classes inherited are called child classes or sub classes. A parent class and child class can have same name methods with same signatures (same number of parameters, same data types parameters and same return type). It is called Method Overriding. Here is the example of Method Overriding -

Class Shape (Shape.java)
// Parent class Shape
import java.lang.Math; // imports Math package
public class Shape {
final static double PI = Math.PI;
double width = 0;
double height = 0;

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

// Returns the area of the shape
public double area() {
return 0.0;
}
}
Class Circle (Circle.java)
// Child class Circle inherits from class Shape
public class Circle extends Shape{
// Returns the text telling what shape it is
public String whatShape() {
return "Circle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
double radius = width / 2;
return Math.round(PI * radius * radius * 100) / 100.0;
}
}
Class Triangle (Triangle.java)
// Child class Triangle inherits from class Shape
public class Triangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
Class Rectangle (Rectangle.java)
// Child class Rectangle inherits from class Shape
public class Rectangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Rectangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round(height * width * 100) / 100.0;
}
}
Class ShapesTest (ShapesTest.java)
// class ShapesTest to test class Shape's overridden methods - whatShape() and area()
public class ShapesTest {
public static void main(String args[]) {
// Created an array of 3 shapes
Shape shapes[] = new Shape[3];

// Created 3 instances of 3 child classes
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Rectangle();
System.out.println("Shapes Test");

for(int i = 0; i < shapes.length; i++) {
shapes[i].height = 5;
shapes[i].width = 9;

// Called the methods through parent's reference (Compiler doesn't know which object's method is called)
// At run-time decision is made, which class method is called
System.out.println("Shape is " + shapes[i].whatShape());
System.out.println("Area is " + shapes[i].area());
System.out.println("");
}
}
}
Output:

Shapes Test
Shape is Circle
Area is 63.62

Shape is Triangle
Area is 22.5

Shape is Rectangle
Area is 45.0

Sunday, June 21, 2020

Java: What is Encapsulation?

Encapsulation means the action of enclosing something in or restricting access to something. Java uses the principle of encapsulation - bundles (hides) the data and methods (behaviors) in a class definition. In my previous posts and examples, I have explained how we can use the variables and methods in the class together.



By putting related data and method altogether in an class, it becomes easy and safe way to handle data. Whenever we need to change a specific class, we have to change only one class, means we don't have to compile whole program. We need to compile only one class. And that we can restrict access to the class components from outside. In Java, to define the scope of the variables and methods, access modifiers are used. There are 3 access modifiers - public, private and protected.

Public is the default access modifier. It means, the class components (variables and methods) declared as public can be accessed by the any other classes outside from the class.

Class AccessMod1 (AccessMod1.java)
// To declare public access modifier class components
public class AccessMod1 {
public int num = 10;

public void printNum() {
System.out.println("Calling from the class itself: " + num);
}
}
Class AccessTest1 (AccessTest1.java)
// To test public access modifier class components
public class AccessTest1 {
public static void main(String args[]) {
AccessMod am = new AccessMod();

// It can access directly as the variable is public
System.out.println("Calling From Main Class: " + am.num);

// It can access directly to the method as it is public
am.printNum();
System.out.println();

// Public variables can be changed directly
am.num = 15;
System.out.println("Calling From Main Class: " + am.num);
am.printNum();
}
}
Output :

Calling From Main Class: 10
Calling from the class itself: 10

Calling From Main Class: 15
Calling from the class itself: 15

Private access modifier restricts access for the variables and methods to the class itself. No other class can access directly the variables and methods declared as private.

Class AccessMod2 (AccessMod2.java)
// To declare private access modifier class components
public class AccessMod2 {
private int num = 10;

public void printNum() {
System.out.println("Calling from the class itself: " + num);
showMsg();
}

public void changeNum() {
num = num + 5;
}

private void showMsg() {
if(num > 12) System.out.println("Number > 12");
}
}
Class AccessTest2 (AccessTest2.java)
// To test private access modifier class components
public class AccessTest2 {
public static void main(String args[]) {
AccessMod am = new AccessMod();

// It can not access directly as the variable is private
// System.out.println("Calling From Main Class: " + am.num);

// It can access directly to the method as it is public
am.printNum();
System.out.println();

// Private variables can not be changed directly
// am.num = 15;
// Private variables can only changed indirectly by the class methods
am.changeNum();

// This time private method is called internally, which can't be called directly
// am.showMsg();
am.printNum();
}
}
Output:

Calling from the class itself: 10

Calling from the class itself: 15
Number > 12

Protected access modifier restricts access for the variables and methods to its package classes (all classes in the package including non-subclasses) and its child (inherited) classes in other packages.

Note: I will explain Inheritance shortly.

Thursday, June 18, 2020

What is byte code?

When Java was developed in 1995, there are other languages - C / C++. There were other languages too - COBOL, PASCAL, FORTRAN and they had specific purposes. C language became popular in 1972 to develop programs and solve complex problems on all the platforms (operating systems). C was the structural language and the program was written on each platform to compile and run specifically on that platform. For each platform, the code was re-written and executed to run on the platform.

In 1979, C++ was developed as enhanced version of C language. C++ was too structural languages with object oriented fundamentals and features. Because of the object oriented, it was possible to reuse of some of the components of the program. Still, the code was re-written / compiled for each platform. So, for all the structured languages, the following path was used to compile the program files and run on the specific platform -

To change anything in the program, whole code was needed to compile and execute again and also for each platform separately.

In 1995, Java was developed to enhance C++ object oriented features, but Java is a very different language than C++. Java is totally object oriented language. Java language is data driven, and data is in the form of objects (things) and procedures were in objects specifically used to manipulate data itself. 

In Java, everything is categorized as a class and each class can have its own data (properties / features / fields whatever you name) and methods (used to manipulate data inside or outside the class, interact with other classes, etc.).  Each class has a separate file .java file. And objects are the instances of the classes.

Each .java file is compiled and converted into a byte-code file .class file. This byte-code file is universal file for every platform. Each platform has their own JVM (Java Virtual Machine) or Java platform, which interprets the .class file for that specific platform. When there is a need in change in any particular class, you compile only that class and load it again. You don't need to compile and execute whole program again.


As shown in above picture, Java file is only once compiled and converted into byte code. JVM (Java Virtual Machine) /Java platform is developed for all available platforms mostly. JVM interprets the same byte code for the specific platform and runs on the machine accordingly. 

So, byte-code is an intermediate code file which is not machine specific and can be run on any platform with the help of Java Virtual Machine (JVM).

Sunday, June 14, 2020

Java: What is a varargs method?

Varargs Method
A method is called varargs method when it can take a variable number of arguments as its parameters. The arguments should be of same data type. The all arguments combined is called as variable-length argument and is specified by three dots (...). And in the method, the argument is accessed as an array.

Here is the example of the method definition -
Test(int ... num) {
for(int i = 0; i < num.length; i++) {
System.out.println(num[I]);
}
}
And to call method, you can pass variable number of values of int data type -
Test(3, 4, 5);
Test(2, 4, 6, 8, 10);
The varargs method can have arguments more than one, but there can be only one variable-length argument and it should be the last argument passed to the method. Here are the examples of valid varargs method declaration -
Test(boolean a, int ... num) 
Test(int a, float b, int ... num) 
Test(boolean ... a) ✓
These are invalid method declaration examples,  -
Test(int ... num, float b, int a) 
Test(boolean a, int ... num, float y) 
Overloaded Varargs Methods
Varargs method can be overloaded too. Like I mentioned examples of valid varargs methods above, when used in a program they are considered as overloaded methods - 
Test(boolean a, int ... num) 
Test(int a, float b, int ... num) 
Test(boolean ... a) 
Ambiguous Overloaded Varargs Methods
Sometimes overloaded varargs methods are syntactically fine but show ambiguity. Following example shows ambiguity when the program calls the overloaded  method without any arguments, the program will not compile.  -
Test(int ... num)

Test(boolean ... a)
And call the method Test() without arguments, compiler won't be able to know which method should be called when there are no arguments passed to the method -
Test();
Here is another example of overloaded varargs method which shows ambiguity. The compiler won't be able to resolve which method should be called -
Test(int ... num)

Test(int a, int ... num)
Example of use of Varargs method to get maximum of given numbers 
public class MaxVal {
public static void main(String args[]) {
int a = max(10, 20, 30);
int b = max(25, 35, 37, 28, 25);
int c = max(1, 12, 33, 23, 45, 19, 34, 64, 28);

System.out.println("Max Values are : a = " + a + ", b = " + b + ", c = " + c);
}

public static int max(int ... num) {
int m = num[0];
for(int i = 1; i < num.length; i++) {
if(num[i] > m) m = num[i];
}
return m;
}
}

Saturday, June 13, 2020

Java: How to reverse any string backwards using recursive method

What is recursive method?
Recursive method is a method which calls itself. There should always be a condition on which the recursion stops, else it will keep running indefinitely. Suppose we have to add numbers consecutively for particular start and end numbers.

Suppose start number is 2 and end number is 8, then consecutively you will add like below -
total = start + ..................... + end 
= 2 + 3 + 4 + 5 + 6 + 7 + 8
= 5 + 4 + 5 + 6 + 7 + 8
= 9 + 5 + 6 + 7 + 8
= 14 + 6 + 7 + 8
= 20 + 7 + 8
= 27 + 8
= 35

We use the same concept for writing recursive method to add consecutive numbers.

Class SumRecursive (SumRecursive.java)
public class SumRecursive {
public static void main(String args[]) {
int start = 2, end = 8;
int next = start + 1;
int total = sum(start, next, end);
System.out.println("Total is: " + total);
}

public static int sum(int total, int next, int end) {
int tot = total + next;
if(next != end) {
next++;
tot = sum(tot, next, end);
}
return tot;
}
}
Here is the output:

Total is: 35

Reverse the string using recursive method
To reverse a string, we have created two methods - revStr() and swapChars(). In the main method, user is asked to enter any string. String is converted to a char array. The converted array is passed to the method revStr() as the parameter. revStr() method calls method swapChars() and pass the char array and the first and last character positions to swap. Here is the logic -

Suppose user enters the string: "Logic Blocks" -

Converted char array will be like this.
ch[] = {'L', 'o', 'g', 'i', 'c', ' ', 'B', 'l', 'o', 'c', 'k', 's'}

Characters will be swapped like this
'L' = > 's'
'o' = > 'k'
'g' = > 'c'
'i' = > 'o'
'c' = > 'l'
' ' = > 'B'

Reversed String will be like this 
"skcolB cigoL"

Class Reverse (Reverse.java)
import java.util.Scanner;

public class Reverse {
public static void main(String args[]) {
String s1, s2;
char ch[];

System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();

ch = s1.toCharArray();
s2 = revStr(ch);

System.out.println();

System.out.println("String backwards:");
System.out.println(s2);
}

public static String revStr(char[] ch) {
swapChars(ch, 0, ch.length-1);

String str = String.valueOf(ch);
return str;
}

public static void swapChars(char[] ch, int left, int right) {
if(left < right) {
char tch = ch[left];
ch[left] = ch[right];
ch[right] = tch;
swapChars(ch, left+1, right-1);
}
}
}
Here is the output:

Enter the string:
Logic Blocks

String backwards:
skcolB cigoL

Friday, June 12, 2020

Java: Example of passing object reference as the parameter

When a method is called in a program, parameters can be passed two ways -

Call by Value
When a variable is passed as a parameter to a method, the method can use the value of the variable or manipulate the value in the method and can return the new value. But any changes in the variable value doesn't reflect after returning from the method. Method doesn't change the value of original variable. Here is the example -

Class CallByVal (CallByVal.java)
public class CallByVal {
    public static void main(String args[]) {
        int i = 5;

        System.out.println("Original Value: " + i);

        int y = doubleVal(i);

        System.out.println("After Method Called: " + i);
        System.out.println("Doubled Value: " + y);

    }

    public static int doubleVal(int x) {
        x = x * 2;
        return x;
    }
}
A class CallByVal is created and an int variable i is declared and initialized to 5. There is one static* method defined in the class which returns the double of the passed value - doubleVal(). In the method, the parameter value is doubled. It returns the doubled value in different variable. After method, still the original variable i has the same value.

*Why static method? - static methods can call only static methods, main method is static method so called method is also static method.

Call by Reference
When a object is passed as a parameter to a method, then the reference of the object is passed to the method, and any changes to the object in the method, reflects after returning from the method. The method has still the reference to the original object and changes the value in the original object.

So, here is the example of passing object reference as the parameter -

Suppose there are two players and they throw the dice turn by turn and whoever has more, gets scored. They play 15 times. A class Score is created for to keep a track of scores. A constructor sets the initial value of score as 0. There are two methods in the class - setScore() and getScore().

Class Score (Score.java)
public class Score {
    private int val;
    Score(int i) { val = i; }

    static void setScore(Score sc) {
        sc.val++;
    }

    int getScore() {
        return val;
    }
}
setScore() is a static method so it can be accessed by class itself. It takes one parameter - Score  class object. The method increases the score value by 1.

getScore() method is regular method which can only be accessed through the object of the Score class. It returns the score value for the particular player.

Class ScoreDemo (ScoreDemo.java)
import java.lang.Math;

public class ScoreDemo {
    public static void main(String args[]) {
        int max = 6;
        int min = 1;
        int range = max - min + 1;

        Score s1 = new Score(0);
        Score s2 = new Score(0);

        System.out.println("Initial Score: ");
        System.out.println("Player1 " + s1.getScore());
        System.out.println("Player2 " + s2.getScore());

        for(int i = 0; i < 15; i++) {
            int dice1 = (int)(Math.random() * range) + min;
            int dice2 = (int)(Math.random() * range) + min;
            if(dice1 > dice2) Score.setScore(s1);
            else Score.setScore(s2);
        }

        System.out.println();
        System.out.println("Final Score: ");
        System.out.println("Player1 " + s1.getScore());
        System.out.println("Player2 " + s2.getScore());

    }
}
A class ScoreDemo initializes two variables max and min as 6 and 1, like a dice can have. A range is also set as total possible values. Two objects of class Score created. There is a for loop for 15 iterations - players throw dice turn by turn (number is generated randomly between 1 to 6 like dice). If player1 has more than player2, score1 value is increased. else score2 value is increased. Here is the sample output -

Initial Score:
Player1 0
Player2 0

Final Score:
Player1 7
Player2 8

Notice that how the method setScore() is declared in the class Score, and how it is called in class ScoreDemo using the class name itself: Score. This is a good example of passing object reference to a method.

Thursday, June 11, 2020

Java: How to create a class Stack

What is Stack? 

It is basically pile of anything kept in such way that things are accessed in LIFO (Last In First Out) order. A very good example is when we stack the plates. And we pick up the last plate first, and when we put more plates, we stack them up.

Stack in computer language is an array of any data type elements / class objects where the data is pushed or stacked one on top of another and always the last element is popped or retrieved first. Here is the implementation of Stack class.

In the following example, two classes are created - Stack and StackDemo.

Class Stack is a simple representation of a stack. Here stack is in the form of a character array. There is a constructor for the class Stack, which creates a character array for the given size and set pointer to start of the array. All the data members of the class Stack are kept private to avoid direct access from other classes.

There are two methods push and pop - push method checks if the stack is full, if not puts the element into last available index and increases index value by 1. pop method checks if the stack is empty, if not pops the last index element from the stack and then decreases the index value by 1.

Class StackDemo simply shows how to use the push and pop method from the class Stack.

Class Stack (Stack.java)
public class Stack {

    private char ch[];
    private int size, lastIndex;

    Stack(int size) {
        this.size = size;
        ch = new char[size];
        lastIndex = 0;
    }

    void push(char c) {
        if(lastIndex == size) {
            System.out.println("Stack is full");
            return;
        }

        ch[lastIndex] = c;
        System.out.print(c + " ");
        lastIndex++;
    }

    void pop() {
        if(lastIndex == 0) {
            System.out.println("Stack is empty");
            return;
        }

        System.out.print(ch[lastIndex-1] + " ");
        lastIndex--;
    }
}
Class StackDemo (StackDemo.java)
public class StackDemo {
    public static void main(String args[]) {
        Stack s1 = new Stack(10);

        System.out.println("Push to stack:");
        s1.push('j');
        s1.push('a');
        s1.push('v');
        s1.push('a');

        System.out.println("");
        System.out.println("Pop from stack:");

        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();

        System.out.println("");
        System.out.println("Push to stack:");

        s1.push('s');
        s1.push('t');
        s1.push('a');
        s1.push('c');
        s1.push('k');

        System.out.println("");
        System.out.println("Pop from stack:");

        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
        s1.pop();
    }
}
Output
Push to stack:
j a v a
Pop from stack:
a v a j Stack is empty

Push to stack:
s t a c k
Pop from stack:
k c a t s Stack is empty