Translate

Sunday 21 December 2014

Variable Length Arguments in java

Java supports variable length argument of one data type. That is we don't need to define number of arguments when its variable for one type of data-type.

For example:-
class Calculator
{
    public int sum (int... a)
    {
        int total=0;
        for(int i=0; i < a.length; i++)
                    total+= a[i];
        return total;
    }
}

A variable length argument allows us to pass any number of arguments while calling the method.
There can be only one variable length argument in a method and if  present it must be the last parameter.

for example
public void method(String S, float f, int... a)
{
   .......
}

Variable length argument reduces number of method if method overloading is being done on the basis of number of parameters.

Saturday 20 December 2014

Constructors in Java

Constructors are special methods that are called automatically when an object of the class is created. Constructor have same name as the class and they dont have a return type not even void.
Basically there are 3 types of constructors

  1. Default
  2. Parameterized
  3. Copy-constructor
Default Constructor:- This constructor takes no argument. It is called when an object is created without any explicit initialization.
              Money m1 = new Money();
If we have not defined any constructor then default constructor is provided by java.

Parameterized Constructor:- This constructor is called when object is created  and initialised with some value at the time of creation.
               Money m1 = new Money(1000,20);

Copy Constructor:- This constructors is called when an object is created. It's initialised with some other object of class at the time of creation.
               Money m1 = new Money(1000,20);             
               Money m2 = new Money(m1);

Definition of constructor looks like this
class Money
{
    private int rs, paisa;
    public Money()
    {
         rs = paisa = 0;
    }
    public Money (int r, int p)
    {
         rs = r;
         paisa = p;
    }

    public Money (Money m)
    {
         rs = m.rs;
         paisa = m.paisa;
    }
    public void set (int r, intp)
}

Always remember that we can call a method from an another method of the same class, simply by using it's name. 

this keyword in java

'this' is a reference variable that refers to the object that has called the member function. 'this' is available in all methods of a class except static methods. It is created implicitly so we don't need to declare it.

class Money
{
     private int rs, paisa;
     public void set (int rs, int paisa)
    {
       this.rs = rs;
       this.paisa = paisa;
    }
}

Now in above example rs and paisa to the left of equal op belongs to class and to the right are arguments passed.

Method Overloading in Java

While defining a method it is compulsory to specify return type, otherwise it would give a compile time error. In java following syntax is followed to define a method.

access_specifier return_type method_name(argument 1, ..., argument n)
{
    .....//main body
}

method_name(argument 1, ..., argument n) is known as signature of method.
We can have as many methods in our class as we want as long as their signature is different. We can have multiple methods with the same name as long as their argument list are different. This is called Method Overloading. Either no of argument must be different or type of argument must be different or order of argument must be different.

For example:-

class Calculator
{
    public int sum(int a, int b)
    {
        return a+b;
    }
    public int sum(int a, int b, int c)
    {
        return a+b+c;
    }
    public float sum(int a, int b)
    {
        return a+b;
    }
}

class Java
{
    public static void main(String Args[])
    {
         Calculator calc = new Calculator();
         int x,y;
         float f1;
         x = calc.sum(3,4);
         System.Out.Println("3+4=" + x);
         y = calc.sum(3,4,5);
         System.Out.Println("3+4+5=" + y);
         f1 = calc.sum(1.2f, 1.4f);
         System.Out.Println("1.2+1.4=" + f1);
    }
}

Method overloading is an example of compile time Polymorphism.

Wednesday 3 September 2014

Object Oriented Programming (Class)

If a problem is solved in terms of classes and objects. It is called OOP.

Class:-
A class provides definition for an object. Normally variables of a class are declared as private members which are directly not accessible to the user and methods form public part of class which is accessible to user.
Object is an instance of a class.

Lets do an example:-
class Money
{
    private int rs;
    private int paisa;
    public void set(int r, int p)
    {
        rs = r;
        paisa = p;
    }
    public void show()
    {
        System.out.print(rs + " " + paisa);
    }
}

Save it as Money.java

class UseMoney
{
    public static void main(String args[ ])
    {
        Money m;
        m1 = new Money();
        m1.set(100,20);
        System.out.print("First amount is");
        m1.show();
        Money m2 = new Money();
        m2.set(200,30);
        System.out.print("Second amount is");
        m2.show();
    }
}

