Results 1 to 2 of 2
Like Tree7Likes
  • 7 Post By levent

Thread: Java Programming Tutorial

  1. #1
    levent Guest

    Default Java Programming Tutorial

    You may find a lot of Java Programming Tutorials online that will help you in understanding Java programming. My aim here is to provide a simple and basic Java Programming Tutorial, that you can digest easily. Normally Java programming tutorials are written for readers who are fimilier with some object oriented language like Smalltalk, Eiffel or C++. Obviously if you know C++, Java is easy to learn for you and many Java Programming Tutorials target those audience. My aim is to write a simple Java programming tutorial that will help readers, who are new to programming world, how to start programming in Java programming language. This Java programming tutorial, won’t cover object oriented concepts.

    Hello World Application

    Normally Java programming tutorials start with Hello World application. I will also use this program as it will give you an idea how to structure code.

    HelloWorldApp.java

    Java Code:
    /** 
     * HelloWorld application
     * prints Java Programming Tutorial: Hello world on console. 
     */
    class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("Java Programming Tutorial: Hello World"); 
    // Display the string.
        }
    }
    Take a closer look at the give code. HelloWorldApp.java consists of 3 components.

    1. source code comments
    2. class definition
    3. main method


    1. Source Code Comments

      Source Code Comments are only for documentation purpose. They are not compiled by the compiler. The purpose is only to made the code easy to understand. Comments can appear anywhere in a Java source file except within character and String literals.

      Java has three types of comments: line comments, block comments, and JavaDoc comments.

      Line Comment

      To add comments in one line, use line comment. Line comment starts with with two forward slashes (//) and ends at the end of the line the slashes appear on.

      Example:

      Java Code:
      // taking input from console
      // displaying the output
      Block Comment

      To add comments of more than one line, use block comments. A block comment starts with a forward slash and asterisk (/*) and ends with an asterisk and forward slash (*/). Anything in between is treated as comment.

      Example:

      Java Code:
      /* for loop will iterate through the whole array
         if any index contains not zero value
         calculations will be done
      */
      JavaDoc Comment

      To document non-private classes, attributes, and methods, we use JavaDoc comments. It starts with a forward slash and two asterisks (/**). It ends with one asterisk and a forward slash (*/). Everything in between is treated as comment.

      JavaDoc comments can be converted into HTML file. This HTML file can be packaged with the generated .class file to document the class's non-private API. So these comments are even visible if user does not have java code.

      Example:

      Java Code:
      /**
       * @author James Andereson
       * Java Tutorial comments code
       */
    2. Class Definition

      Do define a class in Java, we use keyword class. It begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces { code comes here }.

      Java Code:
      class HelloWorldApp {
      // code here
      }
    3. main Method

      Your Java application may contain many classes and many method. How will the compiler know, from where to start the program execution? The answer is main method. Program execution starts from main method. Each application must contain main method. Some of you might have worked in C or C++. For your reference, main method is similar to main function in C and C++.

      Signature of main method is:

      Java Code:
      	public static void main(String[] args) {
      		// TODO Auto-generated method stub
      	}
      An application cannot contain more than one main method and main method has to be defined in a public class. One important think to note is that, name of java file containing public class with main method, should be same as the class name.

      The main method accepts an array of elements of type String. They are specified through command line. Though our example does not make use of this but its an open option to use it according to requirement.

      Example:

      Java Code:
      public class JavaProgrammingTutorial {
      	public static void main(String[] args) {
      		System.out.println("First argument is : " + args[0]);
      		System.out.println("Second argument is : " + args[1]);
      	}
      }
      To provide command line arguments:

      Java Code:
      java JavaProgrammingTutorial JavaProgramming Tutorial
      Output:

      First argument is : JavaProgramming
      Second argument is : Tutorial

      Arrays in java start with index 0.

      So far this Java Programming Tutorial has introduced you to the structure of Java programs. Now we come to things that you need to write code.


    Java Programming Language – Few basics

    I know many programmers, who started Java without going through Java Programming Tutorial. Consequence was, they had to spend hour fixing simple bugs. I am sure you won’t face those small bugs if you remember these:

    • After each expression: 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: // xxx or /* xxx */ multiple line comment
    • Outside class-declarations: Only the instructions "import", "package" and your own comments are allowed! Nothing else.
    • One program can contain one or more class-declarations
    • A class-declaration consists of:
      <Modificator> keyword class <class name>
      {
      <Trunk>
      }
    • Modificator "public" in classes means: class can be "seen" in all other classes
    • Modificator "static" in methods means: method can be used without instantiation.
    • Modificator "void" in methods means: you‘ll get no return-value after method-execution.
    • One source-code file can only contain one public-class.
    • The source-code file has to have the same name as the public-class.
    • The trunk contains variables (let‘s say properties) and methods
    • If the variables are defined within methods, we‘ll have local variables i.e can't be accessed outside the method
    • System.out.println: System.out is also called "reference" - don‘t mix it with reference-variables


    Now you know the basics, you should try writing code. First download and install JDK.
    Installation of SDK 1.5



    If you’ll have a look into C:\jdk1.5\...

    • …bin: Contains all tools for development (Compiler, Debugger,…)
    • …demo: Examples
    • …docs: If downloaded, this folder contains the Java-documentation
    • …include: Native interface header files: All C-header-files which have to be integrated into the java-code (e.g. definitions concerning input/outputvariables, time declarations,…)
    • …jre: Java Runtime Environment
    • …lib: All libraries which have to be included when code-compilation takes place


    Java Programming – Writing/Compiling/Running

    Now follow following steps:

    1. Write the source code in some editor
    2. Save the source code under file extension java (MyClass.java)
    3. In Microsoft Windows: Open the (black) command window via START>Programs>Utilities
    4. Go to the folder which contains your MyClass.java file
    5. Compile your application/ applet with JDK 1.5:
      Type in javac MyClass.java. A class-file will be generated (MyClass.class) in the same folder
    6. Type in java MyClass. Application will be started


    Java programming is case sensitive so take special care. If you make any change in the code, then you have to recompile the code.

    Java Programming - Data Types

    In Java Programming, each variable has to be declared before it can be used. Such languages are called strongly-typed languages. Java has 8 primitive data types:

    • byte: Stores value in 8 bits. Range of byte is -128 to 127 (inclusive). It is useful with you have small value to store and using int will result in wastage of memory.
    • short: Stores value in 16 bits. Range of short is -32,768 to 32,767 (inclusive). It is useful in situations, where memory saving is important and data you want to store can be stored in short apart from int.
    • int: Stores value in 32 bits. Range of int is -2,147,483,648 to 2,147,483,647 (inclusive). Usually when ever we have to store integral values, we use int. But as written above, using byte and short is more useful if value can be stored in them.
    • long: Stores value in 64 bits. Range of long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
    • float: Stores value in 32 bits. It is used to store floating point values.
    • double: Stores value in 64 bits. Stores floating point values.
    • boolean: Stores value in one bit. The boolean data type has only two possible values: true and false. When decision making is involved, used this data type. Some programmers tend to use integer or short for flags. Obviously, they will achieve the required results but the point is, they will be wasting few bits. Boolean data type is to be used where required.
    • char: 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).


    Java Programming - Variables

    In Java Programming, 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. Syntax of declaring variable is simple.

    Example:

    Java Code:
    int int_a;
    float int_b;
    boolean flag;
    char char_a;
    Variables can also be initialized while declaring.

    Java Programming – 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. Arrays in Java are of finite size. So while declaring, you have to mention their size. You cannot change the size of an array at runtime. But you can copy contents of an array to other at run time.

    Example:

    Java Code:
    int[] int_values = new int[25];
    double[] double_values = new double[25];
    Java also allows declaration and usuage of multi-dimensional arrays. These are very useful in complex calculations like matrixes.

    Example:

    Java Code:
    	int[][] x = new int[3][5];
    Java Programming – Assignments

    There are many assignments operators in Java programming language. In the Java programming tutorial, I will cover each one.

    Postfix-notation : x++
    Prefix-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:

    Java Code:
    int a= 15;
    int b = 25;
    		
    if(a<10 || b>10)
    {
    	System.out.println("Entered: Java Programming Tutorial");
    }
    else
    	System.out.println("Not Entered: Java Programming Tutorial");
    Output:

    Entered: Java Programming Tutorial

    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:

    Entered: Java Programming Tutorial

    Example:

    Java Code:
    int a= 15;
    int b = 25;
    
    if(a<10 && b>10)
    {
    	System.out.println("Entered: Java Programming Tutorial");
    }
    else
    	System.out.println("Not Entered: Java Programming Tutorial");
    Output:

    Not Entered: Java Programming Tutorial

    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


    Java Code:
    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


    Java Code:
    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 similier. 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. loopcondition 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:

    Java Code:
    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:

    Java Code:
    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:

    Java Code:
    int num = 2;
    int end = 10;
    	
    for(int start=1;start <= end; start++)
    {
    	System.out.println(num + " * " + start + " = " + (num*start));
    }
    Output will be the same as in while loop example.

    I hope this basic Java programming tutorial will help you start coding in Java.
    sidratul, Sufiyana, Xelk and 4 others like this.

  2. #2
    janeansley's Avatar
    janeansley is offline Member
    Join Date
    Jun 2008
    Posts
    23
    Rep Power
    0

    Default

    Thanks. Very useful especially for newbie like me to revise

Similar Threads

  1. Java networking programming (II)
    By Java Tutorial in forum Java Tutorial
    Replies: 0
    Last Post: 12-27-2007, 07:19 PM
  2. Java networking programming (I)
    By Java Tutorial in forum Java Tutorial
    Replies: 0
    Last Post: 12-24-2007, 08:21 PM
  3. Java Applet 3D programming
    By ramk in forum Java Applets
    Replies: 0
    Last Post: 11-28-2007, 11:36 PM
  4. Java Swing Tutorial
    By JavaBean in forum Java Tutorial
    Replies: 0
    Last Post: 09-22-2007, 10:06 PM
  5. Java Programming
    By JavaForums in forum Java Tutorial
    Replies: 0
    Last Post: 07-29-2007, 12:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •