Friday, August 11, 2017

Introducing Classes and Object


Class

Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.

A class contains

      Data Member

      Method

      Constructor

      Block

      Class and Interface



Object

 Object is an instance of class.

An Object has three characteristics

      State

      Behavior

      Identity

State: Represents data of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.


Difference between Class and Object
















Syntax to declare a Class

class Class_Name

{

data member;

 method;

}

Syntax to create an Object

Class_name ObjectName=new Class_name();



Example

class Employee

{

 int eid; // data member (or instance variable)

 String ename; // data member (or instance variable)

eid=101;

ename=“ram";

public static void main(String args[])

{

Employee e=new Employee(); // Creating an object of class Employee

System.out.println("Employee ID: "+e.eid);

System.out.println("Name: "+e.ename);
 }
}


Basic IO


Java I/O (Input and Output) is used to process the input and produce the output.

It uses the concept of streams to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

Stream

A stream is a sequence of data. In Java a stream is composed of bytes.

In java,3 streams are created for us automatically. All these streams are attached with console.



1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream



Let's see the code to print output and error message to the console.

System.out.println("simple message");  

System.err.println("error message");  



Let's see the code to get input from console.



int i=System.in.read();//returns ASCII code of 1st character  

System.out.println((char)i);//will print the character  


Output Stream vs Input Stream



OutputStream

Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.

Reading Console Input



In Java, there are 3 ways to read input from a console.

  1. BufferedReader + InputStreamReader (Classic)
  2. Scanner (JDK 1.5)
  3. System.console (JDK 1.6)





1. BufferedReader + InputStreamReader

InputStreamReader  that can read data from the keyboard.



Syntax

InputSteamReader obj = new InputStreamReader (System.in);



Connect InputStreamReader to BufferReader, which is another input type of stream to read data properly.

Syntax

BufferedReader br = new BufferedReader (obj);

two steps can be combined and rewritten in a single statement

Syntax

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
 

Now, we can read the data coming from the keyboard using read () and readLine () methods available in BufferedReader class.
2. Scanner Class
In JDK 1.5,the developer starts to use java.util.Scanner to read system input.
Syntax
Scanner scanner = new Scanner(System.in);

3. System.console

In JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class to read system input.
 It provides methods to read texts and passwords.
syntax
Console c=System.console();  

 Writing Console Output

PrintStream is an output stream derived from OutputStream,it also implements the low-level method write().
write() can be used to write to the console.
Syntax
The simplest form of write() defined by the PrintStream  is
void write(int byteval)

Naming conventions

All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.
      class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
      interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
      method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
      variable name should start with lowercase letter e.g. firstName, orderNumber etc.
      package name should be in lowercase letter e.g. java, lang, sql, util etc.
      constants name should be in all uppercase letters. e.g. RED, YELLOW, MAX_PRIORITY etc.
       

Arrays


Array is a collection of similar type of data. It is fixed in size means that you can't increase the size of array at run time. It is a collection of homogeneous data elements. It stores the value on the basis of the index value.



Advantage of Array

1.      Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.

2.      Random access: We can get any data located at any index position.

Disadvantage of Array

1.      Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.



Types of Array

  1. Single Dimensional Array
  2. Multidimensional Array

 Array Declaration

Single dimension array declaration

Syntax

  1. int[] a;
  2. int a[];
  3. int []a

Multidimensional Array declaration

Syntax

  1. int[][] a;
  2. int a[][];
  3. int [][]a;
  4. int[] a[];
  5. int[] []a;
  6. int []a[];
Array creation

Every array in a Java is an object, Hence we can create array by using new keyword.

Syntax

int[] arr = new int[10]; // The size of array is 10.

or

int[] arr = {10,20,30,40,50};

Accessing array elements

Access the elements of array by using index value of an elements.

Syntax

arrayname[n-1];

every array type has  its corresponding class .

Class arr

{

Public static void main(String[] args)

{

Int[]  x=new int[3];

S.O.P(x.getClass().getName());// [I

}

}

Control Statements


Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution.

Types of control statements

  1. selection control statements.
  2. iteration control statements.
  3.  jump control statements.  

1. Selection control statements

Selection statements can be divided into the following categories.

  1. The if statements
  2. The if-else statements
  3. The if-else-if statements
  4. The switch statements

1. If statement

if statement performs a task depending on whether a condition is true or false.

Syntax:

                                    if (condition)   

                                    statement1;

2. The if-else statements.

if the specified condition in the if statement is false, then the statement after the else keyword  will execute.

Syntax:

if (condition)  

 statement1;  

else  

statement2;



3. The if-else-if statements

This statement following the else keyword can be another if or if-else statement.

Syntax

if(condition)
   statements;
else if (condition)
   statements;
else if(condition)
   statement;
else
   statements;



4. The Switch Statements

When there are several options and we have to choose only one option from the available ones, we can use switch statement.

Syntax:

switch (expression)

   {

 case value1: //statement sequence     

break;   

case value2: //statement sequence

break;      

 ………….…..   

case valueN: //statement sequence  

   break;   

default: //default statement sequence 

 } 



2. Iteration Statements

Repeating the same code fragment several times until a specified condition is satisfied is called iteration.

the following loop for iteration statements

  1. The while loop
  2. The for loop
  3. The do-while loop
  4. The for each loop





1. The while loop

It continually executes a statement while a condition is true. The condition must return a Boolean value.

Syntax:

while (condition)  

{   

statements; 

 }



2. The do-while loop

The only difference between a while and a do-while loop is that do-while evaluates its expression at the bottom of the loop instead of the top. The do-while loop executes at least one time then it will check the expression prior to the next iteration.

Syntax

      do  

        {  

             //Statements

        }  

        while ( condition);  



3. The for loop

A for loop executes a statement as long as the Boolean condition evaluates to true. A for loop is a combination of the three elements initialization statement, Boolean expression and increment or decrement statement.

Syntax:

for(<initialization>;<condition>;<increment or decrement statement>)

     {     
//block of code
}



4. The For each loop

This was introduced in Java 5. This loop is basically used to traverse the array or collection elements.

Syntax

for(data_type variable : array | collection)

{

}  







3. Jump Statements

Jump statements are used to unconditionally transfer the program control to another part of the program.

Java provides the following jump statements

  1. break statement
  2. continue statement
  3. return statement



1. Break Statement

The break statement immediately quits the current iteration and goes to the first statement following the loop.

2. Continue Statement

The continue statement is used when you want to continue running the loop with the next iteration and want to skip the rest of the statements of the body for the current iteration.

3. Return Statement

The return statement is used to immediately quit the current method and return to the calling method. It is mandatory to use a return statement for non-void methods to return a value.

Saturday, August 5, 2017

Operators


Operator is a symbol that is used to perform operations.
Types of operators in java

  1. Arithmetic operators
  2. Relation operators
  3. Logical operators
  4. Bitwise operators
  5. Assignment operators
  6.  Ternary operator
  7. Unary Operator
Arithmetic operators

Arithmetic operators are used in mathematical expression.

Relation operators



Logical operators
Bitwise operators

Assignment Operators
Ternary operator
It is also known as Conditional operator and used to evaluate Boolean expression.
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3

Unary Operators


Friday, August 4, 2017

Type Conversion and Casting


Assigning value of one type to variable of another type is known as conversion.

In java we have two types of conversions.

  1. Implicit type conversion.
  2. Explicit type conversion.



1. implicit type conversion
Java automatically converts from one type to another  if it satisfy the following conditions.
1 Both types are compatible with each other.
2 The size of destination type is more than the source type.
This is also known as “Widening Conversion”.
Example
int i = 3;                                   int i=5;//size of int is 32
double f;                                  long d;//size of long is 64
f = i;                                        d=I;    
Example program
class TypeConversion
{
    public static void main(String arg[])
    {
        byte b = 50;
        short s = 4125;
        int i = 800000;
        long l = 107343L;       
        s = b;    
        i = s;   
        l = i;   
        float f = 25.0f;
        double d = 327.98;
        f = i;
        d = f;
        System.out.println("b = " + b );   
        System.out.println("s = " + s );   
        System.out.println("i = " + i );   
        System.out.println("l = " + l );   
        System.out.println("d = " + d );   
        System.out.println("f = " + f );  
    }
}

2. Explicit type conversion
If we want to convert two types which are incompatible or if the size of destination type is less than the size of source type, then we must do the conversion explicitly.
This process is also called as “type casting”. This is also called as Narrowing conversion .
Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision.
Syntax
newValue = (typecast)value;
Example
double f = 3.5;
int i;
 i = (int)f; // it cast double value 3.5 to int 3.

Example program
class DatatypeCasting
{
    public static void main(String arg[])
    {
        byte b;
        int i = 81;
        double d = 323.142;
        float f = 72.38f;
        char c = 'A';
       
        c = (char) i;
        System.out.println("i = " + i + " c = " + c);
       
        i = (int) d; 
        System.out.println("d = " + d + " i = " + i); 
       
        i = (int) f; 
        System.out.println("f = " + f + " i = " + i); 
       
        b = (byte) d;
        System.out.println("d = " + d + " b = " + b);
   
    }
}

Data Types


Data type is a special keyword used to allocate sufficient memory space for the data.

Categories of data types

1.      Fundamental or primitive data types

2.      Derived data types

3.      User defined data types





1. Primitive data types
Primitive data types are those whose variables allows us to store only one value but they never allows us to store multiple values of same type.
Example
 int a; // valid
 a=10; // valid
a=10, 20, 30; // invalid


We have eight Primitive data type which are organized in four groups.
  1. Integer category data types
  2. Character category data types
  3. Float category data types
  4. Boolean category data types
1. Integer category data types

2. Character category data types
This data type takes two byte since it follows Unicode character set.

3. Float category data types
4. Boolean category data types


2. Derived data types
Derived data types are those whose variables allow us to store multiple values of same type. But they never allows to store multiple values of different types.
Example
int a[] = {10,20,30}; // valid
int b[] = {100, 'A', "ABC"}; // invalid
3. User defined data types
User defined data type related variables allows us to store multiple values either of same type or different type or both.
This is a data type whose variable can hold more than one value of dissimilar type.
Example
Student s = new Student();