Go to Top

Thursday 31 March 2011

To check whether a number is negative or positive

Question 3 : Write a program in Java to to check whether a number given by the user is negative or positive.


Java Program :


public class number_type
{
 public static void main(int a)
 {
     if (a>0)
     System.out.println("The number "+a+" is positive");
     if (a<0)
     System.out.println("The number "+a+" is negative");
     if (a==0)
     System.out.println("The number "+a+" is neutral");
 }
}

Explanation : There is a simple logic applied here that if a number is greater than 0, it is positive, if it is less than 0, it is negative, and if it is equal to 0, then it is neutral.

Input : 


(i) a=10


(ii) a=-10


(iii) a=0


Output : 


(i) The number 10 is positive


(ii) The number -10 is negative


(iii) The number 0 is neutral

Friday 25 March 2011

To print a message on the screen

Question 2 : Write a program in Java to print the following message on screen : 


*****Hello World*****
  
 Welcome to Java programming
We are learning Java
                   on
BlueJ environment

Java program :

class hello_world
{
 static void main()
 {
     System.out.println("\t*****Hello World*****");
     System.out.println("\n     Welcome to Java programming");
     System.out.println("\tWe are learning Java");
     System.out.println("\t\ton");
     System.out.println("\tBlueJ environment");
  }
}

Note : Some symbols used in the above program and some others are listed along with their meaning below :


Symbols
Stand for
\n
Newline
\r
Carriage return
\t
Horizontal tab
\\
Backslash
\’
Single quotes
\”
Double quotes
\?
Question mark

Output : 


The If-Else Loop

                          This is a kind of loop in Java which is required to execute a command only if a condition is true. Its syntax is as follows :

if(condition)
{
  ----------
  ----------
}
 else
 {
  ----------
  ----------
}

                          If the condition is true, then Java will execute the commands following the if statement and neglect the else part, but if the condition is false, it will either execute the command following the else statement and will neglect the part following the if statement, or will execute no command if the else statement is not given, since it is not compulsory. But in some cases, it is very much necessary to give the else option, which will then return an "if without else" error in case if the else statement is absent. An example of its usage is given as follows :

if(n>10) (n is any number given by the user)
{
  System.out.println(n+" is not smaller than 10");
}
else
{
  System.out.println(n+" is smaller than 10");
}

(In case of a single statement, it is not necessary to give the opening and closing braces. If the braces are not found, then the statement just after the if or the else statement will be executed by Java)
                          

Thursday 24 March 2011

To check whether a number is even or odd

Question 2 : Write a program in Java to check whether a number is even or odd.

The Java program for the question is as follows :

public class even_or_odd
{
 public static void main(int a)
   {
     int b=a%2;
     if (b==0)
     System.out.println("The number "+a+" is an even one");
     else
     System.out.println("The number "+a+" is an odd one");
    }
}

Explanation : Here a number is being taken from the user by passing parameter to the method "main". Then it is checked whether it is even or odd. We know that an even number can be divided by 2 without leaving a  remainder whereas an odd number cannot be divided by 2 without leaving a remainder. It will always leave a remainder. So here we are using an operator known as modulus (symbol "%") which returns the remainder on dividing a number by another. If the mod (in short) of the the number given by the user returns 0, it means that the number is even, but if its mod returns any remainder, it means that it is an odd number.

Input :






















Output :



Monday 21 March 2011

Basics of Programming

                            Now let us start with the programming part. For programming, we need to know some basic statements and commands to write some basic programs. Let us first view the structure of a basic program and then each of its parts will be defined :


class (user defined name)
{ -------------------------------à Opening Braces ---à Indicates the starting point of the class
    public static void (user defined name)(int d) -------- à “( )” indicates a method ..........(1)
     { ----------------------------à Opening braces ---à Indicates the starting point of the method
          int a,b,c; ----------------à Defining variables (Note the semicolon at the end)
          a=10; ------------------à \   
          b=20; ------------------à  | ----à Assigning values to variables
          c=0; -------------------à /
          c=a+b; -------------------à Performing mathematical calculation (Addition) ……….(2)
          System.out.print(“The sum is “+c); ---------à Print statement ……….(3)
     } ----------------------------à Closing braces -----à Indicates closing of the method
} --------------------------------à Closing braces -----à Indicates closing of the class


