Java Tutorial: More Basics
More basics
Before we continue we better go through a few basics. As mentioned they are basics but very often forgotten basics amongst newbies.
- Each expression ends with a semicolon (;).
- Java is Case-Sensitive.
- Floating point literals: Use of point (.) for example 1.456.
- Char-literals: Use of single quotation mark ' for example 'M'.
- String-literals: Use of double quotation marks " for example "ABC".
- Comments: single line comments (// foo), multiple line comments (/* foo*/).
- Outside of your class declarations, only package and import instructions, and comments are allowed.
- A program can contain multiple class declarations.
- A source-code file can only contain one public class declaration, and the class name has to coincide with the filename.
- Modificator "static" in methods means: method can be used without instantiation.
JDK installation
Linux users, you need to download and install the following packages: "jdk" and "jre" (most of you have the jre package installed already). Windows users need to download the JDK from Sun's Java website, install, and then configure the JDK with PATH- and CLASSPATH- variables(try a google search). Personally i recommend using Eclipse as the IDE, but if you want to try out Netbeans or some other application thats fine. Eclipse is available from your distrobutions repository, or you can download the installer (Mac, Win, Linux) from their website. I wont be covering a tutorial in how to use these IDE's, I will only briefly explain how to do this from CLI.
- Open up your editor of your choosing (VIM, Notepad, Eclipse, Netbeans, etc) and write your source code.
- Save the file with java sourcecode file extension (MyClass.java)
- Open up your CLI (command in windows, terminal in GNU/Linux) and go to the folder where your saved your file.
- Now its time to compile your class, type "javac MyClass.java" and a class-file will be generated (its called the same as the .java file but with .class extension instead) in the same folder.
- Type "java MyClass" (without extensions) and your application will run.
Dont forget to recompile your source code file everytime you make a change, and remember that Java is case sensitive (also when it comes to running and compiling).
Different kinds of datatypes
Java behaves much like a C or C++ program, and each variable has to be declared before you can use it. These kinds of languages are called strongly-typed languages, and java have 8 different kinds of primitive data types.
- byte (defaults: 0): The
bytedata type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). Thebytedata type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place ofintwhere their limits help to clarify your code; the fact that a variables range is limited can serve as a form of documentation. - short (defaults: 0): The
shortdata type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As withbyte, the same guidelines apply: you can use ashortto save memory in large arrays, in situations where the memory savings actually matters. - int (defaults: 0): The
intdata type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, uselonginstead. - long (defaults: 0L): The
longdata type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided byint. - float (defaults: 0.0f): The
floatdata type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations forbyteandshort, use afloat(instead ofdouble) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings coversBigDecimaland other useful classes provided by the Java platform. - double (defaults 0.0d): The
doubledata type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. - boolean (defaults: false): The
booleandata type has only two possible values:trueandfalse. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. - char (defaults: '\u0000'): The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. The default value is "null".
Variables
In Java, we need holders to store our data during program execution. Variables are those holders. Variables are used in a Java program to contain data that changes during the execution of the program. Before we use a variable, we have to notify the name and type of variable to the compiler so compiler reserves space for it in the memory. The variables can also be initialized while being declared. Syntax of declaring variable is simple:
String myString; // one declaration boolean isMine, areYours; // two declarations of the same sort double myDouble = 1.0; // declaration and initialization int myInt1, myInt2 = 2; // two declarations, and both are initialized with the same number
Arrays
An array is simply a sequence of memory locations for storing data set. All elements of an array has to be of same data type. For instance, an int array can onle store int values. Elements of arrays are approached through index. In Java, index of an array starts with 0 (sequence is 0,1,2,3,4...n where n is the size you declared to be max). Arrays in Java are of finite size. So while declaring, you have to mention their size(n as mentioned earlier). You cannot change the size of an array at runtime. But you can copy contents of an array to other at run time. Java also allows declaration and usage of multi-dimensional arrays. These are very useful in complex calculations like matrixes.
int[] myIntArray = new int[10]; // initializes a int array with size of 10 int[][] myMultiDimIntArray = new int[5][10]; // initializes a multi-dimensional int array with sizes 5 and 10.
Java Programming – Assignments
There are many assignments operators in Java programming language. In the Java programming tutorial, I will cover each one.
Post-fix-notation : x++
Pre-fix-notation : ++x
x+=y is equal to x=x+y
x-=y is equal to x=x-y
x/=y is equal to x=x/y
x*=y is equal to x=x*y
Java Programming – Logical Operators
Following are logical operators that one can use in Java programming.
! Is not…
^ Exclusive Or…
| Or… (bitwise)
& And… (bitwise)
|| Or… (short cut, see &&)
&& And
In this Java programming tutorial, I will code And, Or and Not operators as they are commonly used.
Example:
int a= 15; int b = 25; if(a < 10 || b > 10) { System.out.println("Java sure is fun!"); } else System.out.println("Java isnt fun at all :(");
Output:
Java sure is fun!
In the given example, first condition is false as a is less than 10 but second condition is true as b is greater than 10. So if condition as a whole is true and we get the output:
Java sure is fun!
Example:
int a= 15; int b = 25; if(a < 10 && b > 10) { System.out.println("Java sure is fun!"); } else System.out.println("Java isnt fun at all :(");
Output:
Java sure is fun!
For ‘and’, both conditions should be true. In the given example, first condition if false and the second condition wont even be checked, as it wont make any difference.
This Java programming tutorial will also cover control structures.
Java Programming – Control Structures
if statement
- if – else statements can be nested
- else-branch is not mandatory
- If there is only one statement, brackets can be omitted
- there is no semicolon after the if or else statement
if(a>10) { System.out.println("a > 10"); }
switch statement
Few points about switch statement:
- Actually a shortcut of several if-statements
- Restricted to int or lower order data types
- default is optional
- If more than one statement desired you have to use a block, i.e.{statement1; statement2;...}
- Without break: after match all cases until the next break or end of switch would be executed (fall through)
- Sometimes fall-through is intended, but there should be a comment saying that
switch (a){ case 1: System.out.println("JavaProgramming: 1"); break; case 2: System.out.println("JavaProgramming: 2"); break; default: System.out.println("JavaProgramming: Default"); }
while and do while loops
While and do-while loops are very similar. While loop is executed 0 to n times where as do-while loop is executed 1 to n times.
- while-loop is a repelling loop,i.e. loop-condition is checked before every loop-cycle, whereas
- do/while-loop is an accepting loop, i.e. loop-condition is checked not until end of the loop
- You can omit the brackets if you have just one statement
- while and do/while-loops can be transferred into another
- While and do/while-loops can be nested
- Observe: end of do/while is marked by a semicolon
Example while loop:
int num = 2; int start = 1; int end = 10; while(start < = end) { System.out.println(num + " * " + start + " = " + (num*start)); start++; }
Output:
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Example do while loop
int num = 0; do { System.out.println("I am doing Java Programming"); num--; } while(num>1);
Output:
I am doing Java Programming
for loop:
for loop is usually used to go through an array or some data structure.
- for-loop is a special while loop
- for-loop is repelling too
- Brackets can be omitted if just one statement
- for-loop can be nested
- In the first and last part of a for-loop you can write a comma ','
- you can declare multiple variables or write several expressions
Example:
int num = 2; int end = 10; for(int start = 1; start < = end; start++) { System.out.println(num + " * " + start + " = " + (num*start)); }
(The space between < and = isnt supposed to be there.. stupid wordpress)
Output will be the same as in while loop example.
Thats it for this time, I hope you learned something. In the next tutorial I'll talk about objects and maybe some generics. Feel free to leave a comment down below about what you thought about this tutorial.
Related posts: