OOPJAVA-UNIT-1

1.HISTORY OF JAVA:
- Java is an Object-Oriented Programming Language.
- It was developed by Sun Micro Systems of USA in 1991, by a team of professionals led by James Gosling, later it was sold by Oracle in 2010.
- Java was designed for the development of software for consumer electronic devices like TVs, VCRs, toasters and such other electronic machines.
- The first name of Java is OAK.
- Later, it was renamed to Java in 1995.
- The term ‘Java’ in USA is generally a slang used for coffee.
- Java is also the name of a coffee produced on the islands of Java in Indonesia.
- Java is an open-source language.
- Open-source means it is freely available to the market and any company can develop their own applications using java.
- Java is the most popular language today because of 4 properties in it,
          - Platform Independency
          - Multithreading
          - Internet Programming
          - Distributed Programming

2. JAVA PLATFORM:
- Java platform is a bundle of related programs used to develop and run the applications written in java language.
- It has three editions.
- JavaSE (Java Platform Standard Edition) is used to develop desktop (1-tier) and web applications (2-tier) using java.
- Java Desktop applications are also called as Standalone applications.
- JavaME (Java Platform Micro Edition) is used to develop the software to run the applications on small devices such as mobiles, set-top boxes and so on.
- JavaEE ((Java Platform Enterprise Edition) is used to develop multitier, distributed and server-side applications in java.
- The tools required in JavaME are different from JavaSE and JavaEE.

3. Java Program Structure:
- The general structure of a java program is

i) Documentation Section:
- It provides a set of comment lines giving the name of the program, the author and other details.
- The comments in java are represented in two ways,
            //   Single Line Comments
          /* Multiline Comments */
Example:
//Sum of two numbers

ii) Package Statements:
- The first statement allowed in java file is a package statement.
- This statement declares a package name and informs the compiler that the classes defined here belong to this package.
Example:
package  student;

iii) Import statements:
- These statements will load and link the predefined packages those are already available in the java software.
Example:
import.java.io.*;

iv) Interface statements:
- An interface is represented same like a class.
Example:
interface  A 
{   
--------------
--------------
}
v) Class Definitions:
- A java program may contain multiple class definitions.
- These classes are used to map the objects of real-world problems.
Example:
class  A  
{   
--------------
--------------
}
vi) Main Method Class:
- This is an essential part of a java program.
- Every java standalone program requires a main method as its starting point.
Syntax:

class classname

 {

   public static void main(String args[ ])

      {

        statements;

       }

 }

- The main ( ) method contains arguments called as Command-line arguments.

- In java, the arguments to the main ( ) method must be of type String array because java reads command line values only in the form of strings.
- In java, main ( ) acts as a procedure.
- It means it doesn’t return any value.
- So the return type of the main ( ) method must be void.
- main ( ) is a static method.
- It means the JVM starts the program execution by calling the main( ) with respect to class name.
Syntax:
classname.main ( )

Example:
System.main( )

- If a method is called with respect a class name means it is a static method.

- main ( ) is a public method because it can be accessed from anywhere in the program.

4. Java Software:
- When we install java software, we get two components
            i) JDK
            ii) JRE

- JDK will provides us tools which are required for development of java applications.
JDK – Java Development Kit
JRE – Java Runtime Environment
API – Application Programming Interface

5. JAVA CHARACTER SET:
- Java characters are defined by the UNICODE (Universal Code) character set.
- It is an emerging standard that tries to create characters for a large number of scripts worldwide.
- The Unicode is a 16-bit character coding system and currently supports more than 34000 defined characters derived from 24 languages from America, Europe, Middle East, Africa and Asia (including India).
- However, most of us used are the basic ASCII characters.
- ASCII character set is a subset of UNICODE character set.
- ASCII character set contains

5. JAVA TOKENS:
- The smallest individual unit in a java program is a java token.
- There are 6 types of Java Tokens

i) Keywords:
-Keywords are the words whose meaning has already been explained to the compiler.
-Keywords are also known as reserved words.
-Keywords cannot be used as identifiers.
-All keywords will be appeared in lowercase letters.
-There are 50 keywords are available in java.

ii) Identifiers:
-Any user-defined name in a java program is called as Identifier.
-An identifier is a sequence of letters, digits, underscore and dollar sign characters.
Rules for constructing Identifiers:
- It cannot start with a digit.
- It is Case-sensitive, i.e, Uppercase and Lowercase letters are different.
- Keywords cannot be used as identifiers.
- White spaces and special symbols are not allowed except underscore ( _ ) and dollar ( $ ).
- It can be of any length.
Examples:

sum

name$

student_123

 Variables:
-A variable is a data name used to store data value.
-The values of variables change during execution.
Rules for constructing variables:
- It cannot start with a digit.
- It is Case-sensitive, i.e, Uppercase and Lowercase letters are different.
- Keywords cannot be used as identifiers.
- White spaces and special symbols are not allowed except underscore and dollar.
- It can be of any length.
 Declaration of a variable:
Syntax:
datatype   variable_list;
Example:

int a,b;

float f1,f2;

char c1,c2;

 Initialization of a variable:
Syntax:
datatype variable_1=value_1, variable_2=value_2, …., variable_n=value_n;
Example:
int a=10, b=15;
Primitive Data types in Java:
-It indicates the type of data that a variable can hold.
-The basic data types and their sizes in java are,

Type

Size in bytes

Range

int

4

-231 to 231-1

float

4

3.4E-38 to 3.4E+38

double

8

1.7E-308 to 1.7E+308

char

2

0 to 65535

-The complete set of data types in java is depicted as,


- The Integer data types are,
- The size and range of Integer data types are,

- The Floating-point data types are,

iii) Constants:
-Constants are fixed values that do not change during execution.
-Java constants are of two types

Integer constants:
-Integer constants refers to a sequence of digits that can be decimal, octal, and hexadecimal number
Examples: 
                  127 (decimal)
                  -127 (decimal)
      0127 (octal starts with 0)
      0x127 (hexadecimal starts with 0x)

Real constants:
-Real constants are represented with decimal point.
-It has two parts, decimal and fractional parts
-It can be represented in exponential notation.
Syntax: 
     mantissa E exponent
-mantissa can be either an integer or real.
-exponent should be an integer with +ve or –ve signs.
Examples:
      0.0012
      -0.25
      3.4E-38

Single Character constants:
-It contains a single character from any of Java character set which is enclosed with in single quotes.
Example:
‘5’
‘e’
‘+’

String Character constants:
-It consists of sequence of characters enclosed within double quotes.
Example:
“stud_name” 
“city”

iv) Literals:
- Literals in java are a sequence of characters (letters, digits and other characters) that represent constant values to be stored in variables.
- Java language specifies the following types of literals.
·       Integer literals
·       Floating-point literals
·       Character literals
·       String literals
·       Boolean literals
·       Null literal

- Each of them has a type associated with it.
- The type describes how the values behave and how they are stored.

v) Separators:
- Separators are symbols used to indicate where groups of code are divided and arranged.
- They basically define the shape and function of our code.


Escape Sequences in java: (Backslash Character Constants)
- The backslash( \ ) character called as Escape character and they have a special meaning in java.
- All Escape Characters are given in a table as,

Escape Sequence

Meaning

\n

Newline

\t

Horizontal Tab

\b

Backspace

\r

Carriage return

\f

Form feed

\\

Backslash

\’

Single quotes

\”

Double quotes


vi) Operators:
-An operator is a symbol that tells the computer to perform certain mathematical and logical calculations.
-The different types of Java operators are,

a) Arithmetic operators

b) Relational operators

c) Logical operators

d) Increment or decrement operators

e) Assignment operators

f) Conditional operators

g) Bitwise operators

h) Special operators

a) Arithmetic operators:

Operator

Meaning

+

Addition or Unary plus

-

Subtraction or Unary minus

*

Multiplication

/

Division

%

Modulo division

-Integer division truncates any fractional part.

-The modulo division produces the remainder of an integer division.

Examples:

a+b, a-b, a*b, a/b, a%b

A
rithmetic Expression Types:
Integer arithmetic expression:
-An arithmetic operation involving only integer operands is called integer arithmetic.
int + int = int
int - int = int
int * int = int
int / int = int (truncates decimal part)
int % int = int (results remainder)

Real arithmetic expression:
- An arithmetic operation involving only real operands is called real arithmetic.
real + real = real
real - real = real
real * real = real
real / real = real
real % real = not allowed or error

Mixed-mode arithmetic expression:
-An arithmetic operation involving one operand is real and the other operand is integer, then it is called mixed-mode arithmetic.
real+int=real
real-int=real
real*int=real
real/int=real
real%int=not allowed or error

ii) Relational operators:
-The comparison between two operands or expressions is done with the help of relational operators.

Operator

Meaning

< 

Less than

<=

Less than or equal to

> 

Greater than

>=

Greater than or equal to

==

Equality

!=

Inequality

Example:

a>b

a>=b

a<b

a<=b

a==b

a!=b


iii) Logical operators:
-The java language has three logical operators.

Operator

Meaning

&&

Logical AND

||

Logical OR

!

Logical NOT

-The logical operators &&, || are used when we we want to test more than one condition.
&& - used when all the conditions must be true.
|| - used when any of the conditions must be true.
-A logical expression yield a value 0 or 1, according to the truth table.

Operand1

Operand2

Operand1&&operand2

Operand1||operand2

Non-zero

Non-zero

1

1

Non-zero

0

0

1

0

Non-zero

0

1

0

0

0

0

Example:

(a>b)&&(a>c)

(a>b)||(a>c)

-The logical not is used as a negation or complement of the expression.

Example:
!(y<10) means (y>=10)

iv) Increment or decrement operators:

-The increment operator is ++ which means +1

-The decrement operator is - - which means -1

-The operand must be either incremented or decremented by 1.

Example:

m=5; y=++m;              results m=6 and y=6.

m=5; y=m++;              results m=6 and y=5.

m=5; y= --m;               results m=4 and y=4.

m=5; y=m--;                results m=4 and y=5.

v) Assignment operators:

-Assignment operators are used to assign the result of an expression to a variable.

Operator

Meaning

=

Assignment

-In addition, java has a set of short-hand assignment operators of the form

            V OP=EXP;

- It is equivalent to

V=V OP EXP;

-The short-hand assignment operators are

                        += , -= , *= , /= , %=

Example:

a+=b   -------------  a=a+b

a-=b    -------------  a=a-b

a*= b  --------------  a=a*b

a/=b  ---------------  a=a/b

a%=b  -------------  a=a%b

 

vi) Conditional operators:

-It is also known as Ternary operator.

-The symbols used to construct a conditional expression are ? and :

-A conditional expression is of the form,

                        exp1?exp2:exp3;

Example:

(a>b)?System.out.println(“a is greater”): System.out.println (“b is greater”);

- It is equivalent to if-else statement in java

 

 

Example:

if(a>b)

    System.out.println(“a is greater”);

else

    System.out.println (“b is greater”);

vii) Bitwise operators:

-‘C’ provides bitwise operators that operate on data at the bit-level.

-Bitwise operators interpret operands as string of bits.

-These bit strings are then interpreted according to datatype.

-Bitwise operators are of 2 types.

            i) Logical bitwise operators.

            ii) Shift bitwise operators.     

i) Logical bitwise operators:

Operator

Meaning

&

Bitwise AND

|

Bitwise OR

^

Bitwise exclusive OR

~

One’s complement

Bitwise AND operator:

-The Bitwise AND (&) is a binary operator that requires two integral operands(character or integer).

-It does a bit-by-bit comparison between two operands.

-The result of the comparison is 1 only when both bits are 1, otherwise it is 0.

First operand bit

Second operand bit

Result(&)

0

0

0

0

1

0

1

0

0

1

1

1

Bitwise OR operator:

-The Bitwise inclusive OR (|) is a binary operator that requires two integral operands(character or integer).

-It does a bit-by-bit comparison between two operands.

-The result of the comparison is 0 only when both bits are 0, otherwise it is 1.

                       

First operand bit

Second operand bit

Result( | )

0

0

0

0

1

1

1

0

1

1

1

1

Bitwise exclusive OR:

-The Bitwise exclusive OR (^)is a binary operator that requires two integral operands(character or integer).

-It does a bit-by-bit comparison between two operands.

-The result of the comparison is 1 only if one of the operands is 1, otherwise it is 0.

First operand bit

Second operand bit

Result(^)

0

0

0

0

1

1

1

0

1

1

1

0

One’s complement:

-The one’s complement (~) is a unary operator applied to an integral value.

-The result is 1 when the original bit is 0 and it is 0 when the original bit is 1.

Original bit

Result( ~ )

0

1

1

0

ii) Shift Bitwise operators:

-The shift Bitwise operators move bits to the right or left.

Operator

Meaning

>> 

Bitwise shift right

<< 

Bitwise shift left

>>> 

Shift right with zero fill

 Bitwise shift-right operator:

-It moves some number of bits from right to left.

-It requires two integral operands.

Syntax:

                        Operand1 >> Operand2;

                                    -Here, Operand1 is value to be shifted.

                                                Operand2 is number of bits to be shifted.

Bitwise shift-left operator:

-It moves some number of bits from left to right.

-It requires two integral operands.

Syntax:

                        Operand1 << Operand2;

                                    -Here, Operand1 is value to be shifted.

                                                Operand2 is number of bits to be shifted.

 

viii) Special operators:

- Java supports some special operators such as,

            a) instanceof operator

            b) member selection operator

a) instanceof operator:

- The instanceof is an object reference operator and returns true if the object on the left-hand side is an instance of the class given on the right hand side.

- This operator allows us to determine whether the object belongs to a particular class or not.

Example:

            person  instanceof  student

- It is true if the object person belongs to the class student, otherwise it is false.

 

b) member selection operator:

- The dot (.) operator is used to access the instance variables and methods of class objects.

Example:

person.age              // Reference to the variable age

person.salary( )      // Reference to the method salary( )

- It is also used to access classes and sub packages from a package.

 

6. Arithmetic Expressions:

- An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the language.

- Java does not have an operator for exponentiation.

Evaluation of Expressions:

Syntax:

Variable = expression;

Rules for evaluation of expressions:

-First, parenthesized sub-expressions from left to right are evaluated.

-If parentheses are nested, the evaluation begins with the innermost sub-expression.

-Then the precedence rule is applied.

-Then the Associativity rule is applied.

-Arithmetic expressions are evaluated from left to right using the rules of precedence.

Precedence of Arithmetic expressions:

High priority    * / %

Low priority    +  -

Example:

Z=a-(b/(3+c)*2)-1 where a=9, b=12, c=3

  =9-(12/(3+3)*2)-1      (inner parenthesis)

  =9-(12/6*2)-1             (precedence for * / is left to right)

  =9-(2*2)-1                 (parenthesis)

  =9-4-1                        (Associativity rule for -)

  =5-1

 
  =4

7. type conversion and casting:

-conversion of one data type to another is called as type conversion.

-It is of two types.

            i) Implicit Type conversion

            ii)Explicit Type conversion

i) Implicit Type conversion:

-It is also called as internal type conversion or type coercion or Automatic type conversion.

-If the operands are of different types, the lower type is automatically converted into higher.

Example:

int a;

float b,sum;

sum=a+b

- Where ‘a’ is automatically converted into float type.

- Automatic type conversion chart in java is depicted as,

 

ii) Explicit Type conversion:

