By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,635 Members | 2,174 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

A quick introduction to Java concepts 1

10K+
P: 13,264
Setting up.

Getting started

To get started with java, one must download and install a version of Sun's JDK (Java Development Kit).
The newest release at the time of writting this article is JDK 6 downloadable from

http://java.sun.com/javase/downloads/index.jsp.

I will be using JDK 5(update 8)
but will in most cases will provide code that works on JDK 1.4 compilers as well.
I will also test some of the code on a 1.6 compiler.

The Java Development Kit

This is the tool that java programmers work with.
The chief components of the JDK are the following programming tools
javac - The compiler, which converts java source code(.java files) into Java bytecode(.class files).
java - This executes the java class files. It launches the Java application.
appletviewer - runs and debugs applets without the need of a web browser.
jar - The Java archiver, which packages related class libraries (and other files) into a single JAR file.
This is the executable for java programs.
javadoc - This tool generates documentation using comments in the source code.
jdb - The debugger

The JDK includes the (JRE) Java Runtime Environment. This consists of a Java Virtual Machine and the class libraries that will be present in the production environment including additional libraries useful to developers.

Setting the class path.

After successfully downloading and installing the JDK you need to set the class path.
By default the packages of the JDK standard API are accessible without needing to set the path.
Only the path for user-defined packages and libraries must be set either in the command-line or in the Manifest associated with the Jar file containing the classes(The second approach will
be revisited when we get to jar files).
How to set the class path depends on the operating system you are using.
You can get information on how to set class path for your OS version here

http://java.sun.com/j2se/1.5.0/docs/...classpath.html


The following article is a comprehensive discussion on the class path.
http://mindprod.com/jgloss/classpath.html



We will also revist the set up later when we have seen some of the JDK tools in action.

You will want to use an interface program like TextPad, JCreator, notepad++, etc for writting your code.
It is important to choose a tool you understand well. There are also IDEs like Netbeans(Available on the Sun site), however, you will want to use these only after you are fully conversant with the basic features of the language first.


Compiling Java code.

As mentioned earlier the javac tool is the one you use to compile Java classes. You invoke it by typing javac FileName.java on the prompt. If you are using a program like TextPad you simply click the compile java button and the tool is invoked. If the code does not have any errors, javac produces a class file called FileName.class for the above example. If the code has errors, they will be shown on the command prompt.

It is not neccessary to have a public class definition in a file. In this scenario, the file’s name should be different from the names of classes and interfaces which should not be public. In other words, files with no public classes can have a name that does not match any of the classes in the file.
This is because at most one public class definition is allowed per file.
The name of this class should match the file name. If there are more than one public class definitions, the compiler will accept the class with the file’s name and give an error at the line where the other class is defined. A blank file compiles without error (is a valid java source file).

javac error messages

Compilation errors are very important to a programmer. If the compiler outputs an error message during compilation, the class file is not produced. Compilation errors include a line number where the error has occured.
This should be very helpfull if your interface program has line numbers (a good interface program should have them and you should have them always enabled). When asking for help (eg in java forum always include the error message).

The next part will cover java basics and will contain java programs. So be sure you can compile and run java programs on your machine.


Java Basics

The approach in these articles is to get to program writting as soon as possible and then expand on the salient features of programming later on. One can easily understand those features if one has had some experience with writting programs.

Language structure

The Java programming language is a high level object-oriented language which is class-based and has support for concurrency. It is also strongly typed i.e it distinguishes between compile-time errors
(that can and must be detected at compile time), and run time errors (exceptions) that occur at run time.
The language is case sensitive and free-form(statements can reside anywhere on a line, cross over lines or any number of blank spaces are allowed between tokens)
Statements are terminated by a semi-colon ( ; ). A java file consisting only of semi-colons is a valid java source file.
For a java application to run, the class being run must contain the main method with the following signature:
Expand|Select|Wrap|Line Numbers
  1. public static void main(String[] args)
or(as of 1.5)
Expand|Select|Wrap|Line Numbers
  1. public static void main(String ... args) 
The order of public and static may be interchanged.

Key words

As of jdk 1.5, the following is the set of java keywords.
{abstract, continue, for, new, switch, assert, default, if,
package, synchronized, boolean, do, goto, private, this, break,
double, implements, protected, throw, byte, else, import, public,
throws, case, enum, instanceof, return, transient, catch, extends,
int, short, try, char, final, interface, static, void, class,
finally, long, strictfp, volatile, const, float, native, super, while}

const and goto are reserved, even though they are not currently
used. We will look at the other keywords later on.

Primitive types

Java has the following eight primitive types:

boolean, byte, short, char, int, long, float and double.

You should have a table of their
minimum, maximum and initial values with you.
Literals have their size checked at compile time.
Expand|Select|Wrap|Line Numbers
  1. byte b = 128; //will not compile (Maximum value of byte is 127) but
  2. byte c = 127; //will compile
All numeric data types are signed except char, which is the only unsigned integral type.

Literals

For now I will say a literal is a value of a primitive type (source code representation) or null or the String type(This will be examined in the later).
Literals are not keywords. i.e null, true, false etc are not keywords.

Unicode

It is wise to learn a bit of unicode if you want to become a serious programmer.
For now I will say that unicode characters can appear anywhere in java code. They are prefixed by \u and are four characters long. e.g "a" is represented by \u0061. You can substitute "a" with "\u0061"
in your code and it will still compile. Thus the following are equivalent:
Expand|Select|Wrap|Line Numbers
  1. boolean b = true;
  2. boole\u0061n b = true;
They are hexadecimal characters (0-F).

Separators

The following nine ASCII characters are the separators (punctuators):

( ) { } [ ] ; , .

Operators

The complete set of operators is:
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>>=

Arithmetic operators - *, /, %, +, - can be applied to numeric types only (at least int) except + which can also be applied to String literals.

Extended assignment operators and ++, -- operators perform implicit type casting.
Expand|Select|Wrap|Line Numbers
  1. byte a = 12;
  2. a = a + 1;
Will not compile int is required for + operator but
Expand|Select|Wrap|Line Numbers
  1. byte a = 12;
  2. a++;
Will compile because the ++ does an implicit type cast

Note that
Expand|Select|Wrap|Line Numbers
  1. byte b = 127;
  2. b++;
  3. System.out.println(b);
Will print -128 (smallest byte). This is because there are no overflow/underflow errors in java but the values simply wrap around (silently).

The operators && and || are short circuit logical operators. If the value of the first operand is sufficient for determining the value of the whole expression, the right hand side is not evaluated.
Expand|Select|Wrap|Line Numbers
  1. boolean s = true;
  2.     boolean t = true;
  3.     if((t = false) && (s = false) ) {
  4.         ;
  5.     }
  6.     System.out.println(t);
  7.     System.out.println(s);
Prints
Expand|Select|Wrap|Line Numbers
  1. false
  2. true
t was changed but s was not changed because the (s = false) part was not executed.

You should experiment with the rest of the operators especially the shift operators to understand their functions.
You should also be aware of the associativity of each operator.
eg
Expand|Select|Wrap|Line Numbers
  1. System.out.println( 1 + 2 + "3" ); // Prints 33
  2. System.out.println( "1" + 2 + 3 ); // Prints 123
Because + is left to right associative.

We will look at the instanceof operator after we've covered inheritance.


Identifiers

Identifiers are the names you give to your variables. A java identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.An identifier cannot have a name of a Java keyword, or be a literal.
Embedded keywords or literals are allowed

Java types.

Every variable and every expression has a type that is known at compile time(strongly typed).
There are two broad types in Java: Primitive types and reference types.


Type : PrimitiveType, ReferenceType

PrimitiveType : NumericType, boolean

ReferenceType : Class, Array, Interface

