Translate

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.

Total Pageviews