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: