Friday, 13 June 2014

INPUT FROM USER


TAKING INPUT FROM USER :

Like in C++  .  cout and cin commands were contained by library iostream.h 
And to use cin and cout commands in a program , we used to write :
            
                    #include <iostream.h>

In the similar way , for taking input from user in JAVA , Scanner class is used and this is contained in in-built package      util . 


We will see how scanner method is used :
                 



                                      import java.util.*;
               class ScanDemo
               {
                     public static void main(String args[])
                     {
                          Scanner s = new Scanner(System.in);
                          // an object s of scanner class is                                  created
                           
                           System.out.println("Num1");
                           int a = s.nextInt();
                           System.out.println("Num2");
                           int b = s.nextInt();
                           System.out.println(a+b);
                     }
               }



nextInt is an inbuilt method in scanner class which takes integer as input . 

The input from user can be taken in form of character or string or can have any data type .

Like in C++ keyword #include was used to access the classes of any library , in JAVA keyword import is used for including any in-built class.

We will see later in PACKAGES how in-built classes are kept in packages and how to acces and create package  

To refer how to take other data types as input from user please refer :


Monday, 9 June 2014

Flow Controls in JAVA




CONDITIONAL STATEMENTS :


  •  IF STATEMENT :
                       SYNTAX :
                                            if (condition)
                                                  {
                                                   ------ ;
                                                    }
                                       
                   The IF loop lies in the curly braces . if the condition defined in brackets will be satisfied only then the statements in the curly braces will be executed else the compiler  will jump those statements.

e.g.
                          if (a>b)
                          {
                               System.out.println("a is greater than b");
                          }

ON the screen a is greater than will be printed only if a id greater than b .


  •  IF - ELSE STATEMENT :
                          SYNTAX :
                                           if (condition)
                                             {
                                                 -----;
                                              }
                                         else
                                         {
                                          ----;
                                          }
                                     
IN this kind of statement , if the condition is satisfied statements under if loop will be executed and in case the condition is not met it will jump the if statements and will execute the else part.

MULTIPLE IF ELSE STATEMENTS ARE POSSIBLE :
               
                            SYNTAX :
                                               if (condition_1)
                                              {
                                           
                                               }
                                               else
                                                {
                                                            if(condition_2)
                                                            {
                                                     
                                                            }
                                                             else
                                                             {
                                                                             if(condition_3)
                                                                             {

                                                                             }
                                                                              else
                                                                               {

                                                                               }
                                                              }
                                                }

  • SWITCH STATEMENTS :
                          SYNTAX :
                                         
                                               int n ;
                                               switch(n)
                                               {
                                                 case 1: {-----};
                                                  break;
                                                 case 2 : {-----};
                                                  break;
                                                  -
                                                  -
                                                 case n : {----};
                                                  break;
                                                 default : {};
                                                 }

In the above syntax , we consider any integer n . For n to be 1 , case 1 will be executed , for n to be 2 , vase 2 will be executed .In the same way for n case n will be executed . If the value or the integer is greater than n , then default case will be executed.

NOTE :


  • Instead of passing an integer value , character can also pe passed . In JAVA Version 7 and above we can even pass a string .
  • For character :

                                      char 'n';
                                      switch('n')
                                     {
                                       }


  •  Use of break statement is IMPORTANT . if the value of n is 1 and break statement is not used . All the cases following case 1 will be executed .  

LOOPING :


  • FOR LOOP:
                          SYNTAX :
                                               
               for(initialize any variable;condition;increment/decrement)
                                               {
                                                        ----- ; 
                                                }
 In this loop a variable is first initialized i.e. initial value to the variable is assigned for which the loop will be executed . When the compiler reaches the end of the loop , it increments/decrements the initialized variable as per the command given in third section and then after incrementing condition is checked . If the condition given in second section met even after the increment/decrement , the loop is continued .
In this way loop continues till the condition is satisfied . For any unwanted value of the variable , loop is broken .  

         for (int i = 0 ; i<5 ; i++)
        {
             System.out.println("THE VALUE IS "+i);
        }

The loop will execute till the condition is satisfied and the output of the above program will be :

THE VALUE IS 0
THE VALUE IS 1
THE VALUE IS 2
THE VALUE IS 3
THE VALUE IS 4



  • WHILE LOOP
                               SYNTAX :
                                        initalization ;
                                        while(condition)
                                          {
                                             ---- ;
                                            increment/decrement ;
                                         }