-It is also called as external type conversion or casting a value.

-The process of local conversion is known as “Explicit type conversion”.

Syntax: (datatype) expression;

-Where expression may be a constant, variable or expression.

Example:

(int)7.5 results 7

(int)a+b converts the result as int value.

Operator Precedence and Associativity:

- Java operators are listed in order of precedence (highest to lowest).

- Their Associativity indicates in what order operators of equal precedence in an expression are applied.

-The complete set of operators with priority is depicted as,


8. Control Statements: (Flow of control)

- A Control statement is a statement used to control the flow of execution in a Java Program.

SELECTION STATEMENTS:

-Also called as conditional or decision-making control statements. 

-There are two types in Selection control statements.

                        i) Two-way selection control statements

                        ii) Multi-way selection control statements

i) Two-way selection control statements:

-The different two-way selection statements are,

                        a) if-else statement

                        b) null else statement

                        c) Nested-if statement

 

a)  if-else statement:

Syntax:

if(condition)

   {

true-block statements;

   }

else

   {

false-block statements;

   }

next statement;

Example:

if(a>b)

   {

System.out.println(“a is greater”);

   }

else

   {

System.out.println(“b is greater”);

   }

b) null else statement:

-Also called as simple-if statement.

Syntax:

if(condition)

   {

statements;

   }

next statement;

 

Example:

if(a==2)

  {

p++;

   }

System.out.println(“program over”);

c) Nested-if statement:

-if within if is called as Nested-if.

Syntax:

if(condition-1)

  {

         if(condition-2)

   {

Statement-1;

   }

else

{

Statement-2;

           }

   }

else

   {

if(condition-3)

   {

Statement-3;

               }

else

   {

Statement-4;

   }

   }

next statement;

Example:

if(a>b)

   {

if(a>c)

   {

     System.out.println(“a is greater”);

             }

else

              {

     System.out.println (“c is greater”);

   }

   }

else

   {

if(b>c)

   {

      System.out.println(“b is greater”);

                }

else

   {

System.out.println(“c is greater”);

   }

   }

ii) Multi-way selection control statements:

-The different multi-way selection statements are,

a) switch statement

b) else-if ladder statement

a) switch statement;

Syntax:

switch(expression)

   {

case value-1:statement-1;break;

case value-2:statement-2;break;

………………………….

………………………….

case value-n:statement-n;break;

default: default statement;

   }

next statement;

Example:

switch(digit)

   {

case 0: System.out.println(“ZERO”);break;

case 1: System.out.println(“ONE”);break;

case 2: System.out.println(“TWO”);break;

case 3: System.out.println(“THREE”);break;

case 4: System.out.println(“FOUR”);break;

case 5: System.out.println(“FIVE”);break;

case 6: System.out.println(“SIX”);break;

case 7: System.out.println(“SEVEN”);break;

case 8: System.out.println(“EIGHT”);break;

case 9: System.out.println(“NINE”);break;

default: System.out.println(“Enter between 0-9”);

               }

b)else-if ladder statement:

Syntax:

if(condition-1)

   {

Statement-1;

   }

else if(condition-2)

   {

Statement-2;

   }

…………………

……………..…..

else if(condition n-1)

   {

Statement-(n-1);

   }

else

   {

Statement-n;

   }

next statement;

Example:

if(a>b&&a>c&&a>d)

   {

System.out.println(“a is greater”);

   }

else if(b>a&&b>c&&b>d)

   {

System.out.println(“b is greater”);

   }

else if(c>a&&c>b&&c>d)

   {

System.out.println(“c is greater”);

   }

else

   {

System.out.println(“d is greater”);

   }


LOOP statements:

-The iteration control statements are also called as Repetition or Iteration control statements.

-A looping process includes the following four steps.

            -Setting and initialization of a counter.

            -Execution of the statements in the loop body.

            -Test for a specified condition (loop control expression) for execution of a loop

            -Incrementing or Decrementing counter.

i) Pretest and Posttest loops:

-In a Pretest loop, the condition is checked before we execute a loop body.

-It is also called as entry-controlled loop.

-In the Posttest loop, we always execute the loop body atleast once.

-It is also called as exit-controlled loop.


a) while statement:

Syntax:

while(condition)

   {

loop body;

   }

next statement;

 

Example:

n=10, i=1,sum=0;

while(i<=n)

    {

sum=sum+i;

i++;

                }

 System.out.println(“sum=”+sum);

 

b) do-while statement:

Syntax:

do

   {

loop body;

   }while(condition);

next statement;

Example:

n=10,i=1,sum=0;

do

   {

sum=sum+i;

i++;

   } while(i<=n);

System.out.println(“sum=”+sum);

 

c) for statement:

Syntax:

for(initialization;condition;inc or dec)

   {

loop body;

   }

next statement;

Example:

n=10,i,sum=0;

for(i=1;i<=n;i++)

{

sum=sum+i;

}

System.out.println(“sum=”+sum);


Unconditional control statements:

-The unconditional control statements are,

                        a) break statement

                        b) continue statement

 

a) break statement:

-The break statement skips from the loop or block in which it is defined.

-The control then automatically goes to the first statement after the loop or block.

-The general format is

                        break;

Example:

            sum=0,i

for(i=1;i<=10;i++)

               {

     if(i==3)

break;

     sum+=i;

             }

            System.out.println(“Sum=”+sum);

 

b) continue statement:

-The continue statement is used for continuing next iteration of loop statements.

-When it occurs in the loop, it does not terminate but it skips the statements after it.

-It is useful when we want to continue the program without executing any part of the program.

-The general format is

                        continue;

Example:

sum=0,i

for(i=1;i<=10;i++)

               {

     if(i==3)

continue;

     sum+=i;

             }

            System.out.println(“Sum=”+sum);

 

9. Arrays:

Array - Definition:

- An array is a collection of variables of same datatype referenced by a common name.

OR

- An array is a collection of homogeneous elements

OR

- An array is a group of contiguous or related data items that share a common name and stores its values in sequential memory locations.

- Array index starts from 0 (zero).

- Arrays are dynamic in java

Array - Types:

- There are 3 types of arrays

i) 1-D arrays

ii) 2-D arrays

iii) M-D arrays

i) One-Dimensional Arrays:

- Also called as single subscripted variables.

Declaration of 1-D arrays:

   datatype  arrayname[ ]=new datatype[size];

Example:

   int  a[ ]=new int[5];

Initialization of 1-D arrays:

   datatype  arrayname[ ]={List of values};

Example:

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

 

ii) Two-Dimensional Arrays:

- Also called as Double subscripted variables.

Declaration of 2-D arrays:

   datatype  arrayname[ ][ ]=new datatype[rowsize][colsize];

Example:

   int  a[ ][ ]=new int[2][2];

Initialization of 2-D arrays:

   datatype  arrayname[ ][ ]={List of values};

Example:

   int  a[ ][ ]={{2,4},{6,8}};

 

iii) Multi Dimensional Arrays:

- Multidimensional arrays can be defined as array of arrays.

- An example is 3-D arrays.

Declaration of 3-D arrays:

   datatype  arrayname[ ][ ][ ]=new datatype[size1][size2][size3];

Example:

   int  a[ ][ ][ ]=new int[2][2][2];

Initialization of 3-D arrays:

   datatype  arrayname[ ][ ][ ]={List of values};

Example:

   int  a[ ][ ][ ]={{1,3},{5,7}

                        {2,4},{6,8}};

 

 

10. Math Class in JAVA:

- Java supports basic mathematical functions through Math class

- Math class is defined in the java.lang package

- Mathematical functions sqrt, sin, cos, log are frequently used in the analysis of real-life problems

Syntax:

     Math.function_name();

Example:

     Math.sqrt(x);


Methods in Math class:








































No comments:

Post a Comment