Awami Shopping

  HOME  |  ABOUT  |  CHAT  WEB SEARCH |  MP3 SONGS |  TEL DIRECTORY |  LATEST NEWS E-MAIL

Chat | Mp3 Songs | English News

JAVA LANGUAGE

 

Java is a new object-oriented programming language developed at Sun Microsystems.

Developed in 1994. Sun formally announces Java and HotJava at SunWorld '95.

JAVA Features

Java has been designed with security and portability in mind. The features of the language make writing distributed applications much easier.

Java is a truly Object Oriented language. Object-oriented design is very powerful because it facilitates the clean definition of interfaces and makes it possible to provide reusable code.

Java source code is compiled into byte codes for the Java Virtual Machine specification...

Java was based on C++, and the syntax is very similar, so programmers who know C++ will have little difficulty adopting Java. But Java is much simpler than C++; the best way to describe the simplicity of Java is to talk about some of the things that were omitted. Sun believed that a lot of the features of C++ were more of a preventing to programmers than they were a benefit. These features were omitted from the language design without a loss of functionality. The most important features of C++ that are absent from Java are operator overloading and pointer arithmetic. There is no direct manipulation of pointers in Java. The language handles garbage collection for you. To sum up on the simplicity issue, Java is a full-service language without the endless special cases and exceptions plaguing C++.

Concurrency! Yummy!

 

Java Terminology

OBJECT ORIENTED DESIGN

A software design method that models the characteristics of abstract or real objects using classes and objects.

CLASS

In the Java language, a type that defines the implementation of a particular kind of object. A class definition defines instance and class variables and methods, as well as specifying the interfaces the class implements and the immediate superclass of the class.

OR

A class is a reference name or label of a plan that consist of different objects.

OR

A class is the plan or design for an object, Similar in concept to the blueprints for a car.

CONSTRUCTOR

A method that creates an object. In the Java language, constructors are instance methods with the same name as their class. Java constructors are invoked using the new keyword.

INSTANCE

An object of a particular class. In Java programs, an instance of a class is created using the new operator followed by the class name.

INTERFACE

In the Java language, a group of methods that can be implemented by several classes, regardless of where the classes are in the class hierarchy.

OBJECT

The principle building blocks of object-oriented programs. Each object is a programming unit consisting of data (instance variables) and functionality (instance methods). See also class.

PACKAGE

In the Java language, a group of classes. Packages are declared with the package keyword.

CLASS METHOD

Any method that can be invoked using the name of a particular class. Class methods affect the class as a whole, not a particular instance of the class. Class methods are defined in class definitions. See also instance method.

CLASS VARIABLE

A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions.

OVERLOADING

Using one identifier to refer to multiple items in the same scope. In the Java language, you can overload methods but not variables or operators.

BLOCK

In the Java language, any code between matching braces ({ and }).

BYTECODE

Machine-independent code generated by the Java compiler and executed by the Java interpreter.

 

JAVA PROGRAM TYPES

There are two types of program you can write in JAVA.

  1. Programs that are to be embedded in a web page are called JAVA applet
  2. Normal standalone programs are called JAVA applications.

This type further sub-divided into two types:

  1. Programs that known as console program/applications, which only support character, output to your computer screen.
  2. Program that known as windowed JAVA applications that can create and manage multiple

Rules for writing programs in JAVA

 

JAVA PROGRAM STRUCTURE

public class <<class Name>> // class declaration

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • { //start Body of root classs
  • public static void main(String[] args) //Start Body of main()

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • {

    <<<statement>>>

    } //end Body of root class

    } //end Body of root class

  • Java Basic Important Commands/keywords/Methods

    Command Description Syntax/Examples
    class Use to declare a class class identifier-name { statements }
    public A Supporting command that used with class and with other commands use to specify that the related class code is globally accessible. 1). public class identifier { statements }

    2). public static void main(String [] args)

    { statements }

    static Use to specify that the related function/code/parameters is remains same when program executes. public static void main(String [] args)
    import Use to include built-in Java packages (consist of classes/methods definition) with program. import java.lang;

    import java.io.*;

    import java.awt.*;

    main() A built-in method in Java that must use when you want to develop a Java Application program. public static void main(String[] args)
    system.out.print A built-in method in Java that is use to display your identifiers values on console/monitor, not perform line feed + carriage return operation. System.out.print("Hello");

    System.out.print("====");

    system.out.println A built-in method in Java that is use to display your identifiers values on console/monitor, perform line feed + carriage return operation. System.out.println("Hello World!");

    System.out.println("====");

    if If is use to specify a condition in Java program. The if statement checks the expression value (which returns a boolean) and if the expression value is true, it executes the statement block otherwise the execution block is skipped. int a=0,b=10;

    If (a<b) { System.out.print("Variable A is less than B");}

    Else

    System.out.print("Variable B is less than A");}

    /*****syntax***/

    if(expression) { statements;} else {statements;}

    for Iterative controls structure in Java Language that is use to specify a loop in Java program.

    In for method first argument is use to assign a value to counter; 2nd argument is use to specify a condition; and third argument is is use to define the increment/decrement in counter.

    for (int I=0;I<=10;I++)

    { System.out.print(a);}

    /***** OR***********/

    for (int I=0;I<=10;)

    { System.out.print(a);

    I++;}

    While Iterative controls structure in Java Language that is use to specify a conditional loop in Java program. i=10;

    while ( i>0)

    { System.out.print(i);i--;}

     

    Java Basic Important Commands/keywords/Methods

    Command Description Syntax/Examples
    do.. while The do statement is an example of iteration statement. In do statement the execution block is specify b/w the do & while statement clauses. Syntax:

    do

    {statements;};

    while (expression);

    /****example****/

    int i=0;

    do { system.out.print(i); i+=2;}

    while(i<=100);

    switch A Switch statement is like a multiple if statement. It passes control to one of the many statements within its block, depending on the value of the expression in the statement. Control is passed to the first statement following a case label that matches the value of its expression. If there is no match then control is passed to the default label. Syntax:

    Switch (expression)

    {

    case v1 : statement1;

    break;

    case v2: statement2;

    break;

    default: other statement;

    }

    /*****example***/

    example:

    I=10;

    Switch( I){

    case 1: System.out.print("One");break;

    case 10:System.out.print("Two");break;

    default: System.out.print("other Value");break;

    }

    break The break statement is used to pass the control to another part of the program. An unbalanced break statement in an iteration passes control to the next line after current iteration. Example:

    I=10;

    Switch( I){

    case 1: System.out.print("One");break;

    case 10:System.out.print("Two");break;

    default: System.out.print("other value");break;

    }

    Escape characters or special characters in Java:

    Special Char Description Example
    \n Perform line feed & Carriage return operation System.out.print("A\nB");
    \t Prints a tab sequence on screen System.out.print("A\tb");
    \’ Prints a single quote character on screen System.out.print("\’a\’");
    \" Prints a double quote character on Screen System.out.print("\"a\"");
    \r Perform carriage return operation System.out.print("a\rb")
    \b Remove one character from left System.out.print("a\bHi!" );

     

    Java Virtual Machine: The Java virtual machine(JVM) is the heart of Java. The JVM is a virtual computer that resides in memory and enables a Java program to be executed on a variety of platforms.

     

     

     

     

     

    Java Applications

    For a Java program to run an application, it must have at least one public class that contains a public static method called main() that takes exactly one parameter, an array of string objects. The main() method must be public so that the Java virtual machine can find it. If the method is not public, its name is not included in the compiler’s output. The system does not create any objects prior to the start of the application’s main() method must be static because it cannot be associated with an object.

    If an application has a graphical user interface, then it typically creates a java.awt.Frame object in main(). The Frame object acts as the top level window for the application.

    Identifier: An identifier is generally used as the name for any thing in a program. A few identifiers are reserved by Java for special uses, these are called Keywords.

    Memory Variable: A variable is a named piece of memory that you use to store information in your Java program.

    Variable Names: The name that you choose for a variable, or indeed the name of that you choose for anything in Java is called an identifier. An identifier can be any length, but it must start with a letter, an underscore a dollar sign($). The rest of an identifier can include any characters except those used as operators in Java (such as +,-,or *).

    Java is case sensitive so the names NAME and Name are not the same. You must not include blanks or tabs in the middle of a name. You cannot be anything like keywords in Java as a name of same thing. A name can’t be 1234 or 37.5 constant can also be alphabetic, such as true and false for example.

    Variables and types:

    Each variable that you declare can store values of a type determined by the data type of that variable. You specify the type of a particular variable by using a type name in the variable declaration.

    There are eight basic data types, defined with in the Java language. These fundamentals types, also called primitives, allow you to define variables for storing data that falls into one of three categories:

    Integer Data Types: There are four types of variables that you can use to store integer data. All of these are signed. That is they can store both negative and positive value. The four integer differ in the range of value they can store. So the choice of type for a variable depends on the range of data values you are likely to need. The four integer types in Java are:

    DATA TYPES. DESCRIPTION

    byte Variables of this type can have value form –128 to +127 and occupy 1 byte(8

    bits) in memory.

    short Variables of this type have values from –32768 to +32767 and occupy 2

    Bytes (16 bits) in memory.

    int Variables of this type can values from –2147483648 to 2147483647.

    long Variables of this type can values from -9223372036854775808 to

    9223372036854775807 and occupy 8 bytes (64 bits) in memory.

    Data types that allows decimal value in variables:

    float variables of this type can have values from –3.4E38 (-3.4*10 38) TO

    +3.4E38 (-3.4*10 38) and occupy 4 bytes in memory. Values are represented

    with approximately 7 digits accuracy.

    double Variable of this type can have values from –1.7e308 ( -1.7*10308

    to 1.7e308 (1.7*10308) and occupy 8 bytes in memory.

    Values are represented with approximately 17 digits accuracy.

    Other Data types:

    char variables of that type char store a single character. They each occupy 16

    bits, two bytes, in memory because all character in Java are stored as

    Unicode.

    To declare and initialize a character variable mychar you would use the

    statement * char mychar=’X’;

    boolean varaibles that can only has only one of two values, true or false.

    Array: - Arrays are List of similar data items OR list of homogeneous data items.

    Description

    Java uses arrays in a much different manner than other languages. Instead of being a structure that holds variables, arrays in Java are actually objects that can be treated just like any other Java object. The powerful thing to realize here is that because arrays are objects that are derived from a class, they have methods you can call or manipulate the array. The current version of the Java language only supports the length method, but you can expect that more methods will be added as the language evolves. One of the drawbacks to the way Java implements arrays is that they are only one-dimensional. In most other languages, you can create a two-dimensional array by just adding a comma and a second array size. In Java, this does not work.

    Declaring Arrays

    Since arrays are actually instances of classes (objects) , we need to use constructors to create our arrays much like we did with strings. First , we need to pick a variable name and declare it as an array object and also specify which data type the array will hold. Note that an array can only hold a single data type. You can’t mix strings and integers within a single array. Here are a few examples of how array variables are declared:

    int intarray[];

    String names[];

    As you can see, those look very similar to standard variable declarations, except for the brackets after the variable name, you could also put the brackets after data type if you think this approach makes your declarations more readable:

    Int[] intarray;

    String names;

    Sizing Arrays

    There are three ways to set the size of arrays. Two of them require the use of the new operator. Using the new operator initializes all of the array elements to a default value. The third method involves filling in the array elements with values as you declare.

    The first method involves taking a previously declared variable and setting the size of the array. Here are a few examples:

    int intarray[]; //declare the arrays

    String names[];

    intarray[]= new int[10]; // size each array

    names[]=new String[100];

    or, you can size the array object when you declare it:

    int intarray[]= new int [10];

    String names[] new String [100];

    Finally, you can fill in the array with values at declaration time:

    String names[] ={"asad","ali","tariq"};

    int[] intarray={1,2,3,4,5};

     

    Accessing Array Elements

    Now that you know how to initialize arrays, you’ll need to learn how to fill them with data and then access the array elements to retrieve the data. We showed you a very simple way to add data to arrays when you initialize them, but often this just is not flexible enough for real-world programming tasks. To access an array value, you simply need to know its location. The indexing system used to access array elements is zero-based, which means that the first value is always located at position 0. Let’s look at a little program that first fills in an array then prints it out:

    public class powerof2

    {

    public static void main (Sting args[])

    { int intarray[]= new int [20];

    for (int I=0;I<intarray.length-1; I++)

    {

    intarray[I]=1;

    for (int p=0; p<I;p++)

    {

    intarray[I]*=2;

    }

    for (int i=0; i<intarray.length-1; i++)

    System.out.println("2 to the power of "+I+" is " + intarray[I]);

    }

    }

    The output of this program looks like this:

    2 to the power of 0 is 1

    2 to the power of 1 is 2

    2 to the power of 2 is 4

    2 to the power of 3 is 8

    2 to the power of 4 is 16

    2 to the power of 5 is 32

    2 to the power of 6 is 64

    2 to the power of 7 is 128

    2 to the power of 8 is 256

    2 to the power of 9 is 512

    2 to the power of 10 is 1024

    2 to the power of 11 is 2048

    2 to the power of 12 is 4096

    2 to the power of 13 is 8192

    2 to the power of 14 is 16384

    2 to the power of 15 is 32768

    2 to the power of 16 is 65535

    2 to the power of 17 is 131072

    2 to the power of 18 is 262144

    2 to the power of 19 is 524288

     

     

    So, how does the program work? We first create our array of integer values and assign it to the intarray variable. Next, we begin a loop that foes from zero to intarraylength-1; by calling the length method of our array, we find the number of indexes in the array. Then , we start another loop that does the calculation aand stores the result in the index specified by he I variable from our initial loop. Now that we have filled in all the values for our array, we need to step back through them and print out the result. We could have just put the print statement in the initial loop, but the approach we used gives us a chance to use another loop that references our array. Here is the structure of an index call:

    Arrayname[index];

    Pretty simple. If you try and use an index that is outside the boundaries of the array, a run time error occurs. If we change the program to count to an index of 20 instead of 20-1=19, we would end up getting an error message like this:

  •  
  •  
  •  
  •  
  •  
  • java.lang.arrayIndexOutOfBoundsException:19

    At powerof2.main(powerof2.java:10)

  • Example-2

    public class arraylist

    {

    public static void main(String args[])

    {

    int rollnos[]={1,2,3,4,5,6};

    String studentnames[]={"Asad", "Tariq","Nawaz","Rahim","Ali","Naveed"};

    System.out.println("List of Students\n-----------------\n");

    for (int i=0;i<=studentnames.length-1;i++)

    { System.out.println("Roll no :"+ rollnos[i]);

    System.out.println("Name :"+ studentnames[i]);

    System.out.println("---------------------------------------------------------------");

    }

    }

    }

    The output of this program looks like this:

    List of students

    -------------------

    Roll no : 1

    Name : Asad

    -----------------------------------------

    Roll no : 2

    Name : Tariq

    -----------------------------------------

    Roll no : 3

    Name : Nawaz

    -----------------------------------------

    Roll no : 4

    Name : Rahim

    -----------------------------------------

    Roll no : 5

    Name : Ali

    -----------------------------------------

    Roll no : 6

    Name : Naveed

    Command line arguments

    Command line arguments are only used with Java applications. They provide a mechanism so that the user of an application can pass in information to be used by the program. command line arguments are common with languages like C and C++, which were originally designed to work with command-line operating system like Unix/some time DOS.

    The advantages of using command line arguments is that they are passed to a program when the program first starts, which keeps the program from having to query the user for more information. Command-line arguments are great for passing custom initialization data.

    The syntax of passing arguments are extremely simple. Just start your programs as you usually would and add any number of arguments to the end of the line with each one separated by a space. Here is a sample call to a program named "myapp":

    Java myapp open 640 480

    In this case, we are calling the Java run-time interpreter and telling it to run the class file "myapp". We then are passing in three arguments: "open", "640",and "480" if you wanted to pass in a longer string with spaces as a argument, you could, in this case, you enclose the string in quotation marks and Java will treat it as a single argument. Here is an example

    Java myapp "Nice Program!" "640x480"

    Once again the name of the program is "myapp". However, this time we are only sending it two arguments: "Nice Program!" and "640x480". Note that the quotes themselves are not passed , just the string between the quotes.

    Example-3

    class testargs

    {

    public static void main(String args[])

    {

    for(int I=0;I<args.length-1;I++)

    System.out.println(args[I]);

    }

    }

     

    SUPPOSE

    You pass following arguments after successful compilation…

    C:\java\bin> Java testargs one two three four five

    The output of this program looks like this:

     

    one

    two

    three

    four

    five

     

     

     

     

     

     

     

     

     

     

    Java classes and methods

    In traditional structured programming languages like C or pascal , everything revolves aroud the concepts of algorithms and data structures. The algorithms are kept seprate from the data structures , and they operate on the data to perform actions and results. To help divide programming tasks into separate units, components like functions and procedures are defined. The problem with this programming paradigm is that it doesn’t allow you to easily create code that can be reused and expanded to create other code.

    To solve this problem, object-oriented programming languages like small-talk and C++ were created. These languages introduced powerful components called classes so that programmers could combine functions (operations) and data under one roof. This is a technique called encapsulation in the world of object-oriented programming. Every language that uses classes defines them in a slightly different way; however, the basics concepts for using them remain the same. The main advantages of classes are:

    1. They cab used to define abstract data types
    2. Data is protected or hidden inside a class so other classes can’t access it.
    3. Classes can be used to derive other classes.
    4. New classes derived from existing classes can inherit the data and methods already defined – a concept called inheritance.

    Declaring a Class

    Let’s look at the full declaration used to define classes in java:

    [Doc Comment] [Modifier] class identifier

    [extends Superclassname]

    [implements Interfaces]

    {

    class-body;

    }

    Of course , keep in mind that you won’t always use all of the clauses , such as Doc Comments, Modifier , extends , and so on. For example, here’s an example of a very small class definition:

    /**

    *

    */

    class atom_ant {

    int a=1;

    }

    This class has an identifier , atom_ant, and a body, int a=1; of course , don’t try to compile this at home as is because it will only result in an error. Why ? well , even though it is a valid class , it is not capable of standing on its own. ( you would need to set it up as an applet or a main program to make it work.) A class declaration provides all of the information about a class including its internal data (variables) and functions (methods) to be interpreted by the Java compiler. In addition, class declarations provide:

    1. Programmer comments
    2. Specifications of the other classes that may references the class
    3. Specifications of the superclass the class belongs to (the class’ parent)
    4. Specifications of the methods the class can call

    Abstract class

    The abstract modifier is used to declare classes that serve as shell or placeholder for implementing methods and variables. When you construct a hierarchy of classes, your top most class will contain the more general data definitions and method implementations that represent your program’s features. As you work your way down the class hierarchy , your classes will start to implement more specific data components and operations. As you build your hierarchy, you may need to create more general classes and defer the actual implementation to later stages in the class hierarchy. This is where the abstract class comes in. This approach allows you to reference the operation that you need to include without having to restructure your entire hierarchy . the technique of using abstract classes in java is commonly referred to as single inheritance by c++ programmers.( By the way limited multiple inheritance techniques can also be implemented in java by using interfaces.)

    Any class that is declared as an abstract class must follow certain rules;

    1. No objects can be instantiated from an abstract class.
    2. Abstract class must contain at least one declaration of an abstract method or variable.
    3. All abstract methods that are declared in an abstract class must be implemented in one of the subclasses beneath it.
    4. Abstract classes cannot be declared as final or private classes.
    5.  

    Another Example…

    class atom_ant {

    int i=10; }

    public class bug {

    int i=10; atom_ant abc;

    public static void main(string args[]) {

    abc=new Atom_ant();

    System.out.println("there are "+bug.i+"bugs but only "+ abc.i+" atom_ant");

    }

    }

    The output produced by this example would be:

    There are 10 bugs here but only 1 Atom_ant.

    The main class, Bug, creates an instance of the Atom_ant class- the a object. Then it uses the object to access the data member, a, which is assigned a value in the Atom-ant class. Notice that the the dot operator(.) is used to access a member of class.

    public class

    The public modifier is used to define a class that can have the greatest amount of access by other classes. By declaring a class as public, you allow all other classes and packages to access its variables, methods, and subclasses. However, only one public class is allowed in any single java applet as serving the role that the main() function does in a c/C++ program.

    /*Example Program findprimes.java*/

    import java.io.IOException;

    public class findprimes

    {

    /*...........**Method Definition**.............*/

    static int getval()

    {

    String s;int f;

    /*............*Conditional Loop*..............*/

    while (true)

    {

    char ch=' ';

    s=" ";

    f=0;

    int c=0;

    try

    { while (ch!='\n')

    {

    ch=(char) System.in.read();

    s=s+ch;

    }

    }

    catch (IOException e)

    { }

    s=s.trim();

    for(byte i=0;i<s.length();i++)

    {

    if (Character.isLetter(s.charAt(i)))

    {

    System.out.println("Please Enter a Numerical Value ");

    f=1;

    }

    if (f==1)

    break;

    }

    if (f==1)

    continue;

    else

    break;

    }

    /*............*End of Conditional Loop*..............*/

    if (f==0)

    return Integer.parseInt(s);

    else

    return(1);

    }

    /**************End of Method Definition****************/

     

    public static void main(String args[])

    {

    int f=0;

    int k=getval();

     

    for (int j=2;j<k;j++)

    {

    if(k%j==0)

    { System.out.println("NOT PRIME");f=1;}

    if (f==1)

    break;

    }

    if (f==0)

    System.out.println("Your Entry is Prime");

    } }