While loop and for loop are almost the same . For loops are used when the number of recursions are known and while loop is used when number of recursions are not known .

  Example : The same above program can be implemented using while loop in the following way .
                        int i ;
                        while(i<5)
                       {
                           System.out.println("THE VALUE IS "+i);
                            i++;
                       }


  • DO WHILE LOOP :
                                   SYNTAX :
                                         initialization ;
                                        do
                                         {
                                           ------ ;
                                            increment/decrement ;
                                          }
                                           while(condition);  
   
In do while loop condition is checked after the one time execution of loop . It works in the same sequence as it appears . The loop is one time executed for the initial value of variable and after the execution at the end it is incremented or decremented as per the requirements of the user . After this when the control comes out of the loop , if checks the condition for the current value of variable , if it holds the loop is again executed else control skips the loop.

BRANCHING STATEMENTS :

  • BREAK STATEMENT :
If we use break statement in a loop anywhere , the control comes out of that loop . NOTE THAT word loop is used here and if , if-else and switch statements should not be confused with loops .
If multiple loops are used then the control comes out of the inner loop .

This is explained with the example below :


The output of above program will be 0,1,2,3,4.



  • CONTINUE STATEMENTS :



The output to the above program will appear for 0,1,2,3,4,6,7,8,9.


IN JAVA THERE ARE NO GO TO STATEMENTS .

Sunday, 8 June 2014

Operators in JAVA

OPERATORS 


Operators are the keywords in any programming language that perform the specific pre defined or user defined task on a set of operands . Operands are the values on which the operation is performed to result into a specific value . 
Following types of operators are available in  JAVA . Here is the categorization of Operators and their details with examples :

Arithmetic operators :
  • Arithmetic operators as the name suggests perform the arithmetic operations .
  • Arithmetic operations are performed on two given operations .
  • Following Arithmetic operations are available in JAVA  :
  1. Addition (+)
  2. Subtraction(-)
  3. Multiplication(*)
  4. Division(/)
  5. Modulus (%)
Here is an example of modulus operator :
25%5=5
i.e. modulus operator between two operands gives us the result and would be equal to the remainder that we get after dividing both the operands.

Now, how  you think a java program will resolve the following problem:
  1. (-10)%(3)
  2. (10)%(-3)
  3. (-10)%(-3)  
These are three different cases and it should be made clear clear that SIGN OF DENOMINTOR IS NOT CONSIDERED , IT ASSIGNES THE SIGN OF NUMERATOR AS THE SIGN OF FINAL RESULT.

Hence result to above three problems would be :

  1. (-10)%(3)     = -1
  2. (10)%(-3)     =   1
  3. (-10)%(-3)    = -1
Logical Operators

These operators perform the logical tasks . We have three logical operatos and these are :
  1. AND operator (&&)
  2. OR operator (||)
  3. NOT operator (!)

AND operator considers the statement to be valid if both the two statements on which operator is applied are true . In other words we can say that , logic is true iff both A and B are true.

OR operator considers the statement to be valid if any one statement among the given is valid .
In other words logic is true if any one operand is true .

NOT operator compliments the logic . That is it changes true to false and vice versa.

for more clarification consider the table below :

     A
     B
A&&B
  A||B
      0
      0
      0
      0
      0
      1
      0
       1
      1
      0
      0
       1
      1
      1
      1
        1


Conditional operators :We have only one conditional operator called  TERNARY operators.
the operator is represented by  ?:  and it works like an if else statement .
consider the following statement 
                                                           
a>b?a:b

It means that "If a>b then a Else b" 


Relational Operators :


Relational operators are basically used to compare two numbers. 
in JAVA we have the following relational operators . 


( > , < , >= , <= , == )  and these are (greater than , less than , greater than equl to , less than equal to , to check the equality) respectively .

Bit -Wise Operators :

Bit Wise operators are  (&,|, ^, >> ,<<).

Now the point is that what is the difference between logical and Bit-Wise operators ?

Both of the operators perform AND , OR operation but the difference is in the way they perform .
in BIT-WISE operators the operands are first converted into the binary form  i.e.  bits and then the operation is performed .



Increment and Decrement Operators :

These operators are called UNARY OPERATORS as they operate on a single Operand.
Increment operator increments the number and operates in two ways : 

++a  and  a++  :


a++
(Post increment)
++a
(Pre Increment)
Consider the following expression :
 int a = 10 ;
int b = a++; 
It will first assign the value of ‘a’ to ‘b’ and then will increment ‘a’.


The output of the above expression would be :

a = 11
b = 10

Consider the following expression :
 int a = 10 ;
int b = ++a ;

It will first increment the value of ‘a’ and then will assign the value to ‘b’.

The output of the above expression would be :

a = 11
b = 11



                               


Same is in the case of decrement operator . It decreases the value of operand by 1 . 
In decrement operator also we have same same post decrement ans pre decrement and they work in similar way :


a--
(Post increment)
--a
(Pre Increment)
Consider the following expression :

int a = 10 ;
int b = b-- ;

It will first assign the value of ‘a’ to ‘b’ and then will decrement ‘a’.


The output of the above expression would be :

a = 9
b = 10

Consider the following expression :

int a = 10 ;
int b = --b ;

It will first decrement the value of ‘a’ and then will assign the value to ‘b’.


The output of the above expression would be :

a = 9
b = 9



                                

Friday, 6 June 2014

Java Basic Syntax


When we consider a Java program it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
  • Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
  • Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.
  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {

   /* This is my first java program.  
    * This will print 'Hello World' as the output
    */

    public static void main(String []args) {
       System.out.println("Hello World"); // prints Hello World
    }
} 
http://www.vogella.com/tutorials/JavaIntroduction/images/xfirstjava10.png.pagespeed.ic.-1pEz75_iy.png 
 















How To Save The File ?


Let's look at how to save the file, compile and run the program. Please follow the steps given below:
  • Open notepad and add the code as above.
  • Save the file as: MyFirstJavaProgram.java.
  • Open a command prompt window and go o the directory where you saved the class. Assume it's C:\.
  • Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
  • Now, type ' java MyFirstJavaProgram ' to run your program.
  • You will be able to see ' Hello World ' printed on the window.
C : > javac MyFirstJavaProgram.java 
C : > java MyFirstJavaProgram  
Hello World

Basic Syntax:



About Java programs, it is very important to keep in mind the following points.
  • Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
  • Class Names - For all class names the first letter should be in Upper Case.

    If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.

    Example class MyFirstJavaClass
  • Method Names - All method names should start with a Lower Case letter.

    If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

    Example public void myMethodName()
  • Program File Name - Name of the program file should exactly match the class name.

    When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).

    Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
  • public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program..

 

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  • After the first character identifiers can have any combination of characters.
  • A key word cannot be used as an identifier.
  • Most importantly identifiers are case sensitive.
  • Examples of legal identifiers: age, $salary, _value, __1_value
  • Examples of illegal identifiers: 123abc, -salary

 

Java Modifiers:

 

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:
  • Access Modifiers: default, public , protected, private
  • Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.

 

Java Variables:

 

We would see following type of variables in Java:
  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static variables)

 

Java Arrays:


Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

 

Java Enums:


Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.

 

Example:

class FreshJuice {

   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize size;
}

public class FreshJuiceTest {

   public static void main(String args[]){
      FreshJuice juice = new FreshJuice();
      juice.size = FreshJuice. FreshJuiceSize.MEDIUM ;
      System.out.println("Size: " + juice.size);
   }
}
Above example will produce the following result:
Size: MEDIUM
Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.


http://3.bp.blogspot.com/-H9IQJU5kzz8/UCKgokKbetI/AAAAAAAAAaQ/Z82XypH8e9o/s1600/JAVAKEYWORD.png





















































 

 

 

 

 

 

 

 

 

 

Comments in Java

Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{

   /* This is my first java program.
    * This will print 'Hello World' as the output
    * This is an example of multi-line comments.
    */

    public static void main(String []args){
       // This is an example of single line comment
       /* This is also an example of single line comment. */
       System.out.println("Hello World"); 
    }
} 

 

Using Blank Lines:

A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.

 

Inheritance:

 

In Java, classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario the existing class is called the superclass and the derived class is called the subclass.

 

Interfaces:

 

In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.

Data Types in JAVA

Primitive Data Types :

