Tuesday, 29 September 2020

Java One-Oh-One

Java is a high-level programming language that has been around for two decades and is still going strong. It is object-oriented, is platform independent, has wonderful documentation and community support, is free, and is everywhere – the moment you install Java, a screen generally comes up which states ‘3 billion devices run Java’.

Java and coffee - the ultimate combination

Yes, you must find the ancient scriptures of Sun Microsystems to learn a language, a language which, unknown to many, continues to flourish in the twenty-first century, a language so precious its priceless (in more ways than one), a language not lost in the sands of time.

Or, instead of finding those scriptures, you may read this blog post, which shall unravel the deep, dark mysteries which surround this language, the language called Java.

All right, enough adventure talk, let’s begin already.

We’re going to go through some basic programming concepts in Java, namely variables, operators, selection, iteration and jump statements. If you’re new to programming, you’d want to read this post with hardcore determination, while if you’ve already done some non-Java programming in the past, I’d recommend you quickly skim through this post to get a feel of the language. And if you’re a Java developer, how about you go through this post and let me know about errors, if any? :) Email manasdtrivedi@gmail.com

I’ve used the idea of ‘learning by example’ in this post. If you don’t understand the theory of a section, say, increment/decrement operators, then go through the example code for it, look at the output, and try to figure out the reasons for said output. Since Java is quite close to the way we speak in English, the code is generally pretty clear. But yes, if you indeed have queries, you’re free to email me :)

Variables

Variables are named ‘boxes’ of a certain type, which hold values of that type. For example, a fruit box called fruitBox1 will hold a fruit in it, say a mango, or a jackfruit. Similarly, an integer variable called num will store an integer in it, say 7 or -9 or 0 or 17395.

The way we declare and initialize variables in Java is as shown:

datatype variableName = value;

So, an integer variable called ‘num’ is declared and initialized with the value 3 as:

int num = 3;

Here, ‘int’ is the datatype (i.e. the type of the variable), ‘num’ is the name of the variable, and ‘3’ is the value put into variable ‘num’. In simple terms, int num = 3 means we’re putting the value 3 into an integer box (integer variable) called ‘num’.

Note that the ‘=’ sign doesn’t mean equality i.e. int num = 3 doesn’t mean ‘num is equal to 3’. Rather, we’re inserting 3 into the box called ‘num’. You can perhaps imagine replacing the ‘=’ sign with a ‘<-’ (leftward arrow) to reinforce this idea.

A variable in Java can have any name, as long as it isn’t a keyword, doesn’t begin with a digit, and is composed of only alphabets, digits, underscore and/or dollar sign.

There are 9 types of variables in Java:

1.      Byte variables can store values from -128 to 127.

byte var1 = 25;

2.      Short variables can store values from -32768 to 32767.

short var_2 = 5678;

3.      Integer variables can store values from -2147483648 to 2147483647.

int var$3 = 9999999;

4.      Long variables can store values from -9223372036854775808 to 9223372036854775807.

long _var4 = 112233445566778899.

5.      Float variables can store values from ± 1.4E-45 to ± 3.4028235E+38.

float principal = 10.0F;

Note the ‘F’ at the end of 10.0. That denotes a float.

6.      Double variables can store values from ± 4.9E-324 to ± 1.7976931348623157E+308.

double d = 20.0;

Note that this doesn’t need a ‘D’ or similar, as was used for floats.

7.      Character variables store characters.

char ch = ‘A’;

8.      Boolean variables can store either ‘true’ or ‘false’.

boolean b = true;

9.      String variables can store zero or more characters, like the name of an institute.

String institute = “NIT Karnataka, Surathkal”;

Sometimes, we may want the String variable to be empty. In that case, we can either initialize it with null, or with “” (i.e. empty string).

String username = null;

String str = “”;

 

Operators

Java has a wide variety of operators, but we’ll be looking at only a few of them.

1.      Arithmetic operators:

 

+ is used for adding two operands.

double total = 100.0, tax = 10.0;

double grandTotal = total + tax;

Here, grandTotal will be assigned value 110.0.

+ is also used for concatenating strings.

String str1 = ‘IE’, str2 = ‘NITK’;

String str3 = str1 + “-” + str2;