(1)   ------------------------------à Keywords public, static, void : The word ‘public’ is one of the access specifiers. The other specifiers are ‘private’, ‘protected’, and ‘default’. They restrict the access to the source code to certain levels. Public allows everyone to run or edit the contents of the program. Private allows for access of the variables and methods within the same class, package, and sub-classes. Protected allows for the access of the variables and the methods within the same class only, and default allows for their access in the same package. The keyword 'static', when applied to a method, makes it independent of the object of the class. Thus it can be executed without creating and using the object of the class. The keyword 'void' declares that the method has no return type i.e. it cannot return any value, after its execution, to any other method of the class. We can specify a datatype to the method due to which it will have to return a value that has the same datatype as the method. For example : we can write "public static int display( )". We can pass a parameter to a method by declaring a variable and giving its datatype. The method will then take input from the user for the variable when the method is executed. In this way, we can take inputs from a user in Java.

(2)   ------------------------------à Arithmetical calculations : The calculation simply needs to be written just after the equal to sign i.e. “=” in the Java format. For addition, a plus sign (“+”) is to be given, for subtraction, a minus sign (“-“) is to be given, for multiplication, an asterisk (“*”) is to be given, and for division, a forward slash (“/”) is to be given. First brackets can be provided to define the order in which the calculation has to be done, but the number of opening brackets must be equal to the number of closing brackets.
 
(3) ------------------------------à Print statement : The syntax of the print statement in Java is as follows :

Syntax : System.out.print(“Text”+variable);

To print text, the text has to be put within double quotes “” inside the brackets and to print the value of a variable, the variables has to be put inside the brackets without any quotes. To print text alongwith variables, they have to be concatenated or joined together by a plus sign. System.out.println( ) is used to print the next output in a new line instead of the same line. 

Data types in Java

                                   Java provides for two types of datatypes : 
  • Primitive Datatypes.
  • Non-Primitive or Composite Datatypes.
                                  
                                   They are defined as follows : 
  • Primitive Datatypes : These are the fundamental datatypes which are not composed of any other datatype. There are eight kinds of fundamental or primitive datatypes in Java : byte, short, int, long, char, float, double, and boolean.
  1. Integers : These are the integer type numbers. The datatypes byte, short, int, long, are included in this category. Their width and range are as follows : 
          
Data type
Width in Bits
Range
long
64
-9223372036854775808 to 9223372036854775807
int
32
-2147483648 to 2147483647
short
16
-32768 to 32767
byte
8
-128 to 127
       
     2. Floating-Point Types : These are the real numbers. They can contain decimal or fractional parts. The datatypes float and double are included within this category. Their width and range are given below :

Data types
Width in Bits
Range
float
4
3.4 X 10-38 to 3.4 X 1038
double
8
1.7 X 10-308 to 1.7 X 10308

     3. Boolean : it contains the datatype Boolean. This is a special type for representation of true and false values where “0” represents false and “1” represents true.

     4. Characters : The datatype char is included in this group. It can hold any one character such as alphabets or numbers.

                                   Some examples of their usage are given below (only parts of the Java code are given below, not the full program) : 

int a;
a=5;

float b;
b=3.142;

char c;
c='a';
(Note : Character values are to be enclosed within single quotes '')

  • Non-Primitive or Composite Datatypes : These are the datatypes which are composed of the Primitive datatypes. They consist of classes, arrays, and interface. The datatype String is also a Composite datatype. It can hold any character, from alphabets to numbers to special characters and blank spaces. Some examples of their usage are as follows (only parts of the Java code are given below, not the full program) : 

String a;
s="abc123";
(Note : The string values need to be enclosed within double quotes "").

                                   Thus to sum up, you can view the following table :


Sunday 20 March 2011

