Search Java Tutorials

Custom Search

What You Will Want to Complete This Tutorial?

You must have at least 1st and 2nd pre-requirements to start the tute. Other requirements will require for last chapters only. These all are free to use and download!
  1. Java Development Kit Standard Edition (JDK / J2SE) Any Version(www.java.com)
  2. Any Text Editor (Note Pad quite enough or get Notepad++ from (http://notepad-plus.sourceforge.net)
  3. Java Run Time Environment (JRE) Any Version(www.java.com)
  4. Java Enterprise Edition (J2EE) for advanced developing (For last few chapters)(www.java.com)
  5. Java Wireless Toolkit for Mobile Application Development (For Mobile Application Development Chapters) (www.java.com)
  6. Tomcat Web Server to run Servlets. (www.tomcat.apache.org/)
Your operating system may be any version of Windows.
What will you learn (As a summary)?
  1. How to build console and windowed applications using Java
  2. How to build web page elements with Java Applets
  3. How to build Database Programs with Java
  4. How to build enterprise applications with Beans
  5. How to add Email functions to Java programs
  6. How to program smart devices (Phone, PDA etc…) with Java

Using prewritten classes in java in Java

Java contains many prewritten classes which are stored in a package. The package is implicitly imported into every java program is named “java.lang”. The classes it contains are the fundamental classes. Other classes that you may want to import known as “optional classes”.
The class “java.lang.Math” contains constants and methods that can be used to perform common mathematical functions. All of the constants and methods in the Math class are static. Common useful Math class methods include those used for finding an absolute value, finding maximum or minimum value, rounding values etc… To use a prewritten class other than “java.lang” you must use the path with the class name and import the class or import the package that contain the class.

Ex:
import javax.swing.*;
import java.util.*;


Easiest way to import prewritten classes is, importing whole package it contains. We use “*” to indicate we need all classes in the package as in above example.

Math class Methods:

· Max(x,y) Larger of x and y
· Min(x,y) Smaller of x and y
· Pow(x,y) X raised to the y power
· Sqrt(x) Square root of x
· Round(x) Closest integer to x(where x is a float or double, and the return value is an integer or long
· Rint(x) Closest integer to x(x is a double, and the return value is expressed as a double
· Floor(x) Largest integral value not greater than x
· Celi(x) Smallest integral value not greater than x
· Random() Random double number between 0.0 and 1.0
· Abs(x) Absolute value of x
· Sin(x) Sine of x
· Cos(x) Cosine of x
· Tan(x) Tangent of x
· Asin(x) Arcsine of x
· Acos(x) Arccosine of x
· Atan(x) Arctangent of x
· Atan2(x,y) That a component of the polar coordinate
· Exp(x) Exponent, where x is the base of the natural algorithms
· Log(x) Natural algorithm of x


Sample Program:
Case: We will use fundamental class “Math” in “java.lang” to manipulate some numbers. We have used float numbers and while assigning values, the values follow letter”f” to indicate that casting shouldn’t carry out.

public class TestMathClass
{
public static void main(String[] args)
{
float num1 = 4f;
// becouse we're using float data type, it's better to use assigning its values followed by 'f'
float num2 = 5f;
float num3 = 6.3f;
float num4 = 6.8f;

System.out.println("Larger value amoung num1 and num2 is: " + Math.max(num1, num2));
System.out.println("Smaller value amoung num1 and num2 is: " + Math.min(num1, num2));
System.out.println("Power of num1 raised to the num2 power is: " + Math.pow(num1, num2));
System.out.println("Largest integral value not less than num3 is: " + Math.floor(num3));
System.out.println("Closest integer to num2 is: " + Math.rint(num4));
}
}


This is the output:

What is the difference between Variables and Constants?

Constants are unchangeable and variables are changing its values throughout the program. After a program is compiled, literal strings (Also known as literal constants) never change. Also, the value stored in symbolic constants never change. You create a symbolic constant by inserting the keyword “final” before a variable name. By convention, constant fields are written using upper case letters. A constant must be initialized with a value.

Ex:
static final int COMPANY_ID = 57575;
static final private int COMAPNY_ID = 52525;


Sample Program:
Case: We will define a constant and then used it straight away.

public class Constants
{
static final int COMPANY_ID = 56644;

public static void main(String[] args)
{
System.out.println("Company ID is: " + COMPANY_ID);
anotherMethod();
}

public static void anotherMethod()
{
System.out.println("Company ID is: " + COMPANY_ID);
}
}


The output is:

What is “this” in Java?

As we stated earlier, you just store one copy of a class (including methods) for use with each object. You store separate fields (variables defined just after class declaration) for each object. The compiler access the correct object’s data fields because you implicitly pass a ‘this’ reference to class methods. In general sense, ‘this’ reference removes confusable states occurs with object declarations. If you have more than one objects based on the same class which has class data fields, then java use implicitly ‘this’ reference to keep in track of fields of each object.

You don’t want to worry about this “this” because java will implicitly do most of it. We will bother about “this” later where we want to explicitly define it.

Tip: he Java keywords this and super are closely related to the method invocation. The use of this and super keywords is twofold. They can be used:
As a reference to access the instance members or the superclass members (as we have seen earlier in section 1.4.2)
OR
As a method name for calling the constructors of the class or its superclass
The this keyword used within an instance method refers to the instance on which the method is called upon.

How to Overloading Methods in Java?

Overloading involves writing methods with the same name, but different argument lists.

Ex: If you have enough information. You can do the same task “telling time” in following three different ways.

Public static void tellTime(hour, min); // Only hour and minutes
Public static void tellTime(hour, min, sec); // Only hour, minutes and also seconds
Public static void tellTime(date, hour, min, sec); // Date of the month, and all.

Java can do the same thing. If method receives enough information it can do the same task in different ways. This is what you called as overloading and it provides “Polymorphism” features in java.

Sample Program:
Case: We will define three variables and three methods with same name. It’s your computers work to catch the right method according to arguments it receives.

public class MethodOverloading
{
public static void main(String[] args)
{
String aText1 = "Text 1";
String aText2 = "Text 2";
String aText3 = "Text 3";

aMethod(aText1);
aMethod(aText1,aText2);
aMethod(aText1,aText2,aText3);
}

public static void aMethod(String text)
{
System.out.println("I received one text only: " + text);
}

public static void aMethod(String text, String text2)
{
System.out.println("I received two text only: " + text + " and " + text2);
}

public static void aMethod(String text, String text2, String text3)
{
System.out.println("I received all texts: " + text + ", " + text2 + " and " + text3);
}
}


The Output is:



Tip: Polymorphism helps you write systems that are flexible andmodification resistant. It allows a method to take on "many forms" which in turn makes it re-usable and therefore more flexible.

Tip: Be careful, If you have a mixed collection arguments of integer, long like data types, there may be unexpected errors. To avoid such errors, when assigning values use letter ‘L’ for ‘long’ values, and ‘f’ for float values.

Ex: long aLong = 11338833L;
Ex: float aFloat = 34.7f;

How to Overload Constructors?

Constructor methods can receive arguments and be overloaded. If you explicitly create a constructor for a class, the automatically created constructor does not exist.

How to cast or convert variables in Java?

Casting is a data type conversion technique. You many use these castings often. As we mentioned earlier, every keyboard input receives as String. Imagine, you’re making calculator software. To do mathematical functions with numbers you want data types like integer, long, float, byte or short but not Strings. Then you need to do the conversion Strings into integer, long etc…

If you need to convert value in a larger capacity data type in to a smaller capacity data type, then you need a casting.

Ex: (long variables capacity: 8 bits, and integer variables capacity 4 bits. Casing the value in long into integer)
Int myInteger = (int)myLong;

Casing can be used to conversions of two different data types with similar capacity.
Ex: (integers are 4 bits and floats are 4 bits too. Casing the value in integer into float)
Float myfloat = (float)myInteger;

Sample Program:
Case: We will define 3 variables and we will cast them.

public class Casting
{
public static void main(String[] args)
{
int myInteger = 64; //integers are 4bytes
float myFloat = 0; //floats are 4bytes
byte myByte = 0; // bytes are 1 byte

System.out.println("Casting similar capacity variables...");
myFloat = (float)myInteger;
System.out.println(myFloat);

System.out.println("Casing larger variable value into samller...");
myByte = (byte)myInteger;
System.out.println(myByte);

}
}


This is the output:


Blocks and Scopes in Java

Within any class or method, the code between a pair of curly braces is called a block. When you declare a variable within a block, you can not reference that variable outside the block. The portion of a program within which you can reference a variable is the ‘Variables scope’.

Sample Program:
Case: This program defines a variable called ‘x’ inside main method. The scope of the variable x starts with its declaration and must be ends with main method closing curly brace. You can retrieve its value on that scope, but you can’t do it out f scope. So, when you compile program you’ll get “Cannot resolve symbol” error in line 12 which is out of scope of variable ‘x’.

public class VariableScope
{
public static void main(String[] args)
{
//scope of the main method starts
int x = 12;
System.out.println("x is: " + x);
anOtherMethod();
}
//scope of the main method ends

public static void anOtherMethod()
{
//scope of the anOtherMethod starts
System.out.println("x is: " + x);
}
//scope of the anOtherMethod ends
}


This is the output:



Now take a look at this, you may define two variables in different scopes and the variables may overlap.

public class OverlapScope
{
public static void main(String[] args)
{
int x = 55;
System.out.println("main method:- x is: " + x);
overlap();
System.out.println("main method:- x is: " + x);
}

public static void overlap()
{
int x = 66;
System.out.println("overlap method:- x is : " + x);
}
}


The output is:




Even the variable names overlapped, java knows keep in track both variables separately. This is also known as nesting variables.

How to create constructors in Java?

A constructor method establishes an object and provides specific initial values for the objects data fields. A constructor method always has the same name as the class of which it is a member.
Sample Program:
Case: This is an implementation of previous program. From line 5 to line 8 is the new part to study. That is the constructor. The constructor will execute automatically and assign a value to strText whenever method starts. Constructors do not have ‘void’ keyword.

public class InstanceVariables
{
String strText;

public InstanceVariables()
{
strText = "This value given by constructor";
}

public InstanceVariables(String text)
{
//opening constructor with an argument
strText = text;
}
//closing constructor with an argument

public void setText()
{
strText = "This is variableUser method.";
}

public String getText()
{
return strText;
}
}


This is the output:


Instance Variables in Java

The data components of a class are often referred to as the instance variables of that class. Also, class object attributes are often called fields to help distinguish them from other variables you might use.

This is the source class for ‘myObject’. In line 3 we have declared a instance variable (known as a class field, because it declares inside class block, not in a method). ‘setText’ method will set a value to strText, and ‘getText’ method will return the value in strText.
Save this class as “InstanceVariables.java”

public class InstanceVariables
{
String strText;

public void setText()
{
strText = "This is VariableUserMethod";
}

public string getText()
{
return strText
}
}


This is the class which uses “InstanceVariables.java” through the object “myObject”.

public class TextEdit
{
public static void main(String[] args)
{
InstanceVariables myObject = new InstanceVariables();
//without arguments
InstanceVariables myArgObject = new InstanceVariables("With Arguments");

System.out.println("Getting the value with myObject");
System.out.println("Value is:" + myObject.getText());

System.out.println("Getting the value with myNewObject");
System.out.println("Value is:" + myArgObject.getText());
}
}



This is the output:

Tip: An object is constructed by instantiating a class. The process of creating an object of a class is called as instantiation and the created object is called as an instance.

How to create Objects in Java?

An object is an instantiation of a class, or one tangible example of a class. To create an object as an instantiation of a class, you can use following syntax:

Syntax: = new ();
Ex: Employee security = new Employee();

When you create an object, the source class is copied into memory and it referred by your object name. Therefore, you can make as much as objects using the same class. Computer will make copies of same class over and over again.

Sample Program:
Case: This program needs two classes; ‘Computer’ class which we will use to create an object named ‘myComputer’. ‘ComputerUser’ class which use the object to access ‘Computer’ class.

First create “Computer.java” which is the source of object.

public class Computer
{
public static void ComputerName()
{
System.out.println("Dual Core");
}
}


Then create “ComputerUser.java” which create the object and use it.

public class ComputerUser
{
public static void main(String[] args)
{
Computer myComputer = new Computer();
myComputer.ComputerName();
}
}


This is the output:


Tip: Objects have a state (also known as member variables, fields, data) and certain behavior (also known as operations, methods, procedures, functions).

Tip: A class represents a blueprint that defines the variables and the methods common to all objects of a certain kind.

Tip: Objects communicate by sending a message or a request to another object to do a particular task. It is usually a call to a method of another object.

How to implement class declaration in Java?

To create a class, you must provide;
1. An optional access modifier (Default is ‘public’, private etc…)
2. The Keyword ‘class’
3. Any legal class identifier
4. Open curly brace
5. Closing curly brace

How to return values in Java?

Sometimes, methods need to send information about the task they carry out back, where the method called from. This is known as returning values. If a method returns a value; instead of the keyword ‘void’, the return data type must be indicated. Method can return a class too.

Sample Program:
Case: This is an implementation of previous sample program. Instead of printing value, ‘multiplyMethod’ will return the result back to main method.


public class myHomeWorksReturn
{
public static void main(String[] args)
{
int value1 = 4;
int value2 = 2;
int ReceivedValue;
//declaring a variable that can hold values from multiplyMethod
ReceivedValue = multiplyMethod(value1, value2);
//Calling to method with arguments
System.out.println("Received Value is: " + ReceivedValue);
}

public static int multiplyMethod(int number1, int number2)
{
int Result = number1 * number2;
return Result; //returns value back
}
}


This is the output:




Improving Method Declaration

In this chapter we will discuss about some declarations we used in previous chapters.

How to implement method declaration?

A Method is a series of statements that carry out a task. A method declaration include, as we mentioned earlier:

  1. Declaration
    1. Optional access modifiers (public, private, protected …)
    2. The return type of the method (void or returning data type)
    3. The method name (Ex: main)
    4. An opening parenthesis
    5. Optional list of method arguments
    6. Closing parenthesis
  1. An Opening curly brace
  2. A body
  3. A closing curly brace

Any method can be called by other methods under certain limitations added by access modifier. “public” is no restrictions, every one can access it. “private” is to restrict method access only within the class it declared.

Ex: public void calculateMethod() {}

Ex: private void idNumberMethod() {}

SCJP Tip: you can use more-than-one modifier while declaring class or its members. When you do so, the modifiers may appear in any order in that declaration. For example , you can apply the access modifiers either before or after or in between the other modifiers.

Arguments or parameters consist of information that a method requires to perform certain task. You can provide as many as parameters within braces in line with method declaration.

Ex: public void idNumberMethod (int myNumber)

Indicating method name with arguments within parenthesis can make a call to that method. A method in a class can be called from another class.

Ex: calculateMethod(319);

Sample Program:

Case: This program will print a literal string from method named “printSomething”. ‘main’ method call this method in line 5. Check line 5 again. You may find that this calling do not send any arguments as the parenthesis is empty. Also in the method declaration in line 8, you can see empty parenthes is. Save this code as “Caller.java”.

This is the output:

When you write a method declaration for a method that can receive an argument, you must include the type of the argument and a local name for that argument.

Sample Program:

Case: This is an implementation of “Caller.java”. Instead of print something, main method send a text to printSomething method.

This is the output:

A method may require more than one argument. If so, you have to indicate data type of each argument separately and to define a local name. Arguments can be separated by commas.

Ex: public void calculateMethod(int Number1, intNumber2, String operator)

To make a call to this method: calculateMethod(22, 4, “+”);

Sample Program:

Case: You have two numbers to multiply. You can send those numbers to another method as arguments.

This is the output:

SCJP Tip: That’s basic again! Now the real declaration of a method:

[modifiers] returntype methodName([argumentList]) {

[method body]

}

[modifiers] : You know! It’s ‘public’ like thing!

returntype : If you want to return something (As in next sample program) then you want to state its data type here.

methodName : ID of your method (Method Name).

([argumentList]) : Arguments that the method will receive.

Tip: There’re a method type known as ‘Abstract Methods’. They have no method body and instead a semi colon will be at the end of method declaration. You’ll learn these later.

Ex: public string find(String wordToFind);

Java Operators and Concatenation

An operator is a symbol that tells the computer to perform a vertain mathematical or logical manipulation. Values used by an operator are known as operands.

There’re arithmetic and comparison operators.

Integer Arithmetic Operators

Description

Example

+

Addition

1 + 2 = 3

-

Subtraction

12 – 2 = 10

*

Multiplication

10 * 3 = 30

/

Division

100 / 4 = 25

%

Modulus (Reminder)

3 % 2 = 1

Comparison Operators

Description

Example

Returns True

Returns False

<

Less than

2 <>

100 <>

>

Greater than

500 > 1

1 > 500

==

Equal to

1 == 1

1 == 2

<=

Less than or equal

1 <= 1 , 0.5 <= 1

2 <= 1

>=

Greater than or equal

50 >= 50 , 100 >= 50

1 >= 2

!=

Not equal

1 != 2

1 != 1

Other than this “=” operator known as assignment operator. It can be used within mathematical sums and also to assign values to variables.

Escape sequence

You can use escape sequences within literal strings to format text.

Escape Sequence

Description

\b

Back Space

\t

Tab

\n

New Line or line feed

\f

Form feed

\r

Carriage return

\”

Double quotation mark

\’

Single quotation mark

\\

Backslash


Increment, Decrement operators

You can use operators like +, - as follows.

Ex:

++ adds one to value in variable x. And then print it (Prefix).

Ex:

Computer prints the value in x and then adds 1 to value in x (Postfix).

You can use -- same way.

Concatenation

Joining strings with other data types within a single statement is known as: Concatenation”.

Ex:

‘+’ sign is also known as “Concatenating operator”. Above example concatenate a literal string “Value in x is:” with value in x which is an integer.

Java Variable Declaration

Variables are named memory locations that your program can use to store values. Line 5 declares our variable “strCountry” as follows.

String strCountry;

“String” is the data type of the variable. That means this variable can hold texts, numbers or set of different characters.

“strCountry” is the name of the variable and known as variable identifier.

Other than strings, you may want to declare variables that can hold only numbers, but not characters; or variables that can hold images. Java provides eight primitive variable types and three reference variable data types. (Primitive variable types are the building blocks of Reference data types.)

The primitive types (also known as bulletin data types) comprise of all the numeric types along with a boolean type. The numeric types are four integral types- byte, short, int, long, andchar, and two floating-point types- float and double.

Primitive Data Type

Usage

Capacity

Default Value

Maximum Value able to hold

Minimum Value able to hold

byte

Sign integer

1 byte

0

127

-128

char

Single character

1 byte

u\0000

-

-

short

Sing integer

2 bytes

0

32, 767

-32,768

boolean

True or false

2 bytes

false

-

-

int

Sign integer

4 bytes

0

232-1

-232

float

Floating point values

4 bytes

0.0f

3.4*1038-1

-3.4*1038

long

Sing integer

8 bytes

0L

264-1

-264

double

Floating point values

8 bytes

0.0

1.7*10308-1

-1.7*1-308


The variables of a reference type hold thereferences to the actual objects.

Reference Data Type

Usage

Capacity

Default Value

Maximum

Minimum

Array

Object


Variable Naming Rules

  1. Variable name must be start with a letter, doller sign or underscore.
  2. No embedded space characters allowed within variable name.
  3. Cannot use keywords as variable names.

You can use access modifies like “private” with variable declaration. Default access modifier in “public” that means if you haven’t declare a access modifier, then java will assume it as a “public” variable.

Ex: private String strCountry;

Variable names usually start with lowercase letters to distinguish them from class names.

You can do the variable declaration and assigning values in one statement.

Ex: String strCountry = “India”;

Also be aware how to indicate assignment of value. String variables need its assigning value within “”. Integer, double, float, long, short, byte need value directly. Char needs its assigning values within ‘’.

Ex:

String strCountry = “Sri Lanka”;

Int intCountryCode = 94;

Char chrCountryLetter = ‘S’;

Every text you input using the keyboard into the program is receives as a String. And every thing you print to screen must be a string. You can print an integer on screen using the statement (If x is an integer): System.out.println(x);. Computer will convert integer ‘x’ into String data type and then prints on screen.

We’ll discuss about reference types later.

Tip: Java is a strongly typed language, which means that every variable and expression has a type that is known at compile-time itself

SCJP Tip: Variables declare inside the class declaration, but not inside a method known as ‘class data fields’ or ‘member variables’. Then variables declare inside methods known as ‘local variables’.

SCJP Tip: There’re two kinds of member variables. (1)The static variable is a member variable declared using the keyword static within a class body. Static variables are also known as class variables. They are created when the class is loaded. (2) The instance variable is also a member variable, but it is declared without the keyword static. Instance variables come into life when an instance (i.e. object) of a class is created and they remain associated with that instance. Instance variables are destroyed as soon as that particular instance is destroyed.