Here, str3 will hold the string “IE-NITK”.

 

- is used for subtracting two operands.

int x = 1, y = 2;

int z = x - y;

Here, z will store 1 - 2 i.e. -1.

 

* is used for multiplying two operands.

short s1 = 3, s2 = 4;

short s3 = s1 * s2;

Here, s3 will store 3 * 4 i.e. 12.

 

/ is used for dividing two operands.

double z1 = 5.0 / 2.0;

Here, z1 will store 5.0 / 2.0 i.e. 2.5.

 

% is used for finding the remainder upon dividing two operands.

int op1 = 10;

int op2 = 3;

int remainder = op1 % op2;

Here, remainder will store the remainder upon dividing 10 by 3, i.e. 1.

 

Little note: ‘returns’ in this blog post means ‘is replaced by’.

For example,

int a = 3 + 4;

Here, we say 3 + 4 ‘returns’ 7. This means you can effectively ‘replace’ 3 + 4 in the above line of code with 7. So,

int a = 7;

‘returns’ actually means something else in programming, but for now, this will do.

 

2.      Increment/Decrement operators:

 

Prefix form: Follows ‘change-then-use’ rule, i.e. ++operand or --operand first increments/decrements the value of operand, and then returns the changed value of operand.

 

Example:

int a = 2, b = 2;

int c = ++a;

int d = --b;

 

After execution of above statements, a will store value 3, c will store value 3, b will store value 1, d will store value 1.

 

Postfix form: Follows ‘use-then-change’ rule, i.e. operand++ or operand-- returns the current value of operand and then increments/decrements operand. Note that the ‘changed’ value isn’t returned, the value before changing is.

 

Example:

int a = 2, b = 2;

int c = a++;

int d = b--;

 

After execution of the above statements, a will store value 3, c will store value 2, b will store value 1, d will store value 2.

 

3.      Relational operators:

 

Here and beyond, op1 means first operand, and op2 means second operand.

op1 > op2 returns true if op1 is greater than op2, else returns false.

op1 >= op2 returns true if op1 is greater than or equal to op2, else returns false.

op1 < op2 returns true if op1 is lesser than op2, else returns false.

op1 <= op2 returns true if op1 is lesser than or equal to op2, else returns false.

op1 == op2 returns true if op1 is equal to op2, else returns false.

op1 != op2 returns true if op1 is not equal to op2, else returns false.

 

Example:

int x = 3, y = 2, z = 2;

boolean b1 = x > y;

boolean b2 = 20 < 15;

boolean b3 = y >= z;

boolean b4 = 12 <= 10;

boolean b5 = y == z;

boolean b6 = 10 != 10;

 

Here, variables b1, b3 and b5 will hold value true, while b2, b4 and b6 will hold value false.

 

4.      Logical/Conditional operators:

 

op1 && op2 returns true if both op1 and op2 are true, else returns false, checks op2’s value only if op1 is true.

op1 || op2 returns true if any of op1 or op2 is true, else returns false, checks op2’s value only if op1 is false.

op1 & op2 returns true if both op1 and op2 are true, else returns false, always checks both op1 and op2’s values.

op1 | op2 returns true if any of op1 or op2 is true, else returns false, always checks both op1 and op2’s values.

op1 ^ op2 returns true if either op1 or op2 is true, but not both, else returns false.

!op1 returns true if op1’s value is false, else returns false.

 

Example:

boolean b1 = (3 > 2) && (2 < 1);

boolean b2 = !b1;

boolean b3 = b1 || b2;

boolean b4 = b1 ^ b2;

 

Here, b1 stores false, b2 stores true, b3 stores true, b4 stores true.

 

Selection statements

Selection statements allow us to choose a set of instructions for execution based on an expression’s truth value.

1.      if statement: Statements inside the if block get executed only if the condition evaluates to true. A ‘block’ is denoted by curly brackets i.e. ‘{’ and ‘}’. All statements present inside the curly brackets are a part of one ‘block’ of statements.

if…else statement: Statements inside the if block get executed if the condition evaluates to true, else the statements inside the else block get executed.

 

Example:

int x = 5, y = 5, z = 4;

if (3 > 2) {

      System.out.println(“3 is greater than 2.”);

}

if (x  > y) {

      System.out.println(“x is greater than y.”);

}

else if (x < y) {

      System.out.println(“x is less than y.”);

}

else {

      System.out.println(“x is equal to y.”);

}

if (y >= z) {

      if (y > z) {

            System.out.println(“y is greater than z.”);

      }

      else {

            System.out.println(“y is equal to z.”);

      }

}

else {

      System.out.println(“y is less than z.”);

}

 

Here, the output window displays the following output:

3 is greater than 2.

x is equal to y.

y is greater than z.

 

2.      switch statement: This statement tests the value of an expression against a list of integers or characters. Upon finding a match, the statements associated with that integer or character is executed. If no match is found, the statements associated with the default label (if exists) is executed. It is generally a good idea to have a default label.

 

Example:

int dayOfWeek = 8;

char language = ‘J’;

switch (dayOfWeek) {

      case 1: System.out.println(“Monday”);

            break;

      case 2: System.out.println(“Tuesday”);

            break;

      case 3: System.out.println(“Wednesday”);

            break;

      case 4: System.out.println(“Thursday”);

            break;

      case 5: System.out.println(“Friday”);

            break;

      case 6: System.out.println(“Saturday”);

            break;

      case 7: System.out.println(“Sunday”);

            break;

      default: System.out.println(“Invalid day of week.”);

}

switch (language) {

      case ‘C’: System.out.println(“Language selected is C.”);

            break;

      case ‘+’: System.out.println(“Language selected is C++.”);

            break;

      case ‘J’: System.out.println(“Language selected is Java.”);

            break;

      case ‘P’: System.out.println(“Language selected is Python.”);

            break;

      default: System.out.println(“Invalid language selected.”);

}

 

Here, the output window displays the following output:

Invalid day of week.

Language selected is Java.

 

Iteration statements

These statements (called ‘loops’) are used to execute a set of instructions (the body) repeatedly as long as the value of an expression is true. These statements generally have four parts: the initialization (where the control variable is initialized), the expression (whose truth value decides whether the body will be executed), the updation (which updates the control variable), and the body of the loop.

1.      for loop: The first three elements of the loop (initialization, expression, updation) are gathered at the top of the loop (generally). The expression is first checked, then the body is executed if the expression is true.

 

Example:

for (int x = 1; x <= 2; x++) {

      System.out.println(“Value of x is ” + x + “.”);

}

 

Here, x is first initialized as 1. The expression x <= 2 is checked. It is true, so the body is executed. Now, the updation x++ takes place. x is now 2. The expression x <= 2 is checked. It is true, so the body is executed. Updation x++ takes place once again. x is now 3. The expression x <= 2 is checked. It is false. So, the loop is exited.

 

The output window displays the following output:

Value of x is 1.

Value of x is 2.

 

We can also skip one or more of the three elements at the top of the for loop. For example, for(; x <= 2; x++) {…} is perfectly legal, as long as x is declared and initialized somewhere above the loop. Note that although the initialization expression was removed, the semicolon wasn’t!

 

2.      while loop: It is pretty similar to an if statement in the sense that the body of the loop is executed if the expression evaluates to true. The initialization of the loop control variable (if any) is somewhere above the loop, and the updation (if any) is generally a part of the body.

 

Example:

int k = 2;

while (k > 0) {

      System.out.println(“k is greater than zero”.);

      k--;

}

System.out.println(“k is now zero.”);

 

Here, k is initialized to 2. The condition k > 0 is checked. It is true, so the body is executed. In the body, the updation k-- occurs. k becomes 1. The condition k > 0 is checked again. It is true, so the body is executed. k-- occurs, k becomes 0. Now the condition k > 0 is checked, which returns false. So, the loop is exited.

 

The output window displays the following output:

k is greater than 0.

k is greater than 0.

k is now 0.

 

3.      do-while loop: Here, the loop control expression is evaluated after the body is run, and its truth then determines whether the body is to be executed again. The initialization (if any) is above the loop, and the updation (if any) is generally a part of the body.

 

Example:

int x = 0;

do {

      System.out.println(“Saluton Mondo!”);

      x--;

} while (x > 0);

 