NumericType : IntegralType, FloatingPointType

IntegralType : int, long, char, byte, short

FloatingPointType : float, double


That's all I'll cover now for primitive types. Up next is the Class type.


The Java Class

What is a class?

A class defines a new reference type and how that type is implemented.
The best way to look at a class for now is that it is a template for making objects. A class is therefore different from an object. An object is like the implementation of a class. You can define one class and create many different objects using that same class. Classes are created at compile time and objects are created at runtime in memory. A class specifies both the properties and actions that an object can perform. The properties are specified as fields while the actions are specified as methods. Designing classes is very important during program development. If you design your classes and the relationships between your classes well, you'll find it very easy to solve real worl problems with Java. Class relationships are specified through inheritance and composition. These two are very important and should be mastered.

Encapsulation

A simple definition of encapsulation is combining elements to create a new entity. The idea is to hide certain information so that there is a separation of concerns. Code is grouped together into modules such that no code exists outside of a module. Java supports encapsulation directly in that every line of code that you write has to be in some class. No code exists outside a class. This has several consequences which will become obvious along the way. One consequence is that no object can be created if the code does not have a class.
Next we'll discover that no class exists outside a package.

Java packages

Packages are a way of organizing files into different directories according to their functionality, usability and categories that they belong to. This has the advantages of ease of maintenance, organization and (as an extra) allow us to reuse the same class name in a different package. Think of a package as a folder containing classes. If you type the following in your text editor and save it as PackageTest.java

Expand|Select|Wrap|Line Numbers
  1.  
  2.  package test;
  3. class PackageTest {
  4.       public static void main(String[] args) {
  5.            System.out.println("Tested");
  6.       }
  7. }
  8.  
  9.  
When you compile it, it compiles fine but when you try to run it you will get an exception that the class test/PackageTest
was not found. If however, you create a folder called test and put the file in this folder and compile and run it you get "Tested" printed to the console. The JVM requires the fully-qualified class name to load the class so you needed to use java test.PackageTest to run it. Alternatively, you can specify the location of the .class using the classpath variable.
To use a package's classes, import them in your code using import statements. Package declaration comes before import statements. Many packages have already been created for you to import and use in your code.
You should always try to take advantage of the classes in the java api here . The compiler automatically imports the java.lang package for you.

Class structure

A class declaration starts with a modifier which can be any of
public, protected, private, abstract, static, strictfp, final.
To get us started we'll look at the public and protected modifiers first.
Java classes are encapsulated into packages. Classes in one package can only access public classes in another package. Protected classes are accessible only within the package that they have been defined. If you do not include a modifier, protected access is assumed. The class is put inside the default package which is automatically created for you.
You should always put your classes in a package. Here is the rest of the structure of a Java class:

Modifier(s) class ClassName {
members(methods, fields, nested classes and interfaces)
constructors
static initializers

}

Each of these three componets are optional.

static keyword.

If a variable (including method) is defined as static inside a class, that variable belongs to that class but is not part of instances (objects) of that class(Memory is not allocated for the static variables when the object is created).
Therefore the static variable can be accessed without creating an object of that class.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. static int members;
  6. public static void main(String[] args) {
  7. System.out.println(members); //or Church.members
  8. }
  9. }
  10.  
  11.  
In this code no object is created inside the main method. The static variable member is accessible in main and also through the class name Church. The main method is also a static method. This is very important so that the JVM can always access the main method through the class name. Static variables are resolved at compile time not at runtime (Remember strongly typed). If you do not initialize a static variable, it is initialized for you by the compiler.

Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. static int members;
  4. public static void main(String[] args) {
  5. System.out.println(Church.members);
  6. }
  7. }
  8.  
prints 0 to the console as int defaults to 0 on initialization.

Only static variables are accessible inside a static context.
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. static int members;
  4. int pastors;//pastors is not static
  5. public static void main(String[] args) {//main is a static context(modified by keyword static)
  6. System.out.println(Church.members);
  7. System.out.println(Church.pastors);//! will not compile
  8. }
  9. }
  10.  
non-static variable pastors cannot be referenced from a static context

The static initializers are always resolved first before the program runs
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. static int members;
  4. public static void main(String[] args) {
  5. System.out.println(Church.members);
  6. System.out.println(Church.pastors);
  7. }
  8. static int pastors = 5;
  9. }
  10.  
prints two 0 and 5 on the console.
The Math class contains a lot of static methods which you can reuse. It is in the java.lang package so you do not need to import anything to be able to use it.
Expand|Select|Wrap|Line Numbers
  1. package tests;
  2. class EasyMath {
  3. public static void main(String[] args) {
  4. System.out.println(Math.PI); //static constant
  5. System.out.println(Math.pow(2, 6)); //static mothod
  6. }
  7. }
You can use the static keyword as a way of declaring global variables.

Creating objects.

So far we have not been creating any objects. Objects are created at runtime from classes that were created at compile time. The new keyword is used to create objects.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. static int pastors;
  6. public static void main(String[] args) {
  7. //System.out.println(Church.pastors);
  8. Church c = new Church();
  9. }
  10. }
  11.  
  12.  
Here we have created a new object. A church called c. Note that pastors was created first before c was created. We have not yet put anything inside c. If we create another church it would always print the same value of pastors as c would because both share the same class with the same static variable.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. int pastors;
  6. public static void main(String[] args) {
  7. Church c = new Church();
  8. System.out.println(c.pastors);
  9. }
  10. }
  11.  
  12.  
Now pastors is an instance field. Members are also automatically initialized by the compiler so the above code prints 0
to the screen. Notice that pastors is no longer accessible through class name but only from dereferencing the object c.
We can add more variables of different data types to the field area and each would become part of any object created
from that class.

Methods

Methods have a return type and a signature. A signature consists of the method name, the number of arguments and the order of the arguments. A method can return at most one value. You cannot have two methods with the same signature in the same class.
Notice therefore that
Expand|Select|Wrap|Line Numbers
  1. void a (int x, double y)
  2.  
and
Expand|Select|Wrap|Line Numbers
  1. void a (double x, int y)
  2.  
have different signatures. The argument variable names(x, and y above) in a method must be distinct.

We have already had a look at class methods which are static methods. Remember they can only access static variables.
Instance methods (non-static) execute in the context of a particular object. They operate on the current object's instance variables and can refer to the object itself using the 'this' keyword.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. int pastors;
  6. public static void main(String[] args) {
  7. Church c = new Church();
  8. c.setPastors(10);
  9. c.printPastors();
  10. }
  11. public void setPastors(int p) { //returns nothing takes one int
  12. pastors = p;
  13. // or this.pastors = p;
  14. }
  15. public int getPastors() { //returns int takes nothing
  16. return pastors;
  17. }
  18. public void printPastors() { //returns nothing takes nothing
  19. System.out.println(pastors);
  20. }
  21. }
  22.  
  23.  
The main method is the starting point for an application and has signature public static void main(String[] args). It is the first method called when the Java interpreter executes an application.


Constructors

The other part of a class is a constructor. Note that unlike C++ there are no destructors in java. A constructor is used in the creation of an object. When you create a new instance of a class using the new keyword, a constructor for that class is called.
Constructors are used to initialize the instance variables (fields) of an object. They are similar to methods, but with some important differences. Constructors do not have a return type (the value is always this object). They must have the same name as the class they are in. Every class has at least one constructor. If you don't define a constructor for a class, (like we did in the examples above) a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (we'll examine this in the next lesson on inheritance) and initializes all instance variables to default values (zero for numeric types, null for object references, and false for booleans). Note that the default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. So
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. public static void main(String[] args) {
  4.     Church c = new Church();//calls default no-arg constructor automatically created by compiler
  5. }
  6. }
  7.  