Save it as UseMoney.java
Then compile
c:> javac Money.java
c:> javac UseMoney.java
Now you have compiled these two java files. Now you have to run the file which contains main function.
c:> java UseMoney

This will execute your java program.

Sunday 31 August 2014

String Buffer Class

String buffer objects are used to store character sequences but they are mutable objects which means that they can be altered directly.

Creating a String Buffer Object:-
StringBuffer s1 = null;
StringBuffer s2 = new StringBuffer();
StringBuffer s3 = new StringBuffer("JAVA");
StringBuffer s4 = new StringBuffer(1000);     // Size of string buffer is 1000

By default initial memory allocated to s2 is 16 characters.
For s3 it is 4+16 characters.
So when we create a StringBuffer object, by default memory is allocated for 16 characters. When we create a StringBuffer object and initialize it with string. Then memory allocated will be length of string and 16 characters more. We can also create object with specified memory.

StringBuffer s3 = new StringBuffer("JAVA");
System.out.println(s3.capacity);                // 4 + 16
System.out.println(s3.length);                    // 4

The capacity of StringBuffer object is no of characters it can hold at any instant and length is the number of character it is holding.

Garbage Collector

In Java garbage collector is a low priority thread that runs automatically and destroys the objects that are not being referred to by any reference variable. We can request to run garbage collector by System.gc( ). It is not guaranteed that this request would be fulfilled.

e.g
1.)
String s1="xy";
String s2=s1;
s1=s1+z;
s2=s1;
s1=null;      //"xy" is now eligible for garbage collection
s2=null;


2.)
void Method1( )
{
    String s1 = "xy";
    String s2;
    s2 = method2(s1);
    s2 += "cd";
    s2 = null;
}      //s1 is local variable so after the end of method Method1 "xy" is eligible for garbage collection

String Method2(String s3)
{
    s3 = "Java";
    return s3;
}

Tuesday 26 August 2014

Command line arguments in java

While running a program at the command prompt we can pass some arguments to it. These arguments are command line arguments. They are stored in String args[ ] which we use in public static void main(String args[ ]).

e.g.   c:> java Demo C++ C# C
Interpreter will take it as
c:>java Demo.main(new String[ ]={"C++", "C#", "C"})

//Program to read names from command prompt
class Demo
{
    public static void main(String args[ ])
    {
        for(int i=0; i<args.length; i++)
            System.out.println("Hello"+args[i]);
    }
}

To execute this open command prompt.
c:> javac Demo.java
c:> java Demo Dipesh Shubham Chetna
Hello Dipesh
Hello Shubham
Hello Chetna

String class

String is basically group of characters. e.g Dipesh  this word is made of 6 characters and is a string.

Creating a String object:-
String s1 = null;
String s1 = "Java";
String s3 = new String('Java');

String class objects are immutable objects which means that they can't be changed. It always creates a new object when we try to change them.

String s1 = "ab";     //s1 is pointing to a memory location which has ab
s1 = s1 + "cd";      //as discussed earlier + concatenates two strings. Here s1 starts pointing to a new                                                         memory location which has abcd.

Array of strings:-
We can define an array of strings in the same way we define an array of primitive data types.
String arr[ ]=new String[ 5 ];
We can also assign values to them as we do it primitive data types.
arr[0] = "c++";
arr[1] = "Java";
arr[2] = "c";

for(int i=0; i<arr.length; i++)
      System.out.print(arr[i]);

length:-
It is used to determine number of character in String object.
String str = "abcd";
System.out.print(str.length);

replace( ):-
It is used to replace  a character with another character through out a String.
String s = "Java";          //s is pointing to a memory location which has java
s = s.replace('a','b');     //now s is pointing to a new memory location which has jbvb

Comparing Strings:-
== (equality operator) can't be used to compare 2 string object or any other class objects. It performs shallow comparison i.e. it compares that 2 reference variable hold same reference or not.
equals( ):- It is used to perform deep comparison i.e. it compares whether content of 2 string object are equal or not. It is case sensitive.


Monday 25 August 2014

Double dimensional array in java

Double Dimensional Array in java is used to store data in tabular format. To access an individual element of DDA we require 2 indexes:- Row index and Element index.