Here, x is initialized with the value 0. The body is run. The updation x-- takes place, x becomes -1. Then the expression x > 0 is tested. It is false. So, the loop is exited.

 

The output window displays the following output:

Saluton Mondo!

Loops can also be nested, i.e. a loop can be written inside a loop.

 

Jump statements

They are used for unconditional ‘jumping’ i.e. going to a certain part of the code without any condition. We’ll look at two of these: break and continue.

1.      break statement: It is used to terminate the execution of the loop. The control immediately jumps to the code after the loop.

 

Example:

int x = 1;

while (x < 5) {

      System.out.println(“Incoming break statement!”);

      break;

      x++;

}

System.out.println(“We’re now outside the loop.”);

 

After entering the loop, the break statement is encountered, and we directly go to the statement after the loop. The updation x++ never occurs.

 

The output window displays the following output:

Incoming break statement!

We’re now outside the loop.

 

2.      continue statement: It is used to directly go to the next iteration of the loop, skipping any statements left to be executed in the body.

 

Example:

for (int x = 1; x <= 3; x++) {

      if (x == 2) {

      continue;

}

System.out.println(“x is now ” + x + “.”);

}

 

Here, x is initialized to 1. The condition x <= 3 is evaluated to be true. Hence, we enter the body. x is not 2, hence the continue statement isn’t executed. ‘x is now 1.’ is printed. Updation takes place, x becomes 2. The condition x <= 3 is evaluated. It is true. So, we enter the body again. This time x is indeed 2, hence the continue statement is executed. The rest of the body isn’t executed, we directly jump to the next iteration. Updation takes place, x becomes 3. Condition x <= 3 is yet again true. We enter the body once again. Since x isn’t 2, the continue statement isn’t executed. “x is now 3” is printed. Updation: x becomes 4. Now the condition x <= 3 is false, hence we exit the loop.

 

The output window shows the following output:

x is now 1.

x is now 3.

 

Reached this far? Congratulations! You now have a very sound knowledge of the basics of Java, which we’ll require soon.

Soon?

Yes, I’m going to write another blog post with deals with creating interactive Java applications which have components like buttons, textfields, and checkboxes.

Stay tuned for Episode 2 of the Intellicenter Java series!

Thursday, 24 March 2016

Capturing Clouds

Clear, blue skies are perhaps a sign of nice, sunny weather.

Not a cloud.

Beautiful.

Right?

If you don't agree, congratulations, welcome to the elite society which believes in clouds and their magnificence!

Cloud watching is quite the pastime, if you have a little patience. Looking at the sky for a different cloud is all one has to do. People don't usually take any notice of these white swathes of moisture, but when one does, one may indeed be in for quite a visual treat.

Here are some pictures I've taken over the years of some ceaselessly captivating clouds:

The lightning that isn't

The flying lion-cub

Lion face

Now that's an angry hippo

What are you pointing at?

A frightening smile

Cloud wall

Nice hairstyle, though!

A white smile

The tornado that isn't

Dude, motorboats are not for flying

Elephant's trunk, or devil's tail?

A duck about to enter a pond

Superman?

Dragon-serpent

Power-packed punch!

Grim Reaper!
So for once he's actually captured on camera.

Turkey (the bird)

Orange lightning

Question mark

An eagle, or a cockatoo?


Copyright © 2016 Manas Trivedi
All rights reserved.
All images are copyright protected and are the property of Manas Trivedi. For permissions, please contact me at:
manasdtrivedi@gmail.com
-         Manas Trivedi

Wednesday, 23 March 2016

Role of Wildlife Sanctuaries in Preserving Wildlife


          You must’ve heard about wildlife sanctuaries. Wildlife sanctuaries are places where animals can live freely. India has 550 wildlife sanctuaries. And quite a bit of them are private sanctuaries engaged in buying, selling and trading wild animals. But are they wildlife sanctuaries in real sense?

          First, let us understand the difference between a wildlife sanctuary and zoo.

          Zoos are places where animals are kept in cages, while the people roam around freely. The zoo keeps animals for their conservation. They’re given food and a safe place to live, but not a free space to roam around, where they can feel free.

          But wildlife sanctuaries are places generally spread over huge areas. The animals are free to roam, but the visitors have to move in a restricted area only.

          Nowadays, many wildlife sanctuaries are becoming places for breeding of animals, and where the paying public is allowed to play with the young ones, like tiger cubs.

          If people are coming and playing with the cubs, will the animals feel safe? Do people feel safe when a leopard enters their village? How do people react? They try to get rid of the leopard as fast as they can. In the same way, the animals don’t feel safe when people are around them.

          A wildlife sanctuary should be a place where animals should feel as if they’re living in their natural habitat. They must have sanitary conditions, roomy enclosures, proper vet care, appropriate feed and the like.

          Visitors shouldn’t be allowed to get close to the animals, let alone playing with them. The sanctuaries mustn’t be breeding places and places for sale of animals. They never should be used as a place of entertainment for people.

          Wildlife sanctuaries must be places for animals, not for humans. That must be their sole purpose. Their environment must be one of complete serenity and tranquillity, so that the animals could spend their lives peacefully and safely.

-         Manas Trivedi

Sunday, 8 November 2015

Female Illiteracy

           Female illiteracy is one of the main problems faced by the developing countries in today’s world. Women and girls have often been denied equal opportunities in the field of education. The male dominated societies fail to understand the importance of female education, and hence, arises the problem of female illiteracy.

          The main causes of this problem are gender stereotypes. The girl child is seen as a burden on the family. She is treated unequally, as compared to the boys of the same family. Parents do not consider her education important, as one day she will get married and serve her husband and family. They also believe that their sons are more capable than their daughters. All this results in either denial for her education, or education till the elementary level only.

          This can have wide ranging effects in the society. An illiterate woman does not know the value of education. She does not pay attention to the education of her children. Thus, the vicious cycle of illiteracy gets repeated. She does not understand her own rights, and this makes her a victim of gender discrimination and inequality, once again.

          It is said that “If you educate a man, you educate an individual. But if you educate a woman, you educate a family.” An educated woman ensures the education of her children. She is also able to get employment, improving the economic condition of the family, and contributes to the national income. Thus, female education is a must for development.

          The best way to increase female education is by spreading awareness. The media, especially the radio and television, can be used for this purpose. We can also try to encourage parents to educate their daughters, and mention its advantages. Governments all across the world have implemented schemes ensuring female education.

          Today, we see women working as architects, pilots, teachers, doctors, engineers, accountants, and in every other field. This is the result of female literacy. Nowadays, societies are becoming more and more aware about the importance of woman education, equality and freedom. We still need to spread this awareness, to eradicate female illiteracy and to promote gender equality.

-         Manas Trivedi

Wednesday, 20 May 2015

Book Review - Carry On, Jeeves - by P.G. Wodehouse


‘Carry On, Jeeves’ by PG Wodehouse is the first book in the Jeeves and Wooster collection. The two main protagonists of the story – Bertie Wooster, the master and Reginald Jeeves, Bertie’s valet. The book has ten chapters, with Bertie being the narrator for nine, and Jeeves being the narrator for the last chapter.

          Introduction – The First Page:

The book starts with – ‘Now, touching this business of old Jeeves, my man, you know, how do we stand?’ Hmmm, yeah, so, who is the narrator? Who is speaking these lines? There is no such introduction like – ‘Hey, I’m Bertie Wooster’, or ‘Bertie here!’ throughout the book. You won’t get who the narrator is, until you read the 18th page, where Bertie’s fiancĂ©e takes his name. So, what I think is that there is be a book written before this one by Wodehouse in which features Bertie but not Jeeves. And I completely failed to find that book on the internet, or should I say, the internet completely failed me. Thus, one has to read that book (if there is one) which precedes this one in order to know who the narrator is. It isn’t the author’s fault, as one must read the introduction book before moving on to the second, but still, if you read Rick Riordan’s trilogy ‘Kane Chronicles’, each book introduces the person who is narrating.

          The first page kind of deters you from reading on. It isn’t that nothing is understandable, but mixing a few difficult words along with the fact that you don’t know the narrator, does not help. One needs the willpower and determination to go to the next page. I suggest you just need to, you know, read the first page, whether you understand it or not, and move on. Once you complete the chapter, you’ll know what the first page meant, after all.

