Java Language Fundamentals – I

In this page, we will understand some very core language fundamentals. If you already have an understanding of another programming language like C, C++ or PHP, you can ignore this chapter and move on to the next. If you know the theory and would like to be quizzed, then move straight to the questions embedded in the page.

Statements

Statements are like sentences. Each sentence is ended by a full stop in English. Each statement in Java ends with a semi-colon. Probably a colonial hang-over from the ‘C’ language 🙂

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public Class HelloWorld
{
public static void main(String[] args)
{
System.out.println
("Hello World!");
}
}
[/java]

Question 1 : Will this program compile ? What is your inference ?.

Variables

Variables hold the data in an object.  Let’s introduce some variables to our Hello World class – int count ;

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count;
System.out.println ("Hello World!");
}
}
[/java]

What are we saying here ? This is called “Declaration” – We are just declaring the placeholder variable – We haven’t given it a value yet.

Question 2 : Will this program compile without the variable being declared a value ? What do you understand out of this ?

Let’s assign a value to it. Essentially, we are assigning a value to this placeholder.

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count = 10;
System.out.println ("Hello World!");
}
}
[/java]

We are assigning a value to the variable count – 10. Let’s declare another variable count_twice. Remember, we will not define its value. Just declare it. And then write code to say, count_twice will always be twice the value of count.

[java title=”HelloWorld.java” gutter=”true” highlight=”6″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count = 10;
int count_twice = count * 2 ;
System.out.println ("Hello World!");
}
}
[/java]

That was easy. Can we print out the value of count and count_twice just to make sure it really is doing what we wanted ?

[java title=”HelloWorld.java” gutter=”true” highlight=”5-6,8-9″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count = 10;
int count_twice = count * 2 ;
System.out.println ("Hello World!");
System.out.println ("The value of count is " + count);
System.out.println ("The value of count_twice is" + count_twice);
}
}
[/java]

Question 3 : What is the result ?

Question 4 : What would the result be if we would have coded it as follows ?

[java title=”HelloWorld.java” gutter=”true” highlight=”5-6,8-9″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count = 10;
int count_twice = count * 2 ;
System.out.println ("Hello World!");
System.out.println ("The value of count is count");
System.out.println ("The value of count_twice is count_twice");
}
}
[/java]

The line highlighted instructs the compiler to print the String Literal “The value of count is” and then add the actual value of count at the end as a string.  The next line just says print the string literal “The value of count is count” . We will learn more about String Literals in a minute.

[java title=”Program Snippet” gutter=”true” highlight=”1″]
System.out.println ("The value of count is " + count);
System.out.println ("The value of count is count");
[/java]

Now, in order to understand the different primitive variables, you will have to understand some math. You may skip this section if required and move on to the Variables by Reference section.

Here are some examples of other kinds of important variables. We can ignore some other types like byte,short,long,double etc

[java title=”HelloWorld.java” gutter=”true” highlight=”5-6,8-9″]
public Class HelloWorld
{
public static void main(String[] args)
{
int count = 10;
float big_number = 123456789;
boolean = true;
char = ‘S’;
System.out.println ("Hello World!");
System.out.println ("The value of count is count");
System.out.println ("The value of count_twice is count_twice");
}
}
[/java]

Question 5 : What is the thoeritical limit of float ?

Question 6 : Can you compile the program with the following change ? What does this tell you ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
boolean = TRUE;
boolean = 1;
[/java]

Question 7 : Can a Char contain more than 1 character ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char = ‘Siva’;
[/java]

What if you wanted to declare a variable with the value ‘siva’ . May be you want to represent the first name of a customer in a variable.

Enter Arrays.  An Array is represented by two square brackets as shown below. Think of an array as an array of solar panels, an array of characters, an array of wine bottles in your wine rack.

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] first_name;
[/java]

However you cannot just say

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] first_name = ‘Siva’;
[/java]

Instead, you would have to individually assign a character to each of the values in the array.

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] first_name = {‘S’,’i’,’v’,’a’};
[/java]

This is a pain no doubt. However, we will see later how String Objects makes our life easy.

Question 8 : Declare a char array siva_teaches[]. What is the syntax ?

Declare this variable siva_teaches to contain 12 characters. How do we do it ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] siva_teaches = new char[12];
[/java]

What does siva_teaches[0] contain ? Is it NULL or Blank space ? Only one way to find out

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] siva_teaches = new char[12] ;
System.out.println ("Hello" + "World");
System.out.println ("Hello" + siva_teaches[0] + "World");
[/java]

What is the keyword “new” doing here ?It is essentially creating 12 new character spaces for you.

Question 9 : What is the result of the program above ? What does it tell you ?

Question 10 : Assign the following characters to it and give the syntax for the same.