Declaring DDA variable:-
int arr[ ][ ];
int [ ]arr[ ];
int [ ][ ]arr;


Defining DDA variable:-
arr = new int[4][3];  // here 4 is no of row and 3 is no of column
arr.length = no of row
arr[i].length = no of column


Initialising DDA:-
int arr[ ][ ] = {{90, 80, 70},{40, 50,60},{30, 20, 10}};


Assigning DDA:-
for(i=0; i<arr.length; i++)
    for(j=0; j<arr[i].length; j++)
        arr[i][j] = 100;

Thursday 21 August 2014

Single dimensional array in java

An array is a group of variable of same data type. Each element in array is assigned a unique number to identify it uniquely. This is called subscript or index. The index starts with 0.

In java an array is created in 2 steps:-

Declaring array variable:-
int arr[ ];
int [ ]arr;
These statements declare an array variable that will refer to an array that we have yet to define. No memory is allocated at this point.


Defining the array:-
arr = new int[5];
This statement creates an array of size 5 of type integer and reference to array is assigned to variable arr.
int arr[ ];                          // same as  int *arr;  in c++
arr = new int[5];             // same as arr = new int[5]; 

In java when array is created all array elements are initialised to their default value automatically.
integer default value = 0
floating default value = 0.0
boolean default value = false
character default value = '\0'                      //null

In java each array has a length variable associated with it that returns number of elements in the array.
int arr[ ] = new int[5];
System.out.print(arr.length);
This will print the array size which is 5 here.


Array index:-
We can use any arithmetic expression on an array index. If we specify an invalid index it will throw an exception at run time.
Array Index Out Of Bound Exception
A long type expression is not allowed as an array index. It is compile time error.

Example:
int a[ ]= {25, 35, 45};                 //valid
int b[ ]= new int[]{25, 35, 45};    //valid
int c[ ]= new int[3]{25, 35, 45};  //not valid as when we defined array size as 3 it is already initialised with 0.
int d[ ]= {10,20,30};                    //valid
int e[ ]= d;                                    //valid as we know int e[ ] is same as int *e in c or c++ which is a pointer                                                                        so it can point to any other memory address already existing.

Monday 18 August 2014

Program to read 2 values and display sum

class Sum
{
    public static void main(String args[])
    {
         int a, b;
         Console con = System.console();
         a = Integer.parseInt (con.readLine());
         b = Integer.parseInt (con.readLine());
         sum = a+b;
         System.out.print("Total is :- "+sum);         //we can also wrote con.printf("%d",sum);
    }
}

Reading an input and Creating object of a class

Object:-
Lets assume there is a class Matrix.
To create its object we will simply write
Matrix m = new Matrix();
OR
Matrix m;
m = new Matrix();

Reading an input:-
Here we will create object of console class to read a number, For this we will have to import java.io.*;

Console con = System.console();
String str;
str = con.readline();

Sample code:-
import java.io.*;
class ReadData
{
    public static void main(String args[])
    {
        Console con = System.console();
        String name, city;
        System.out.println("Enter your name");
        name = con.readLine();
        System.out.println("Where do you live?");
        city = con.readLine();
        System.out.println("Hello "+name+" from "+city+" You are welcome" );
    }
}

Basic errors in assignments

1. Local variables of a method are never initialised automatically. It would be a compile time error if we try to access them without initialisation.

2. int a;
   System.out.print(a);
  This is compile time error as a is not initialised.

3. int a=4, b;
    if(a==4)
        b=5;
   System.out.print(a);
   This is compile time error because variable expression a==4 will be checked at run time. So b will be uninitialised at compile time.

4.  int a=4, b;
     if(a==4)
        b=5;
    System.out.print(a);
    This is right as due to final a==4 is a constant expression and will be checked at compile time.

5. String str = "25";
    int no;
    no = str;   //Compile Time error
 This will be a compile time error. To remove error we should use
    no= Integer.parseInt(str);
 parse is a static method in Integer class which returns the integer conversion of the string.

Break and Continue statement

Break:-
It is used to skip remaining statement of the loop and shift the control out of the loop or switch.
e.g.
while(condition)
{
    ....
    ....
    while(condition)
    {
        ....
        ....
        break;                        // breaks inner loop
    }
    break;                            //breaks outer loop
}