Vocabulary – Difficult Words:

As for the difficult words, there are just so many, that after a while I stopped consulting the dictionary. If you are really interested in knowing each and every word’s meaning, you must use an online dictionary, or maybe a dictionary app. Using the dictionary (the real book), doesn’t make sense, since there are at least five hard words on each page, and about 15 minutes are required to find all their meanings, while searching them in the dictionary (the book). I once again suggest you don’t really need to completely know their meanings, and you need to leave the word and move on. You just need to know the meanings of a few frequently used words, and you’ll understand everything, the plot and all, without taking much time.

Style of Writing:

The style of writing used by Wodehouse must’ve been pretty futuristic for his time period, since I believe informal English, slang and humour weren’t there during the War period, only Shakespeare. For example,

‘What ho!’ I said.

‘What ho!’ said Motty.

‘What ho! What ho!’

‘What ho’! What ho! What ho!’

After that it seemed rather difficult to go on with the conversation.

Wodehouse gave this style of writing to Bertie, while giving the Shakespearean style, as I call it, to Jeeves. Bertie's informal style prevails for the nine chapters which Bertie narrates, with a hint of the Shakespearean style, when Jeeves speaks with Bertie. The last chapter gives you a full-fledged insight into the Shakespearean style, as the complete chapter is narrated by Jeeves. An example of Jeeves’ style:

‘The crux of the matter would appear to be, sir, that Mr Todd is obliged by the conditions under which the money is delivered into his possession to write Miss Rockmetteler long and detailed letters relating to his movements, and the only method by which this can be accomplished, if Mr Todd adheres to his expressed intention of remaining in the country, is for Mr Todd to induce some second party to gather the actual experiences which Miss Rockmetteler wishes reported to her and convey these to him in the shape of a careful report, on which it would be possible for him, with the aid of his imagination, to base the suggested correspondence.’

Mind you, the paragraph above is only one sentence, spoken by Jeeves to Bertie. Really, only one full stop at the end. Spoken by a GRE student, isn’t it? Only when Bertie explains the same to Mr Todd are we able to understand the meaning of the same.

Plots – The themes of most stories:

There are two types of plots used –

1.    Engagements – Bertie helps his friends to get engaged with whom they want to marry, and also helps them to break engagements with whom they unwillingly got engaged.

2.    Aunts and uncles – Bertie helps his friends to acquire money from their rich aunts and uncles, who had earlier stopped their allowances.

Basically, each chapter is a different story. There is a problem to be solved. A friend might approach Bertie for his help, for the above two situations. Bertie shows his faith in Jeeves and asks him for his help. And Jeeves faithfully helps Bertie by giving his helpful suggestions to solve the problems. The Wooster motto – When it comes to helping a pal, we Woosters have no thought of self. Thus, Bertie executes the solution, putting himself through all sorts of funny situations, and in the end, the problem is solved.

There is never a tragic end to a story. However difficult a problem may be, it always gets sorted with the help of Jeeves at the end. Each story seems to lift your spirits, irrespective of whether you’ve gone into a depression, or if you’re feeling topping. You get the hope that even the biggest of the problems has a solution.

Very well said by Marian Keyes:

‘The ultimate in comfort reading, because nothing bad ever happens in P.G. Wodehouse land. Or even if it does, it’s always sorted out by the end of the book. For as long as I’m immersed in a P.G. Wodehouse book, it’s possible to keep the real world at bay and live in a far, far nicer, funnier one where happy endings are the order of the day.’

Type of book:

The book is supposed to be a humorous, funny sort of book. There are quite a few instances which were pretty funny. But I wouldn’t call the book altogether funny. I’d say only those situations which Bertie encounters while helping a friend are hilarious. The rest of the book is like a normal storybook. Concerned with the fact that Wodehouse was an English humourist, you won’t find funny one-liners every now and then. Still, I’d call this as a ‘different’ storybook. This is the book which one really wants to read. It is like ‘What will happen next? Will Bertie be able to solve the problem?’ So, you have a bit of suspense in there as well. Humour, suspense, climax, problems, solutions and happy endings. Bored of normal novels? Go for this one.

-         Manas Trivedi