Constants and Variables

                             Constants are the ones whose values are constant and never change. For example 1, 124, 9863, 123857, 10000000, etc. are all constants. Their values remain the same. But the variables do not have a constant value. They are just like the holders of a particular constant. The constant's value is assigned to the variable. They can be a letter a combination of letters (or words, though reserved keyword variables (such as null, void etc.) are regarded invalid by Java), an alpha-numeric representation i.e. containing alphabets as well as numbers (though numbers cannot be the first letter of the variable, cannot contain any special character or blank spaces are invalid variables). Examples of valid variables are a, maximum, abc123 etc. Examples of invalid variables are 12abc, abc xyz, null, a.b, etc. They can be assigned any value within their datatype. For example the constant 5 can be assigned to the variable a. This is shown in the following piece of code :

a=5;

                              Note : The variables need to be defined by using a datatype such as int, float, double, etc.before they are assigned some value. For example :

int a;
or,
double a;
                               

Monday 14 March 2011

The six OOP principles

The six OOP principles are as follows :
  • Objects.
  • Class.
  • Inheritance.
  • Encapsulation.
  • Polymorphism.
  • Abstraction.      

Now what are these? Let us take a look at them.
  1. Object : Object is anything that we create using a program. All the objects (whether made by a program or in the real world) have two main characteristics : State and Behaviour. Let us take the example of a car. A car has state i.e. its characteristics, for example colour, size, and shape and behaviour i.e. what it does, for example running, turning at curves, etc. Similarly, objects have there state or values in the variables and they behave according to the instructions given by the methods contained in them. This combination of state and behaviour i.e. variables and methods is known as an object.
  2. Class : A class is the prototype or the blueprint of the objects and contains the methods and the variables that define the state and behaviour of the object. It is just like a blueprint of the construction of a robot. It contains the information how to construct a robot. Just as the single blueprint can be used to make many similar robots, a particular class can be used to create a number of objects similar in characteristics.
  3. Inheritance : It is the process by which an object or even a class can acquire or "inherit"  the properties of other objects and classes respectively. It can be used to derive a class from another class here the derived class is called the sub-class or the child-class and the class from which it is derived is called the base-class or parent-class. There are two kinds of inheritance in Java :                                1. Simple Inheritance.                                                                                      2. Multilevel Inheritance.
  4. Encapsulation : It is the process of binding the Code and Data within a capsule to prevent any misuse of the data and the commands within the program though the user can interact with it through a interface. Here the capsule is the class which prevents the access to the code through access specifiers (public, private, protected). For example we cannot change the inside contents of a music player but we can interact with it by pressing the buttons on it. Similarly, we can interact with a program by giving values to the variables through methods but we can't edit its contents until we are granted access to it.
  5. Polymorphism : Polymorphism is the ability of an action or method to do different things based upon the object on which it is acting. This is the third OOP principle. The different types of polymorphism are as follows : Overloading, Overriding, Dynamic method binding.
  6. Abstraction : Hiding unnecessary details and showing the essential features is called abstraction.                                                                                                                                                                                                                                                                                                                                             

What is Object-Oriented Programming?

                            This is a new feature of Java. All computer programs consist of two parts : Code and Data. The programs can be organised around the Code or Data (called Process-Oriented) and the previous languages like C, BASIC did just that, but the modern languages like Java create programs that are organised around the Code as well as the Data. This is called Object-Oriented Programming. In simple words, previously, the programming languages like BASIC, Fortran etc. focussed on only providing commands to the computer and getting the job done, but the Object-Oriented Programming languages focus on both data and the commands.
                            
                              There are six important principles of this concept, called the OOP principles, which are as follows :
  • Object.
  • Class.
  • Inheritance.
  • Encapsulation.
  • Polymorphism.
  • Abstraction.

Sunday 13 March 2011

About Java



                       Java is an Object-Oriented Programming  (OOP) language. It was created by James Gosling, at Sun Microsystems. Inc, in 1991. It was initially called "Oak", until it was renamed to "Java" in 1995. Java basically consists of most of the structure of C++, but its new features include :
  • Java is an object-oriented programming language.
  • It has new concepts of concept of classes and objects.
  • Programs can be compiled as well as interpreted.
  • Java programs can create Applets.
  • It is machine-independent.
  • It has improved security.
  • The programs are re-usable.
  • Java doesn't require any preprocessor (like # in C or C++).
  • Java is case-sensitive.

    ShareThis