Unreachable code is not allowed in java it is compile time error.
while(condition)
{
    ....
    ....
    break;      
    ....                 //This statement is always unreachable as break will break the loop.
}                       // This is not allowed in java.

Continue:-
Continue is used to skip remaining statements of the loop and perform next iteration.
e.g.
while(condition)
{
    ....
    ....
    if(condition)
        continue;    //This will start the loop again.
    ....
    ....
}

Continue should never be used without condition otherwise loop will become infinite loop.

Saturday 16 August 2014

Iteration of statements (Looping)

Repetitive execution of a statement is known as iteration or loop.

While loop:-
while(boolean expression)
   statement;

This loop runs till the condition is true. Compiler first checks the condition in while loop, if its true then statements under while loop are run then condition is checked again and iteration occurs.
In case of while loop initially condition is checked then loop runs.
e.g.
int a=5;
while(a<10)
{
    System.out.println("Loop");
    a++;
}
here Loop will be printed 5 times.


Do while loop:-
do
    statement;
while(boolean expression);

Do while also runs as a while loop statement. But here statement is executed first then condition is checked. Which means statement is executed once, whether condition is true or false.
int a=5;
do
{
    System.out.println("Loop");
    a++;
}while(a<5);
Here condition is false still Loop will be printed once.


For loop:-
for(initialization; condition; action part)
     statement;

Here compiler first goes to initialization part then checks the condition then after executing statement under for loop it goes to action part then checks the condition part and continues doing so till condition is false. Here initialization is done only once when loop starts then only condition and action part is run.
for(int i=0; i<5; i++)
    System.out.println("Loop");
Here first i will be assigned to 0 and then it starts printing Loop for 5 times.


If loop never ends then it is known as infinite loop.

Friday 15 August 2014

Conditional operators in java

? and : are conditional operators in java. They are used as shown below.
variable = (boolean expression) ? true part : false part

e.g
c=  ( a>b ) ? a : b;

It means 
if (a>b)
    c =a;
else
    c=b;

Conditional Statements (if else switch)

If else statements:-

If, else, switch statements are formed using boolean expression and they are used to alter the sequence.

e.g
if( a>=90 && a<=100 )
   System.out.println("A grade");
else if( a>=80 && a<90)
   System.out.println("B grade");
else
   System.out.println("Fail");

Here if variable a lies in 90-100 (including both than it will print A grade).
Here && stand for logical AND which means both conditions a>=90 AND a<=100 should be true for if condition.

Instead of && we can also use || which is logical OR.
if( a<0 || a>0 ) means either a should be less than zero OR a should be greater than zero.

! stands for logical NOT

== is used for equality check and single = is used as assignment so always use  == (double equal to) for equality check.

else if condition is checked if, if condition above it is false.
else condition is checked if, if or else if condition above it is false.


Switch statements:-

If else is used for a condition check on set of values. Switch case is used for a specified value check.
e.g
switch(a)     //here a can be integer or character type only.
{
     case 1:  ..........
                 break;
     case 2:  ..........
                 break;
     default:  ..........
                 break;
}

Here if a is 1 then compiler goes to statements written in case 1 and starts executing. It runs till it finds break.


default is executed when above all cases are not true.
switch(a)
{
     case 1:  ..........
               
     case 2:  ..........
                 break;
     default:  ..........
                 break;
}
Here for case 1 statements in case 1 and 2 both will be executed as there is no break in case 1.

Wednesday 13 August 2014

Understanding Basic Java Program

class Demo
{
    public static void main(String args[])
    {
        int a=2, b=3, sum;
        sum= a+b;
        System.out.print("Total is:-" + sum);
    }
}

Execute it in your command prompt as discussed earlier.

Lets understand this program:-
Here class Demo creates a class by name Demo.

public specifies that the method is accessible from outside the class. (Will be discussed later in detail)

static specifies that the method is accessible without creating an object. (Will be discussed later in detail)

void specifies that the method main does not return any result to the calling environment.

String args is to store command line arguments.

int a=2, b=3, sum;   It creates 3 variable a, b, sum of integer type and assign values 2 and 3 to a and b

sum= a+b; It adds a and b and stores it in sum.

System.out.print("Total is:-" + sum); It prints Total is:- 5


Instead of System.out.print we can also use System.out.println which prints a new line character in the end.

Tuesday 12 August 2014

System.out.print method in java

System.out.print() is used to print on output devices in java programs.

To print a text with a number we use
int a = 5;
System.out.print("a = "+ a);
It prints a=5

We can also add two numbers in System.out.print()
int a=5, b=9;
System.out.print(a+b);
It will print 14

If the first two value passed to System.out.print() is number than it treats + as addition operator otherwise as concatenation operator.

e.g
int a=1, b=2;
System.out.print(a+b);
System.out.print(a+b+" is the sum");
System.out.print("Sum is"+a+b);

Output will be
3
3 is the sum
Sum is 12            // Instead of adding a and b + concatenates them.

Hello world program in java

class Demo
{
    public static void main(String args[])
    {
        System.out.println("Hello World!!");
    }
}


Use command prompt to run java. Please Download java as shown in
http://javaproglearner.blogspot.in/2014/08/java-lets-start.html

Also set environment variable as shown.
Open My Computer-> Properties-> Advanced System Settings-> Advanced -> Environment Variables
        -> user variables -> New ->
Now give variable name = Path
variable value = c/program files/java/jdk/bin                  (Path of java/jdk/bin in your computer)

Now to execute this program open command prompt in your windows PC and enter

c:> javac Demo.java
c:> java Demo

Monday 11 August 2014

Bitwise shifting operators in Java

Bitwise operators are used to manipulate individual bits of a variable.
In java -ve value is always stored in two's complement form.


Left shift operator (<<):- This operator is used to shift individual bits of a variable towards left by specified number of location and fills the vacant places with zero. In simple terms if we write

a = b << n;
It means a = b * (2 ^ n);

int a = 2;
a = a << 4;
it means bits of a should shift left 4 places
a = 2 = 0000 0000 0000 0000 0000 0000 0000 0010   //bits representation
now after left shifting
a = 0000 0000 0000 0000 0000 0000 0010 0000
i.e. a = 32 = 2 * (2^4)



Signed right shift operator (>>):- This operator is used to shift individual bits of a variable towards right by specified number of location and fills the vacant places with sign bit. In simple terms if we write

a = b << n;
It means a = b / (2 ^ n);

int a = 32;
a = a >> 4;
it means bits of a should shift right 4 places
a = 32 = 0000 0000 0000 0000 0000 0000 0010 0000   //bits representation
now after right shifting
a = 0000 0000 0000 0000 0000 0000 0000 0010
i.e. a = 2 = 32 / (2^4)

int a = -32
a = a >> 4;
a = -32 = 1111 1111 1111 1111 1111 1111 1110 0000
now after right shifting we will use sign bit to fill the spaces which is 1 here
a = 1111 1111 1111 1111 1111 1111 1111 1110
i.e. a = -2 = -32 / (2^4)


0 fill right shift operator (>>>):- This operator is used to shift individual bits of a variable towards right by specified number of location and fills the vacant places with 0. For +ve number both right shift operator are same.

In case of -ve number.

int a = -32
a = a >>> 4;
a = -32 = 1111 1111 1111 1111 1111 1111 1110 0000
now after right shifting we will fill vacant places by 0 here
a = 0000 1111 1111 1111 1111 1111 1111 1110

Note:- Bitwise operators can be applied to INTEGER variables only.

Datatype Conversion in java

Let's take an example
int a = 25;
double b = 3.14;
a = b;      //compile time error
In c language this is not an error and a would become 3. But in java narrowing of datatype is not allowed.
As discussed in http://javaproglearner.blogspot.in/2014/08/data-types-in-java.html size of datatype varies from 1 byte(8 bit) to 8 bytes(64 bits). So if you want to assign a double value to integer basically you are trying to store data of 8 bytes into 4 bytes. Java does not support this. It is a compile time error.

But,
a = (int) b;
This statement is valid. This is known as explicit typecast. In simple language here we are asking a double type variable b to behave like an integer and then assigning it to integer variable a.

Similarly,
int a = 25;
float b = 6.2f;
double d = 9.14;
a = (int) b;
b = (float) d;

These are all valid statements.

Expressions in java

An expression is a valid combination of operators and operands.
In general there are two kind of expressions.
Constant expression and variable expression
  • Constant expression:- Operands are either literals or constants. These are evaluated at compile time.

e.g. 3+2, 9*8
  • Variable expression:- If any operand is variable than it is  variable expression. These are evaluated at run time.
e.g. a+b, b/c


Sunday 10 August 2014

Identifier Literals and Constant in Java

Identifier:-
The name we choose for a variable is called an identifier. An identifier can be of any length but it must begin with an alphabet, underscore or ‘$’  the rest of an identifier can include digit also.
Operators and spaces are not allowed in an identifier. We can’t use java keyword also. Keywords are words that are an essential part of java. Java is case sensitive language.
Name of class should start with capital letter only.

e.g.
max, Max, maX, MAX all are different
ab$cd         right
ab_123       right
_abcd         right
ab+cd        wrong
ab@cd      wrong
_ab123      right
123ab       wrong
while         wrong it is a keyword
While         right


Literals:-
Explicit data values that appear in our program are called literals.
int a = 25;      here a is variable and 25 is literal.


Constant:-
If a variable is declared final its value can’t be changed
final int MAX=100;                 constant name should be in capitals only.

Data Types in Java

There are eight data types supported by Java. Primitive data types are predefined by java and named by a keyword.

byte:
  • ·         It is 8-bit integer.
  • ·         Range:- Minimum value is -128 (2^7) Maximum value is 127 (2^7 -1)
  • ·         Default value is 0.
  • ·         Example: byte a = 100 , byte b = -50

short:
  • ·         It is a 16-bit Integer.
  • ·         Range:- Minimum value is -32,768 (-2^15) Maximum value is 32,767 (2^15 -1)
  • ·         Default value is 0.
  • ·         Example: short a = 15000, short b = -15000

int:
  • ·         Int data type is a 32-bit integer.
  • ·         Range:- Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(2^31 -1)
  • ·         The default value is 0.
  • ·         Example: int a = 100000, int b = -200000

long:
  • ·         Long data type is a 64-bit integer.
  • ·         Range:- Minimum value is -2^63 Maximum value is 2^63 -1.
  • ·         Default value is 0L.
  • ·         Example: long a = 100000L, long b = -200000L

float:
  • ·         Float data type is a single-precision 32-bit IEEE 754 floating point.
  • ·         Default value is 0.0f.
  • ·         Example: float f1 = 234.5f

double:
  • ·         double data type is a double-precision 64-bit IEEE 754 floating point.
  • ·         Default value is 0.0d.
  • ·         Example: double d1 = 123.4

boolean:
  • ·         boolean data type represents one bit of information.
  • ·         Only two possible values: true and false.
  • ·         Default value is false.
  • ·         Example: boolean one = true

char:
  • ·         char data type is a single 16-bit Unicode character.
  • ·         Range:- Minimum value is '\u0000' (or 0)  Maximum value is '\uffff' (or 65,535 inclusive).
  • ·         Example: char letter ='A'

Java: Let's Start

Java!!
What is java? Some programming language. Blah blah blah. :P
First we have to understand what is programming language? :O
Programming language is a formal language written by user to instruct a machine.
Java is an Object Oriented Programming language created by sun microsystems in 1995. Java is used to create applet and application programs.
Applets are java program that are embedded within a web page.
Application programs are programs that are written for a specific application and which can run on any machine supporting java.
In java first program is compiled then interpreted. For compilation of java code we need JVM (Java Virtual Machine). Java is platform independent but JVM is platform dependent.  JVM is combination of OS and Java interpreter. Here we are going to use Java on windows platform.

To run java into your system first you have to install JDK. You can find it online.
Please follow this link for installation or you can google it. Please set the environment variables too.

http://docs.oracle.com/javase/8/docs/technotes/guides/install/windows_jdk_install.html

Now to compile a java program open your command prompt.
c:>javac Demo.java
javac is the compiler that compiles our Demo.java program and creates a file with the extension .class.
class file contains byte code which are binary instruction for java interpreter.
To run application program after compilation enter
c:>java Demo
This will execute the file.  Always save the java file name with the name of class.





Total Pageviews