compiles but
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. public Church(long a) {
  4. }
  5. public static void main(String[] args) {
  6.     Church c = new Church();//calls default no-arg constructor automatically created by compiler
  7. }
  8. }
  9.  
will not compile (Cannot resolve symbol variable: constructor Church()) because the presence of the constructor stops the automatic
creation of the no-arg constructor. You can define as many constructors as you feel are necessary as long as they have different signatures.
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. int pastors;
  6. public Church() {// initializes pastors to 0
  7. pastors = 0;
  8. }
  9. public Church(int pastors) {// initializes pastors to the given value
  10.     this.pastors = pastors;
  11. }
  12. public static void main(String[] args) {
  13.     Church c1 = new Church();
  14.     c1.printChurch();
  15.     Church c2 = new Church(10);
  16.     c2.printChurch();
  17. public void printChurch() {
  18.     System.out.println("Church with :" + getPastors() + " Pastors");
  19. }
  20. public int getPastors() {
  21.     return pastors;
  22. }
  23. }
At runtime you specify which constructor to call by the number and order of arguments you give to the new operator. The new operator basically calls a constructor. Notice in the second constructor above:
Expand|Select|Wrap|Line Numbers
  1. public Church(int pastors) {// initializes pastors to the given value
  2. this.pastors = pastors;
  3. }
  4.  
the name of the argument 'pastors' clashes with the name of the member variable of the class. This hides the member variable as it is declared further from the context than the method argument. To access the member variable, the 'this' keyword is used. 'this' refers to the current object instance.

You should use the constructor to initialize variables only.

A constructor can call another constructor in the same class (or in a different class. This will be examine in the next class on inheritance).
To do this you use the 'this' keyword. This must be the first line of the constructor.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package religion;
  4. class Church {
  5. int pastors;
  6. int members;
  7. public Church() {
  8. pastors = 0;
  9. members = 0;
  10. }
  11. public Church(int pastors) {
  12. this(); // calls the default constructor so members is also initialized to 0.
  13. this.pastors = pastors;
  14. }
  15. public Church(int pastors, int members) {
  16. this(pastors); // calls the one-arg constructor so pastors has been initialized.
  17. this.members = members;
  18. }
  19. }
  20.  
  21.  
If the call to this is not the first line of the constructor you'll get the error call to this must be first statement in constructor

The final keyword

Use the modifier to denote that a variable is assigned a value at most once. The compiler will not allow you to assign a value to a final variable twice.
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. final int pastors;
  4. public Church() {
  5. pastors = 0;
  6. }
  7. public Church(int pastors) {
  8. this.pastors = pastors;
  9. this.pastors = 2; //! will not compile
  10. }
  11. }
  12.  
final variables can be declared anywhere in the class. They can be static or non-static. It is allowed to define a final variable without assigning anything to it and then initializing it later on in the code at most once in a context.

If you declare a final variable as a member variable of a class without initializing it, then that final variable must be initialized in every constructor of that class otherwise the compiler will give an error.
Expand|Select|Wrap|Line Numbers
  1. package religion;
  2. class Church {
  3. final int pastors;
  4. public Church(int pastors) {
  5. this.pastors = pastors;
  6. }
  7. public Church() { //! will not compile (variable pastors might not have been initialized)
  8. }
  9. }
Next we look at inheritance but will have a look at the java.lang.String class first.
Dec 27 '06 #1
Share this Article
Share on Google+
5 Comments


chiragvithlani
P: 9
It is very nice to see the Java Sort Introduction as it just helps in revising or introducing the lang. basics....... Thanks
Nov 23 '07 #2

P: 2
It is very nice and able to understand the concepts... Thanks very much...
Mar 9 '08 #3

lotus18
100+
P: 866
Nice tutorial ^ ^

Rey Sean
Apr 5 '08 #4

P: 4
Its very nice and a clear tutorial.
thanks
Feb 21 '12 #5

P: 21
Great job...thanks a lot
Feb 21 '12 #6