This kind of data types have fixed size . Here is the list of various Primitive data types in JAVA with their corresponding size .

  1.   short       :  Size 2 bytes 
  2.  int            :  Size 4 bytes
  3.  long         :  Size 8 bytes
  4. double      :  Size 8 bytes
  5.  char         :  Size  2 bytes
  6.  boolean   :  Size 1 bit


NON - Primitive Data Types : 

This kind of data types have variable size ... i.e. can have user defined size .
In JAVA we normally have three types of data types as non primitive data types :

  1. Classes
  2.  Array
  3.  String 


Size of these data types is defined by user and we will check later in the blog .

Thursday, 5 June 2014

Beginning with programming in JAVA

Getting Started With Basic Programs And Concepts :

The first very basic program to start with is :

  • TO PRINT HelloWord on the screen 
The coding initially can be done in notepad . For better understanding of programs , beginners are suggested to work on notepad and use command prompt for compilation and to run the program .

Coding to print the HelloWord is given as well as explained below :




Every word used in the above program has a specified meaning. Note that JAVA is a case sensetive language . In the above program some words have their first letter capital . All these concepts are explained below :

class
It is a reserved keyword used to create a class . This keyword is used as it is in the program . Every Program in java begins with the formation of class.

Hello
It is the name of class. First letter of the name of class should be capital . Not every time , but sometimes user can face problems in execution.

public static void main(String args[])
This whole statement works as void main()  in C++ . Note that execution of a program starts from this statement .  

public : It is a access specifier . There are three types of access specifiers . we will discuss the concept of access specifiers later . public here implies that any other program or method can access this class .

String args [] : It is a Command Line Argument (CLA) . S of String should be capital. It is a inbuilt class and note that in java whenever inbuilt class is used ... first letter is always kept capital. 

This whole statement is used to define the main program . The execution starts from here .

 System.out.println("HelloWord"); :

It works like cout command in C++ . To print the content on screen this command is used . System  is again an inbuilt class and hence S is kept capital. out  is a variable and println is a method . Functions in C++ are called methods in java . 

Note that there is difference between println and print command 
 In println command , the string or output is printed in next line . println command breaks the line and moves to next line whereas in simple print command , output is printed in the same line.

After typing this program in notepad , save the file with file name
                                                                 Hello.java
Note that the name of class and name of file should be exactly same. And the extension of file must be .java

Suppose that file is saved in followind address  :
                                                     C:\Users\HP\workspace

Then in command directory must be changed in following way :



Now to compile the program , the command given is    javac (Name of file).java
If there is no error in compilation process or program , cmd will ask for next command else a set of errors will appear on screen .
For error free program , we can run the prograam with the following instruction :  java (Name of file ) .

For  clarification refer the image :




NOTE : 
Before starting this whole process make sure that valid version of JAVA is installed on your system and also for execution of programs on cmd user must the change the PATH .

Wednesday, 4 June 2014

JAVA

Java is a programming language and is second mostly used language worldwide. Java is used for programming due to the following features provided by this language. Java Language is presently under Oracle company.

Features of JAVA :

  • Simple language
             Java is considered as a simple language because no pointers are used in its programming. Use of                  pointer on C++ is considered as the most difficult part in C++
  • Highly secure
              Java is said to be a secure language as for hacking purposes hackers use concept of pointers . They  get the address and the value t can be easily accessed with the help of pointers if they know the address  once. No pointers are used in java , hence programs , application in java and websites made in java  cannot be hacked easily.
  • Platform independent  
             Program made in one Operating system can  be used on any Operating system. A program or application made in java can easily run on all operating systems.
    

        What makes JAVA platform independent?
         Compilation and generation of output of JAVA languauge worksinthe following way :

               .Class is a byte code and is comman for all Operating Systems. This feature makes the language                     platform indepedent.

  • Open Source
         All the files and directories and coding can be accessed from the jdk folder inside the java  folder.
        C:\Program files\Java\jdk

  • Robust
          Exception handling provided in java makes the language error free. This feature is called robust.

  • Java - A 3 Tier language
           Any software is said to be a 3-tier language if it offers the following three layers :
               1. Presentation Layer
               2. Business Layer
               3. Data Layer              
   
     Presentation layer consists if the user interface (UI) . Business layer comprises of logic designing. And Data Layer is meant for Database management. 

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes