Author Archives: Omkar Bhagat

Arrays in Java

So there’s something called Array in Java. In an array, you can store fixed-size sequential collection of elements of the same type.

The simplest way to create an array is using the following code:

int[] orray = {1,2,3,4,5,6};
System.out.println(orray[0]);

This code declares and creates an array called orray of size 6 starting from index 0 to index 5. And on the next line we use print statement to print the element at position 0 in the array (which is 1).

The coolest part about arrays is that we can run a loop and print (or do something with) all the elements in the array as follows:

class hello {
	public static void main (String args[]) {
		int[] orray = {1,2,3,4,5,6};

		for(int i=0; i<orray.length; i++) {
			System.out.println(orray[i] + " ");
		}
	}
}

This should print numbers from 1 to 6 (elements in the array), each on it’s own line. We can do so much more with arrays but that’s all you need to know for now!

Loops in Java

If you want to repeat certain set of statements over and over again, you can make use of loops in Java. Let’s start with the while loop:

 
int x = 0;
while (x < 10) {
	System.out.println(x);
	x++;
}

This will print 0 to 9 on screen, each on a new line because we have println. If you use print instead, it’ll be printed on the same line.

In the above code, we basically initiated variable x to zero. And said keep printing x till it’s value is less than 10. Also each time we print x, we increment x by 1.

Let’s do the same thing using a do-while loop now:

int x = 0;
do {
	System.out.println(x);
	x++;
} 
while(x<10);

This again does the same thing but the difference is (as you might have noticed), it will execute the loop at least once even if the condition returns as false.

Let’s do this with a for loop now:

for (int x=0; x<10; x++) {
	System.out.println(x);
}

This prints the same thing. In this code, x is initialized to zero and the condition is checked (x is less than 10). So everything inside the for loop gets executed. After execution x is incremented and again the condition is checked. This goes on till the condition returns false.

There’s another kind of loop called the for-each loop. We’ll look into that after we understand Arrays. So the next post is of course about Arrays!

Decision making in Java

The best part about coding is making things happen. But it’s not fun printing predefined stuff, we need things to happen on specific conditions. For this we make use of something called if statement. This is a simple if statement:

int x = 5;
int y = 2;

if (x > y) {
	System.out.println("X is greater than Y");
}

Currently the condition (x > y) is true, so the if block will be executed. And then everything else after the if block will be executed in normal flow.

What if you need to execute something if (x < y)? In that case, you can use an else statement as follows:

int x = 5;
int y = 2;

if (x > y) {
	System.out.println("X is greater than Y");
}
else {
	System.out.println("X is less than Y");
}

In any case you wish to have multiple conditions, you can do that as well using an else if statement in the middle as follows:

int x = 5;

if (x == 5) {
	System.out.println("X is 5");
}
else if (x == 6) {
	System.out.println("X is 6");
}
else {
	System.out.println("X is not 5 or 6");
}

You can also have nested if statements as follows:

String x = "human";
String y = "male";

if (x == "human") {
	if (y == "male") {
		System.out.println("It's a human male model");
	}
}

Then there’s the switch statement:

int x = 0;

switch(x) {
	case 1: System.out.println("number is 1");
			System.out.println("this is first case");
			break;
	case 5: System.out.println("number is 5");
			break;
	default:
			System.out.println("number is not 1 or 5");
}

You can try to run the above code with different values of x. Try putting in 0, 1 and 5 to see the output. If x equals 1, statements inside the first case are executed. If x equals 0, the default case is executed as no case is matched.

In the next post, I’ll share info on loops in Java!

Basic Arithmetic in Java

You can do basic arithmetic in Java but before we get to that point, we need to learn about variables in Java. Check the following code –

 
class basic {
	public static void main (String args[]) {
		int a = 3;
		int b = 2;
		System.out.println(a+b);
	}
}

Ignore public static void main part, that’s something which you need to include in every program and we’ll get to that sometime later in the future. For now, just know that you need to have it in your program to run it. Everything that matters is contained within the main block. And the program execution begins from the main block!

So we initiate variable a as integer with value 3 and we do the same for b with value 2. Then using a print command we print the sum of a and b using an arithmetic operator (a+b).

Similarly we can subtract, multiply, divide numbers in the program –

class basic {
	public static void main (String args[]) {
		int a = 3;
		int b = 2;
		System.out.println(a+b);
		System.out.println(a-b);
		System.out.println(a*b);
		System.out.println(a/b);
	}
}

In the next post, I’ll share a bit about decision making statements and conditional operators in Java!

How Java code works?

In the previous post, we learned how to print hello world using Java. And we used two commands in terminal – javac and java (to compile and run java program).

These two commands are required to achieve platform independence (meaning you can run this compiled java program on any operating system). You compile your human readable code using javac into a bytecode file. This is essentially an object file which will be used by Java interpreter (java command).

When you install JDK, you also install JVM (Java Virtual Machine) along with it. This is where the magic happens! JVM runs on top of your OS. So the compiled code is never really executed by your OS and is always executed by JVM.

This is why you can simply move your compiled object file (bytecode) to a different operating system and still manage to run your java program.

If you need more detailed information on this, you can refer this awesome page and let me know what you think in the comments below!

Printing Hello World using Java

If this is the first time you’re going to run a Java program, the very first thing you should do is check whether you have Java Development Kit installed on your system. To do this, just enter the following command in the terminal –

javac

If you don’t have JDK installed, it’ll return the following message –

No Java runtime present, requesting install.

If you see this, you can get JDK by a quick google search or by visiting this page.

Once you download JDK, just install it and test the javac command again in the terminal. If it works, you are good to write Java code.

I am using textedit to write code for now. You can use the same (textedit, notepad, anything actually as long as it’s plaintext). If you’re looking to upgrade your text-editor to something more amazing, I’ll recommend using Sublime.

Anyway, coming back to the point. Copy paste the following code in a new textedit document and save it as hello.java on your desktop. (Don’t forget the extension .java).


class hello {
	public static void main (String args[]) {
		System.out.println("Hello World");
	}
}

Go back to your terminal. Enter the following command to compile your program –

javac hello.java 

If it doesn’t give any errors, you’re all good to execute the program using this next command (it doesn’t need .java extension anymore) –

java hello 

The output should be Hello World.

Note: If you receive illegal character as errors while compiling the program, just switch to a different text-editor like sublime and that’ll fix the issue.

I’ll explain (or try to explain) how all of this works in my next post!

Writing Hello World using Bash

I haven’t been writing blogs since a long time now. But I’ve been learning a lot of good stuff working at Automattic (the company behind WP.com). So I plan to write and share stuff I learn here on this blog (at least one article on a daily or a weekly basis).

Today, I’ll be sharing something which I just learned from a YouTube video – Writing hello world using bash (shell scripting).

I’ll be writing this for Mac OS X but if you’re using Linux or Windows 10, you should be good. Now before you start, you can check the shells available to you by typing in the following command in the terminal –

 cat /etc/shells 

Once you enter it, you should see all the shells available to you. I see this on my Mac operating system –

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh

In this post, I’ll be specifically using bash. So it’s important to locate where bash is stored on your system. To do this, we will use the which command.

which bash

This will return the directory where bash is stored. For me this is –

 /bin/bash 

Next just navigate to your desktop using the change directory (cd) command. And create a file called hello_world.sh using the touch command.


cd desktop
touch hello_world.sh

Now type the following to see a short list of files in your directory –


ls - al

I’m seeing this being returned in my terminal –


-rw-r--r-- 1 omkarbhagat staff 0 Oct 23 03:01 hello_world.sh

This means, out of the three permissions (read r, write w, execute x) – the owner of the file has read, write; the group has read permission and others have read permission.

Just keep this information in mind and move to the next step. Go ahead and open your newly created file using textedit (or your preferred text editor). And then write the following code inside of it –


#! /bin/bash
echo "Hello World"

In the above code, #! is something which is called shebang in Unix. We use that as first line to make use of bash and the 2nd line is self explanatory.

Save the file and run it in terminal using the following command –

 ./hello_world.sh 

The moment you run it, you’ll see a permission denied error. If you remember, you still don’t have write permissions for this file. So you can now chmod it –

 chmod +x hello_world.sh 

This will add an execute permission to all three types of user groups. And if you run ls -al again, you should be able to see the x permission there –

 -rwxr-xr-x@  1 omkarbhagat  staff    32 Oct 23 03:21 hello_world.sh 

Now you can simply run or execute hello world again and the output will be Hello World on screen –