ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Basics of the java language

Updated on December 6, 2016

Java language basics

Java is a powerful, cross-platform, object-oriented programming language suitable for writing anything from a distributed application that runs on a corporate network to a database-driven Web site to host your personal photo gallery. To make it easier to learn, the Java language was designed to resemble some of the most popular programming languages in use today, most notably C/C . If you're not a C/C expert, however (and most Web developers aren't), the language can be a little intimidating. In this article, I'll bring you up to speed on the basic syntax of the Java language, including variables, data types, operators, and control structures.

This article is the second in a series teaching the Java programming language with an eye towards its application to Web design and development. Specifically, the goal of this series is to teach you all you need to know to create dynamic Web sites using JavaServer Pages (JSP) and Java Servlets. This article picks up right where the previous article in the series, Getting Started with Java, left off.

Variables

Here is the listing for the program I helped you create in the previous article:

1  /**

2   * Hello.java

3   * A simple Java program

4   */

5

6  class Hello {

7    public static void main(String[] args) {

8      // Print a couple of one-line messages

9      System.out.println("Hello, World!");

10     System.out.println("This is a test.");

11   }

12 }

This is an exceedingly simple program, as Java programs go, and I'm sure you don't need me to tell you that it's quite useless. What good is a program that prints out the same two lines every time you run it? At the very least, a program should perform some kind of useful calculation, right?

To be able to perform calculations and do useful work, a program must be able to manipulate data in some fashion. Like most programming languages, Java lets you store data in variables. A variable may be thought of simply as a named location in memory where data may be stored. Since different kinds of data may have different storage requirements, Java requires you to specify a data type for every variable that you create.

Let's look at a basic example to help solidify this concept in your mind. Say you were writing a program that was performing temperature calculations for a laboratory experiment. Many such experiments take the room temperature into account in their calculations, so your program might need to store the room temperature in a variable. The following code creates a variable for storing whole numbers called roomTemp, and then assigns it a value of 20:

int roomTemp;     // Create integer variable

roomTemp = 20;    // Assign the variable a value of 20

For the Americans in the audience who are used to seeing temperatures in Fahrenheit, 20 degrees Celsius is 68 degrees Fahrenheit. int stands for integer (programming lingo for a whole number), and is the data type of the roomTemp variable. So as you can see, creating a variable is as simple as typing the data type followed by the name of the variable. Variable names in Java, like methods (as we saw in the previous article), are not capitalized by convention, but it's okay to use uppercase letters within the variable name to make them more readable. This is why I chose to name the variable roomTemp, instead of RoomTemp or roomtemp, or some other variation on the theme.

The second line assigns a value to the variable that was just created; specifically, it stores the number 20 in the variable. The equals sign (=) is called the assignment operator because it is used to assign values to variables. During the course of this article, you'll meet many other operators that do other weird and wonderful things to variables and the values they store.

You must always create a variable before assigning it a value, and you'll usually want to assign the variable a value before putting it to use. Trying to assign a value to a variable that does not exist will cause the Java compiler spit out an error message when you try to compile your program. Rather than automatically creating the variable for you, as some other programming languages do, Java errs on the side of caution by assuming you mistyped the name of the variable. This helps avoid bugs due to simple typing mistakes.

A newly created variable does not have a value. For example, until we assigned it a value of 20, one might assume that the roomTemp variable had some default value, such as zero. In fact, it did not. A variable with no value is said to be null. If you have trouble getting your head around something having no value at all, you could instead think of null as a special value that is assigned to all newly created variables, no matter their data type. Attempting to use a null variable as if it contained a value is one of the most common types of programming mistakes that cause programs to crash. That goes not only for Java programs, but also for programs written in other languages such as C/C .

A shortcut exists for creating a variable and assigning it a value on the same line. The following code is equivalent to the two lines we saw above:

int roomTemp = 20;     // Create variable and assign value

Once created and assigned a value, a variable may be used anywhere the value it contains might be used. Let's look at a simple program that prints out the room temperature as stored in a variable. Open your text editor and type the following (remember, don't type the line numbers), then save the file as PrintRoomTemp.java:

1  /**  

2   * PrintRoomTemp.java  

3   * A simple Java program that prints out the temperature  

4   */  

5    

6  class PrintRoomTemp {  

7    public static void main(String[] args) {  

8      int roomTemp = 20; // Room temperature  

9    

10     // Print out the temperature  

11     System.out.print("Current room temperature: ");  

12     System.out.print(roomTemp);  

13     System.out.print(" degrees Celsius\n");  

14   }  

15 }

This program is a lot like the Hello program we saw above, with a few notable exceptions:

  • Line 8: The first thing this program does is to create a variable called roomTemp and assign it a value of 20.

  • Lines 11-13: In Hello, we used System.out.println(...) to print messages on the screen a line at a time. In this program, we have used System.out.print(...) instead. The only difference between these two commands is that println prints a line break at the end of its output, so that the next character to be displayed on the screen will appear at the start of the next line. print doesn't add this line break, so several print commands may be strung together to print a single line on the screen.

  • Line 12: This is an example of using a variable where a value would normally be expected. Everywhere else that we've used print or println, we've fed it a string of text (surrounded by double quotes) as the exact value to be printed out. In this case, we've given it a variable name instead. For the print command to know what to print out, it has to look inside the variable for the value stored within. So this line just prints out whatever value is stored in the roomTemp variable at the time.

  • Line 13: Since this print statement represents the end of the line of text that we want to display, you could use a println instead to output the requisite line break. Instead, I elected to stick with a print statement to demonstrate how to output a line break without using println. Notice that the text string to be printed out by this line ends with \n. This is a special character code that, when printed out by Java, gets converted to a line break. If a situation arises where you want to actually print out a backslash followed by the letter 'n', you must prefix your backslash with a second backslash (i.e. "\\n"). The first backslash cancels the special meaning of the second. In other words, \\ is a special character code that gets converted to a single backslash when printed out, so Java no longer sees the \n as a special character code.

Compile the program as usual by typing javac PrintRoomTemp.java at the command line, and then, assuming the compiler didn't point out any typing errors, run the compiled version of the program:

D:\java\JavaLanguageBasics> java PrintRoomTemp

Current room temperature: 20 degrees Celsius

Although there were a few new tricks in this program, its main purpose was to demonstrate how to use a value stored in a variable. In this case, we printed the value out, but as you'll see in later examples, variables can be used in many other ways as well.

Data Types

In the previous example, we identified the roomTemp variable as being of the int data type, meaning that it could store integer (whole number) values. Now let's say you keep your laboratory a little warmer than most, so you wanted to record a temperature of 22.5 degrees. You might modify line 8 of PrintRoomTemp.java so that it read as follows:

    int roomTemp = 22.5; // Room temperature

If you tried to compile this modified program, however, you would see an error message much like this one:

D:\java\JavaLanguageBasics>javac PrintRoomTemp.java  

PrintRoomTemp.java:8: possible loss of precision  

found   : double  

required: int  

   int roomTemp = 22.5; // Room temperature  

                  ^  

1 error

Java is telling you that the int data type can't store the value 22.5, and that you should instead use the double type, which is the Java data type for storing floating point numbers (numbers requiring a decimal point). The message "possible loss of precision" refers to the fact that the int data type could store 22 or 23, but not 22.5; that is, int does not provide the level of precision required to represent the value you're trying to store.

So to allow for precise temperature values, you need to declare the roomTemp variable as a double instead of as an int:

    double roomTemp = 22.5; // Room temperature

Try this corrected line in your program, and you should see the expected output.

Java provides a handful of data types for use in your programs. Here's the complete list for the technically minded:

  • boolean: true or false

  • char: a single 16-bit Unicode character

  • byte: an 8-bit signed integer

  • short: a 16-bit signed integer

  • int: a 32-bit signed integer

  • long: a 64-bit signed integer

  • double: a 64-bit floating point number

In case you're wondering what the number of bits means for these various data types, basically the more bits a data type uses, the more different values it can store. Thus, long variables can store larger numbers than int variables, and double variables can store more precise values than float variables. In most programs you'll be able to get by using int, double, and boolean (of which we'll see some examples in a moment). The other types are reserved for special cases, or instances where you want to squeeze as much performance as possible out of the language by storing values in memory with as few bits as possible.

Some readers might wonder how we can store a string of text in a variable if there is no data type. The char data type lets you store a single character... does that mean that Java forces you to split up strings of text into characters when storing them in a variable? Certainly not!

You may remember that I mentioned in the previous article that Java programs are built by combining software components (also known as classes) to create the required functionality. As I'll show in detail in the next article in this series, classes are similar in many ways to data types. In addition to letting you define your own classes, the Java language provides a number of built-in classes, one of which is the String class. The String class is actually quite special, as it is the only class in the Java language that shares certain properties with the basic data types shown above. In fact, many Java programmers get so used to using the String class as if it were a data type that they forget that it isn't!

If that last paragraph just sailed straight over your head, don't worry too much -- classes in general and the special case of the String class will be discussed in greater detail in the next article in this series. In the meantime, all you need to know about the String class is that it can be used just like the data types we've seen so far:

String myName;  

myName = "Kevin Yank";  

 

String companyName = "SitePoint.com";  

 

System.out.print(myName);  

System.out.print(" works for ");  

System.out.println(companyName);

The above code will print the message "Kevin Yank works for SitePoint.com". The only detail that you should be especially careful about is to spell String with a capital letter. While all true data types are written in lowercase letters, String is a class, and as such it must be capitalized. The Java compiler will display an error message if you type it wrong.

Operators

As I said above, any program that does anything useful will likely have to perform some kind of calculation, or manipulate information in some way or another. So far we've seen how to define pieces of information and store them in variables in preparation for that work to be done. In this section, I'll introduce some of Java's operators. Using operators you can take simple values (like numbers and strings of text) and perform operations on them (like addition, subtraction, or concatenation).

int a, b, c; // Three integer variables    

a = 10;      // Assigns value 10 to a    

b = 10 1;  // Assigns value 11 to b ( is addition)    

c = b - a;   // Assigns value 1 to c (- is subtraction)    

a = b * 3;   // Assigns value 33 to a (* is multiplication)    

c = a / b;   // Assigns value 3 to c (/ is division)

As a side note, you may have noticed that I used another shortcut on the first line of the above block of code to create three integer variables (a, b, and c) in a single statement. That one line could be expanded to the following, and it would work exactly the same:

int a;

int b;

int c;

Getting back to these operators, notice how I used the symbols , -, *, and / to perform addition, subtraction, multiplication, and division respectively. These symbols are arithmetic operators. Notice also that operators may be used on literal values (10 1), variables (b - a), or both (b * 3).

Another arithmetic operator that is less commonly used is the modulus operator:

c = b % 3;   // Assigns value 2 to c (% is modulus op.)

The modulus operator gives the remainder of an integer division. In this example, the value stored in b (11) divided by three is 9 with a remainder of 2 -- this remainder is the value calculated by the % operator.

You can perform multiple operations in a single statement, if you want to. Note that arithmetic operations obey the same rules of precedence as they do on a scientific calculator: multiplication and division first, followed by addition and subtraction. Of course, we can use parentheses to change this if we want:

a = 1 2 * 3;   // a = 7    

b = (1 2) * 3; // b = 9

Recall that variables don't have to contain numbers. They can also hold strings of text... and operations can be performed on strings as well:

String name = "Kevin";

System.out.println("Hi " name ", how are you today?");

The code above displays the message Hi Kevin, how are you today? Notice how the operator, which is used to add numbers together, can also be used to stick strings of text together (in other words, concatenate strings). Used in this context, is called the string concatenation operator. Notice also that we've used the result of the expression "Hi " name ", how are you today?" as the value to be printed out by the println command. Nothing says we must store the result of an arithmetic calculation or other operation in a variable; as the example above shows, if we only need the value in one place we can simply type the expression where we need it.

Another family of operators is called the comparison operators. As their name suggests, these operators are used to compare different values together. While the arithmetic operators produce results that are numbers (usually int or double, depending on the data types that went into the operation) and the string concatenation operator produces String's, the comparison operators produce boolean values (i.e. either true or false). As before, some examples should illustrate this effectively:

// From above: a = 7, b = 9, and c = 2    

   

boolean d, e, f; // Three boolean variables    

d = (a == 7);    // d = true (== tests equality)    

e = (a == b);    // e = false (a doesn't equal b)    

f = (a != b);    // f = true (!= tests inequality)    

d = (a > 0);     // d = true (a is greater than 0)    

e = (b < 6);     // e = false (b is not less than 6)    

f = (c >= 2);    // f = true (c is greater than or equal to 2)    

d = (c <= 1);    // d = false (c is not less than or equal to 1)

As shown here, the comparison operators are ==, !=, >, <, >=, and <=. Most of these operators only really make sense when applied to numbers (or variables containing numbers). One might expect, however, that == (test for equality) and != (test for inequality) would work on String values, when in fact they don't. While you won't get an error if you try to compare strings using these operators, you'll quickly discover that == will always turn out false (whether the string are the same or not), while != will always give a true result. The reason for this, however, will have to wait for our next article, where I'll explain objects and classes in all their glory.

You might be wondering about the practical uses of these comparison operators. In fact, they are essential when it comes to making your program do different things under different conditions. To accomplish such a feat, however, you'll need one more tool in your belt: control structures.

Control Structures

Don't let the name scare you; control structures aren't as complicated as they sound! Both of the simple programs and all of the examples we've seen so far have had one thing in common: they've executed in a straight line, a statement at a time, from top to bottom. In simple terms, control structures let you break out of that straight-line mould, allowing your programs to react differently to different conditions and saving you some typing when performing repetitive tasks.

Let's start with the most basic control structure, an if statement:

if (condition) statement;

If the condition is true, then Java will execute the statement. If not, nothing happens and Java just moves on to the next line of the program. Here's a simple example:

// Check if a and b are equal

boolean abEqual = (a == b);

if (abEqual) System.out.println("a and b are equal!");


This is the practical application of the comparison operators that I promised above! The first line of the above (after the comment) checks if a and b are equal (that is, if they contain the same value). If they are, abEqual is assigned a value of true. If not, abEqual is set to false. On the second line, we have an if statement that uses abEqual as its condition. As you can see, if a and b are equal (and thus abEqual is true), the program prints out a message to that effect. If not (and abEqual is false), then nothing happens.

Since most conditions are only used once, it is more common to type the conditional expression directly in the if statement, instead of using a variable. Here's how the above example would normally look:

// Check if a and b are equal

if (a == b) System.out.println("a and b are equal!");


As always, use whichever method you are most comfortable with. Here are a few more examples of comparison operators in action as part of if statements:

if (a > b) System.out.println("a is greater than b");    

if (a < b) System.out.println("a is less than b");    

if (a >= b) System.out.println("a is greater than or equal to b.");    

if (a <= b) System.out.println("a is less than or equal to b.");    

if (a != b) System.out.println("a does not equal b");

Instead of a single statement, you can specify a whole series of statements that should be executed if the condition is true. You do this by putting the statements between braces:

if (userIsKevin) {    

 System.out.println("Hi, Kevin!");    

 // ... more statements here ...    

}

If you want to do something when a condition is false instead of when it is true, there is a handy shortcut you can use. Here's how the code might look without using the shortcut:

// Print message when myCondition is false    

if (myCondition == false) {    

 System.out.println("myCondition is false!");    

}

The == operator (and the != operator) can be used on boolean values as well as numeric types. As a result, the condition above will be true when myCondition is false, and false when myCondition is true. The shortcut I mentioned involves something called the negation operator. By placing this operator (!, an exclamation mark) before a variable name or before a set of parentheses containing an expression, the value of that variable or expression will be flipped from true to false (and vice versa). Thus, the above example could be more simply written as follows:

// Print message when myCondition is false    

if (!myCondition) {    

 System.out.println("myCondition is false!");    

}

If myCondition is true, the ! operator will cause the condition to evaluate to false so the message will not be printed. If myCondition is false, the ! flips the expression's value to true and the message does get printed. It's important to note that the ! operator doesn't actually change the value that is stored in myCondition; it just alters the value of the condition for the purposes of the if statement.

Another control structure that is related to the if statement is the if-else statement:

if (condition) {    

 // statements to be executed if condition is true    

}    

else {    

 // statements to be executed if condition is false    

}

In this case, one group of statements or the other will be executed. The condition determines which. Each of the bracketed sets of statements could also be a single statement instead. In fact, by using another if-else statement in place of the second bracketed block of statements, you can test multiple conditions and perform an action depending on which of the conditions is true:

if (condition1) {    

 // do this if condition1 is true    

} else if (condition2) {    

 // do this if condition2 is true    

} else if (condition3) {    

 // do this if condition3 is true    

} else {    

 // do this only if none of the conditions is true    

}

This code structure may be a little overwhelming at first glance, but reading it aloud helps to make its operation pretty self-evident. Here's the code above, as it might be expressed in English:

If condition1 is true, execute the first block of statements. Otherwise, if condition2 is true, execute the second block of statements. Otherwise, if condition3 is true, execute the third block of statements. Otherwise, execute the final block of statements.

The rest of the control structures that I'll discuss in this article have to do with making your program perform the same operation several times without having to type the commands for that operation over and over again. These structures are normally called loops.

Loops

The first type of loop is called a while loop. Its name suits its function: to do something over and over again while a condition remains true. Here's what a while loop looks like:

while (condition) {      

 // a block of commands (the loop body)      

}

The operation of a while loop is best illustrated by the flowchart in Figure 1.

In most cases, the condition for a while loop will be something that starts off being true, but eventually will change to false after the block of commands has been executed a certain number of times. Here's a simple program that uses a while loop:

1  /**      

2   * Countdown.java      

3   * A simple Java program that counts down from 10.      

4   */      

5        

6  class Countdown {      

7    public static void main(String[] args) {      

8      int count = 10;      

9      

10     System.out.println("Countdown to liftoff...");      

11     while (count > 0) {      

12       System.out.println(count "!");      

13       count = count - 1;      

14     }      

15     System.out.println("Liftoff! We have liftoff!");      

16   }      

17 }

Here's the breakdown of this program:

  • Line 8: We declare a variable called count with a value of 10.

  • Line 11: A while loop that will continue for as long as count is greater than 0.

  • Line 13: Subtract 1 from the value stored in count.

So when the program first gets to the while loop, count is 10 so the loop body is executed, printing out "10!" and then subtracting 1 from the value stored in count. The condition is then checked again. 9 is still greater than zero, so the loop body is executed once more ("9!"). This continues until the 10th time the loop body is executed ("1!"), when subtracting 1 from count brings its value to zero. Now when the condition is checked it is false; thus, the loop stops and execution continues following the loop.

Here's what you should see when you compile and run this program:

D:\java\JavaLanguageBasics> java Countdown      

Countdown to liftoff...      

10!      

9!      

8!      

7!      

6!      

5!      

4!      

3!      

2!      

1!      

Liftoff! We have liftoff!

while loops are very handy, but there are two limiting cases you should be aware of:

  • If the condition is false to begin with, the loop body won't be executed at all.

  • If the condition stays true forever, the program will execute the loop over and over and will never stop.

While the first case has its uses, the second case is something to be careful of. A loop that never ends is called an infinite loop. Infinite loops can happen under the most unexpected circumstances, and are a surprisingly common mistake that even experienced programmers sometimes make. If one of your programs ever seems to get 'stuck' and just stops responding, chances are good that it's gotten stuck in an infinite loop. You can regain control by pressing Ctrl-C, which will interrupt the program, forcing it to stop. Of course, an infinite loop in a program like the one above would be fairly obvious, since the println statement within the loop would cause the program to print out an endless stream of numbers. To see what this would look like, just change the condition for the while loop on line 11:

11     while (true) {

Don't worry; it won't hurt your computer. It might make you a little dizzy, though!

for loops

The final control structure we'll be seeing in this article is actually just a more advanced version of a while loop, called a for loop. The relatively complex syntax tends to scare away beginners; additionally, the fact that any for loop can also be written as a while loop makes it especially tempting to simply not use this particular control structure. Nevertheless, the for loop provides a nice shortcut for the most common application of while loops, so in my opinion it's worthwhile learning. Here's what the syntax looks like:

for (initialize; condition; update) {      

 // loop body      

}

In the above, initialize is a statement that is executed once, just before the condition is checked for the first time. It is usually used to set up a counter variable for the loop. condition is simply the condition that determines when to stop executing the loop (it works exactly the same as the condition in a while loop). Finally, update is a statement that will be executed after the loop body and before the condition is re-checked. It is commonly used to update the counter variable. Figure 2 illustrates how a for loop works.

To demonstrate a for loop in practice, I've adapted the Countdown program above to use a for loop instead of a while loop:

1  /**      

2   * Countdown.java      

3   * A simple Java program that counts down from 10.      

4   */      

5        

6  class Countdown {      

7    public static void main(String[] args) {      

8      System.out.println("Countdown to liftoff...");      

9      

10     for (int count=10; count>0; count=count-1) {      

11       System.out.println(count "!");      

12     }      

13      

14     System.out.println("Liftoff! We have liftoff!");      

15   }      

16 }

The actual code used by this program is not so different from the original version with the while loop! The creation and initialization of the count variable has become the 'initialize' statement in the for loop, while the command from the loop body that subtracts 1 from the value of the count variable has become the 'update' statement. The condition and the remaining line of the loop body remain unchanged. What a for loop lets you do is combine all of the commands having to do with the initialization, checking, and updating of the counter variable (count, in this case) into a single line, making the code in general easier to read.

Even though any for loop could be expanded out into a while loop with the appropriate statements before the loop and at the end of the loop body, it is common practice (and generally tidier) to express any loop that uses a counter variable as a for loop.

Summary and Further Reading

We've covered a lot of ground in this article; it's a shame most of it had to be so dry!

We looked at how variables let you store data for use in calculations, how that data can come in the form of a handful of data types, what operators are available for putting pieces of data together and getting a result, and what control structures let you make programs that do something other than go in a straight line. Unfortunately, these are by far the least exciting aspects of any programming language; so if I've bored you, I apologise.

The good news is that I've now covered most of the mundane details of the Java language, and you should now be ready to make the leap into the world of object-oriented programming! It's no coincidence, then, that the next article in this series will cover the concepts of object oriented programming and how they apply in Java. And I'll finally answer the Big Question: how can you compare two Strings together to see if they match? Don't tell me you're not dying to know!

If you're keen to get a head start, the book "Beginning Java Objects" from WROX Press is an excellent read that will have you weaving webs of Java classes like a pro. Look for a review around the same time as the next instalment in this series!

Thanks to Kevin Yank for making it clear.

Java Books

Good Java Books

Java Books

Books on Java

Comments

Submit a Comment

No comments yet.