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’.

Yes, you must find the ancient scriptures of Sun Micro systems 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 welcome to drop an email.

 

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 var_4 = 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.

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 IE Java series! мфо долгосрочные займы список

Leave a Reply

Your email address will not be published. Required fields are marked *