Question 11 : After you assigned the above characters to it, What does the following statement print ? What does this tell you ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] siva_teaches = new char[12] ;
System.out.println (siva_teaches[0] + siva_teaches[5]);
[/java]

Question 12 : Can you change the length of the array siva_teaches now ? ( After creation )

Question 13 : Create the following arrays and give the syntax for the same.

  • An Array of 5 integers
  • An Array of 6 floats
  • An Array of 12 chars

Question 14 : What is the difference between Program snippet 1 and program snippet 2 below ? Does it produce the same result ?

[java title=”Program Snippet 1″ gutter=”true” highlight=”1″]
char[] siva_teaches = new char[12] ;
siva_teaches[0] = ‘S’;
siva_teaches[1] = ‘I’;
…..
…..
siva_teaches[11] = ‘S’;
System.out.println (siva_teaches);
[/java]

AND

[java title=”Program Snippet 2″ gutter=”true” highlight=”1″]
char[] siva_teaches = { ‘S’ , ‘I’ , ‘V’ , ‘A’ ,’ ‘ ,
‘T’ , ‘E’ , ‘A’ , ‘C’ , ‘E’ , ‘S’} ;
System.out.println (siva_teaches);
[/java]

You can also create an array of arrays. The syntax for that is quite simple as well.

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] [] siva_teaches = {
{ ‘S’ , ‘I’ , ‘V’ , ‘A’ , ‘T’ , ‘E’ ,’A’ , ‘C’ ,’H’ , ‘E’ ,’S’ } ,
{ ‘J’ , ‘A’ , ‘V’ ,’A’ }
} ;
[/java]

The first [] represents the rows in the matrix and the second [] represents the columns in the matrix. So siva_teaches[0] [5] will take you to the first row,  6th character – ‘E’

Question 15 : Give the output for the following Program.

[java title=”Program Snippet” gutter=”true” highlight=”1″]
char[] [] siva_teaches = {
{ ‘S’ , ‘I’ , ‘V’ , ‘A’ ,’ ‘ , ‘T’ , ‘E’ ,’A’ , ‘C’ ,’H’ , ‘E’ ,’S’ } ,
{ ‘J’ , ‘A’ , ‘V’ ,’A’ }
} ;

System.out.println (siva_teaches[0][0]);
System.out.println (siva_teaches[0][1]);
System.out.println (siva_teaches[1][0]);
System.out.println (siva_teaches[1][1]);
[/java]

Operators

We will explore the following main Operator. There are many more operators like bit-wise operators, shift operators etc which we will not explore yet. We just got started 🙂

  • Manipulative Operators like Addition (+) , Substraction (-) , modulus (%) etc.
  • Comparision operators like Less than (<) , greater than (>) , equal to (==) , not equal to (!=) etc.
  • Assignment operators like equal to (=) etc.

You can add 2 numbers. Say you have 10 brow eggs and 10 white eggs. How many total eggs do you have ? Let the program decide 🙂

[java title=”Program Snippet” gutter=”true” highlight=”1″]
int brown_eggs = 10;
int white_eggs = 10;
int total_eggs = brown_eggs + white_eggs;
System.out.println (total_eggs);
[/java]

Say you have broken 2 brown_eggs. How many eggs do you have now ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
int brown_eggs = 10;
int white_eggs = 10;
int broken_brown_eggs = 2;
int total_eggs = brown_eggs + white_eggs – broken_brown_eggs;
System.out.println (total_eggs);
[/java]

Say each egg crate can contain 6 eggs. You have put 6 white eggs in the crate. How many eggs are remaining ? Did you get the answer ?

[java title=”Program Snippet” gutter=”true” highlight=”1″]
int white_eggs = 10;
int remaining_eggs = white_eggs%6;
System.out.println (remaining_eggs);
[/java]

Question 16 : Let’s say you have 6 crates of eggs with each crate containing 6 white eggs. Write a program to show how many total white eggs are there in the 6 crates ?

Question 17 : Let’s say you have 60 eggs and each crate can contain 6 eggs. Write a program to show how many crates are required to pack all the 60 eggs into crates ?

There are incremental/decremental operators that we will see when we come to loops

Let’s look at comparative operators now. It is difficult to look at comparative operators without understanding at least one conditional statements (Like IF , ELSE). We will more of the same in the next section.

Say you have 10 brown eggs and 10  white eggs. Compare the count of brown eggs and white eggs and print out “Equal number of white eggs and brown eggs”  in case they are equal

[java title=”Program Snippet” gutter=”true” highlight=”3″]
int white_eggs = 10;
int brown_eggs = 20;
if ( brown_eggs == white_eggs)
{
System.out.println ("Brown Eggs = white Eggs");
}
else
System.out.println ("Brown Eggs not = white eggs");
[/java]

The program is probably self explanatory. What is important is to understand the double equal to symbol highlighted above (==) . Why don’t we use a single equals ? Remember, a single equal means assignment. Double equals is comparison.

Question 18 : What is the result of the following Program ?

[java title=”Program Snippet” gutter=”true” highlight=”3″]
int white_eggs = 10;
int brown_eggs = 20;
if ( brown_eggs = white_eggs)
{
System.out.println ("Brown Eggs = white Eggs");
}
else
System.out.println ("Brown Eggs not = white eggs");
[/java]

Similarly, greater than (>) , less than (<) , less than equal to (<=) and greater than or equal to (>=) are pretty simple.

Question 19 : If you have 10 brown eggs , 20 white eggs and 10 green eggs. Write a program to find out if

  • Which type of eggs are more in number ?
  • Which type of eggs are least in number ?

NOT Equal to operator (!=) . The ! operator ( Exclamation mark ) signifies negation. So, != means not equal to. However, there is no !> or !< to signify not greater than or not less than.

The following program will print “Brown eggs is not equal to white eggs

[java title=”Program Snippet” gutter=”true” highlight=”3″]
int brown_eggs = 20;
if ( brown_eggs != white_eggs)
{
System.out.println ("Brown Eggs is not equal to white Eggs");
}

else
System.out.println ("Brown Eggs equals white eggs");
[/java]

Loops

Looping is the same as in any other language. Just more easier.Looping is used when you want to repeat things again and again. For example, let’s take the same array example that we have taken. Without using the System.arraycopy method, let’s try to copy over the characters to create a new array.

The main looping operators are ‘for’  and  ‘while’ .

The FOR Loop. My first name is ‘Siva’ . Let’s say you have the same first name as mine. Whey copy each character manually ? Put them in a loop and start copying as follows. This might seem trivial if there are just 4 characters. What if there are 1000 characters ?

[java title=”Program Snippet” gutter=”true” highlight=”4″]
char[] my_first_name = {‘S’,’i’,’v’,’a’};
char[] your_first_name = new char[4];

for (int count = 0 ; count < my_first_name.length; count++)
{
your_first_name[count] = my_first_name[count];

}

System.out.println ( your_first_name);
[/java]

As highlighted above, a temporary variable called ‘count’ to compute the iteration you are going through. During the first iteration, we are copying the first character and so on. The for loop automatically, takes care of incrementing the count to 2 using the syntax ‘count++’ . This is a new operator that we have not seen in operators.

You might as well have said count = count + 1 and it would still work fine too. But just to make things easy, you can say count++ to increment it by 1 each time the for loop is iterated.

[java title=”Program Snippet” gutter=”true” highlight=”2″]

for (int count = 0 ; count < my_first_name.length; count = count +1 )

[/java]

What if you wanted to increment by 2 ?  Is there a short cut ? Java always has the answer 🙂 The syntax for that would be count += 2 . Make sure you don’t give a gap between + and equals . It is a special operator and has to be used that way only.

[java title=”Program Snippet” gutter=”true” highlight=”2″]

for (int count = 0 ; count < my_first_name.length; count += 2 )

[/java]

asdf

Question 18 : Write the program in such a way that you count from the back and start copying characters from the end to the beginning by using a for loop and the  -= operator.

Blocks

Anything between 2 curly braces is called a block. Blocks are used to segregate chunks of code. It could be any number of lines.  This program wouldn’t even compile.  A block is more like a girl friend. You wouldn’t know what she is until you marry her ( go inside the block ). Just stop assuming that you know your boy girlfriend (delete line No.9 ) and the program will compile) We will discuss more on this in another section where we discuss variable scope.

[java title=”Blocks Program” gutter=”true” highlight=”9″]

public class HelloWorld {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String boyfriend= "John";
System.out.println("I think I know my girlfriend. Her name is = " + girlfriend);
{
String girlfriend= "Mary";
System.out.println ("I know my boyfriend for sure. His name is " + boyfriend);
}
System.out.println ("Now, I realize – I don’t know my girlfriend – says the boyfriend" + boyfriend);
}
}
[/java]

Strings

Know more about Java String , Java StringBuffer and Java StringBuilder here.

Question : Is boolean the same as integer ? Which of the following lines will error out during compilation ?

[java title=”Program Snippet” gutter=”true” highlight=”7-12″]

public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean bool1 = true;
boolean bool2 = false;
boolean bool3 = 0;
boolean bool4 = 1;
boolean bool5 = TRUE;
boolean bool6 = FALSE;
}
}
[/java]

Question : Which of the following primitive data types can be used to represent the value of pi (3.14159 ) upto 5 decimals ?

  • int
  • float
  • double
  • long

Question : Write a Java program to print out the odd numbers between 10101 to 23433.

Question : Write a Java Program to calculate the summation of all integers from 1 to 100 . ( 1+2+3+…..+100 )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s