You are on page 1of 37

C Programming Basics:

====================
Keywords(32)
-----------
Keywords are the words which are associated with some functionalities.

EX: short,int,long,float,double,char,if,for,while,do,break,continue,switch,case,
default,return,void,.....

Integer: EX: 10,20,-345,939388=%d(int)


int totalinterest=10000;

Float: EX: 2.30,-23.00,0.01,21211.99=%f(float)


float account_bal=30000.50;

Characters: EX: 'a','2','.',' ','!'=%c(char)


char alphabet='d';

String: EX: "tree","a"," ",",","1999"=%s(char[])


char name[]="harish";

if and else:
=============
//C program to add 2 numbers
#include<stdio.h>//preprosessor directive-std input/output header file
void main()
{
int firstno=200;
int secondno=20;
if(firstno >20)
{
printf("good morning");
}
else
{
printf("good evening");
}

for Loop:
=========
//C program to add 2 numbers
#include<stdio.h>//preprosessor directive-std input/output header file
void main()
{
int x=10;
int y=20;
printf("x=%d,y=%d\n",x,y);//x=10,y=20
x=y;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
y=x;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
x=8;
x=y;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20
x++;//x+1
y--;//y-1
printf("x=%d,y=%d\n",x,y);//x=21 ,y=19
x=y++;
printf("x=%d,y=%d\n",x,y);//x=19 ,y=20
y=++x;
printf("x=%d,y=%d\n",x,y);//x=20 ,y=20

}
EX:
==
#include<stdio.h>
void main()
{
int x;
printf("before for loop");
for(x=1;x<=100;x++)
{
printf("%d\n",x);
}
printf("after for loop");

Nested for loop:


----------------
A for loop inside another for loop.
Ex:
for()
{
for()
{

}
}
Ex:
#include<stdio.h>
int main()
{
int i,j,sum=0;

for(i=1;i<4;i++)
{
for(j=1;j<4;j++)
{
sum=i+j;
printf("The sum of %d and %d is %d\n",i,j,sum);
}
printf("The control goes out of the inner for loop\n");
}
printf("The control goes out of the outer for loop\n");
}

while loop:
===========
#include<stdio.h>
void main()
{
int x=1;
printf("before while loop");
while(x<=100)
{
printf("%d\n",x);
x++;
}
printf("after while loop");

break: break keyword is used to get the control out of the recent loop.
======
#include<stdio.h>
int main()
{ int i=2;
int num;
printf("enter any no to find prime or not\n");
scanf("%d",&num);//5
while(i<=num-1)
{ if(num%i==0)
{
printf("Not a prime");
break;
}
i++;
}
if(i==num)
printf("Prime number");
}

Function:
=========
Function is a block consits of set of statements to perform particular tasks.

function signature:
-------------------
EX:1)int add(int x,int y);
EX:2)void sub();

return type:int and void


function name:add and sub
arguments (or) parameters:int x and int y

There are 2 types of functions:


--------------------------------
pedefined functions: printf(),scanf(),pow(),main(),sqrt(),......
and
user defined functions: add(),sub(),xyz(),abc()....

Example for user defined functions:


-----------------------------------
3 parts of user defined functions
1)function declaration (OR)prototype
2)function call
3)function defination

Ex:1)
#include<stdio.h>
void message();//func decl
void main()
{
printf("Beginning of main method\n");
message();//func call
printf("End of main method\n");
}
void message()//func def
{
printf("Hi welcome to HCL\n");
printf("Techbee scholars\n");
}

Ex:2)
#include<stdio.h>
void m1();//func decl
void m2();//func decl
void m3();//func decl
void main()
{
printf("Beginning of main method\n");
m1();//func call
printf("End of main method\n");
}
void m1()//func def
{
printf("beginning of m1\n");
m2();//func call
printf("end of m1\n");
}
void m2()//func def
{
printf("beginning of m2\n");
m3();//func call
printf("end of m2\n");
}
void m3()//func def
{
printf("beginning of m3\n");
printf("end of m3\n");
}

Return Types:(void,int,float,double,char...)
=============
void(Empty)
------------
#include<stdio.h>
void add(int x,int y);//FDecl
int main()
{
int a=10,b=20;
add(a,b); //a,b actual arguments//Fcall
}
void add(int m,int n)//m,n formal arguments//Fdef
{
int z;
z=m+n;//30
printf("The addition is %d",z);// 30

}
int(10,-3455)
-------------
#include<stdio.h>
int add(int x,int y);//fun dcl
void main()
{
int a=10,b=20,c;
c=add(a,b); //a,b actual arguments//Fcall
printf("The addition is %d",c);//30
}
int add(int m,int n)//m,n formal arguments//Fdef
{
int z;
z=m+n;
return z;

Arrays:
-------
Array is a set of similar datatypes.

1-Dimensional array:
-------------------
int x[];//error

int x[3];//ok
x[0]=10;
x[1]=20.50;//error
x[1]="hi";//error
x[1]='f';//error
x[1]=77;
x[2]=30;
x[3]=40;//error

int x[3]={10,20,30};//ok
int x[]={10,20,30,40};//ok

2-D array(Matrix):
-------------------
int x[row][column];

int x[3][2];

x[0][0]=10;
x[0][1]=20;
x[1][0]=30;
x[1][1]=40;
x[2][0]=50;
x[2][1]=60;

int x[3][2]={{10,20},{30,40},{50,60}};

char name[10]={'h','a','r','i','s','h'};

switch: used to choose among multiple options.


======
Ex 1:
#include<stdio.h>
int main()
{
int num;
printf("enter the no between 5 to 8\n");
scanf("%d",&num);
switch(num)
{
case 7: printf(" you entered 7");
break;
case 8: printf(" you entered 8");
break;
case 5: printf(" you entered 5");
break;
case 6: printf(" you entered 6");
break;
default:printf("you entered other than 5,6,7,8");
}
}
Ex 2:
#include<stdio.h>
int main()
{
char c;
printf("enter the characters among(A,B,C,D)\n");
scanf("%c",&c);
switch(c)
{
case 'A':
case 'a': printf(" you entered aaa");
break;
case 'B':
case 'b': printf(" you entered bbb");
break;
case 'C':
case 'c': printf(" you entered ccc");
break;
case 'D':
case 'd': printf(" you entered ddd");
break;
default:printf("you entered other than a,b,c,d");
}
}

Pyramid Example:
=================

(39)*\n
(38)* * *\n
(37)* * * * *\n
(36)* * * * * * *\n
(35)* * * * * * * * *\n

Ex:
#include<stdio.h>
int main(){
printf("Enter number of rows");
int rows;
int i,j,k,center=40;
scanf("%d",&rows);//5
for(i=1;i<=rows;i++)//traversing rows
{
for(j=1;j<=center-i;j++)//printing spaces
{
printf(" ");
}
for(k=1;k<=2*i-1;k++)//printing *stars
{
printf("*");
}
printf("\n");
}

JAVA:
=====
Keywords:(Reserved words)
========
Note:Keywords should be in lowercase.

Reserved words=53 words

1)Reserved Keywords(50)-they are associated with some functionalities


a)Used(48)-if,else,for,,,,,
b)Unused(2)- goto, const

2)Reserved Literls(3)-they represents values


true and false are the values For boolean datatypes
null- default value For Object type.

Used Keywords(48):
-------------------
Keywords For datatype(8):
------------------------
byte,short,int,long,float,double,char,boolean

keywords For flow control:


---------------------------
if,else,do,while,for,break,continue,return,switch,case,default

keywords For exception handling:


---------------------------------
try,catch,finally,throw,throws,assert

Class level keywords:


---------------------
class,extends,interface,implements,import,package

Object level keywords:


----------------------
new,this,super,instanceof

Keywords For access modifiers:


-------------------------------
public,protected,private,abstract,synchronized,static,strictfp,transient,
final,volatile,native,<default>
enum keyword:
-------------
enum keyword is used to represent a group of constants.

Ex:
---
enum Weekdays
{
sunday,monday,.......,saturday;
}

Weekdays w1= sunday;//ok


Weekdays w2= monday;//ok
Weekdays w3= someotherday;//error

void keywords:
--------------
ex:
m1()//error
{
}

void m1()//ok
{
}
Unused keywords(2):
------------------
goto: It increases the complexity of the program,i.e its harder to debug
the programs.

const: final keywords replaces const keyword in java.

Datatypes:(8)
==========
1)Numerical-byte,short,int,long,float,double
2)Non-numerical-char,boolean

Note:
-----
1 Terra byte=1024 Gigabytes
1 giga byte=1024 Megabytes
1 mega byte=1024 kilo byte
1 kilo byte=1024 bytes
1 Byte=8 bits
1 bit=0 (OR) 1

00000001=1
00000010=2
00000100=4
00001000=8
00010000=16
00100000=32
01000000=64
10000000=128

97=64+32+1=01100001===97
111=64+32+8+4+2+1=01101111===111
1 Byte:(max)=11111111=255
(min)=00000000=0
0.........255

byte:
-----
size=1 Byte
range=-128 to 127

byte b=10;//ok
byte b=-128;//ok
byte b=-130;//error
byte b=128;//error

short:
-------
size=2 Bytes
range= -32768....0.....32767

short s=32000;//ok
short s=33000;//error

int:
-----
size=4 Bytes
range= -210cr....0.....210cr

long:
-----
size=8 Bytes

float:
-------
size=4 Bytes
range= -210.00cr....0.....210.00cr

double:
-------
size=8 Bytes

char:
------
size=2 Bytes

Range:0....255(ascii)........65535

ASCII:(American std code For information interchage)


characters : '/0'...' '...'#'...'0','1'....'A','B'....'a','b'.....

ASCII values: 0....32....35.....48,49.....65,66.......97,98......255

ex:char ch='a';//97==01100001

boolean:
--------
No size.
it jsut represents either true or false.

ex: boolean b=true;


boolean b=false;

[5/26 12:42 PM] Nakul (Guest)


JAVA:

=====

Keywords:(Reserved words)

========

Note:Keywords should be in lowercase. Reserved words=53 words 1)Reserved


Keywords(50)-they are associated with some functionalities

a)Used(48)-if,else,for,,,,,

b)Unused(2)- goto, const 2)Reserved Literls(3)-they represents values

true and false are the values For boolean datatypes

null- default value For Object type. Used Keywords(48):

-------------------

Keywords For datatype(8):

------------------------

byte,short,int,long,float,double,char,boolean keywords For flow control:

---------------------------

if,else,do,while,for,break,continue,return,switch,case,default keywords For
exception handling:

---------------------------------

try,catch,finally,throw,throws,assert Class level keywords:

---------------------

class,extends,interface,implements,import,package Object level keywords:

----------------------

new,this,super,instanceof Keywords For access modifiers:

-------------------------------

public,protected,private,abstract,synchronized,static,strictfp,transient,

final,volatile,native,<default> enum keyword:

-------------

enum keyword is used to represent a group of constants. Ex:

---
enum Weekdays

    sunday,monday,.......,saturday;

} Weekdays w1= sunday;//ok

Weekdays w2= monday;//ok

Weekdays w3= someotherday;//error void keywords:

--------------

ex:

m1()//error

} void m1()//ok

Unused keywords(2):

------------------

goto: It increases the complexity of the program,i.e its harder to debug

the programs. const: final keywords replaces const keyword in java. Datatypes:(8)

==========

1)Numerical-byte,short,int,long,float,double

2)Non-numerical-char,boolean Note:

-----

1 Terra byte=1024 Gigabytes

1 giga byte=1024 Megabytes

1 mega byte=1024 kilo byte

1 kilo byte=1024 bytes

1 Byte=8 bits

1 bit=0 (OR) 1 00000001=1

00000010=2

00000100=4

00001000=8
00010000=16

00100000=32

01000000=64

10000000=128 97=64+32+1=01100001===97

111=64+32+8+4+2+1=01101111===111 1 Byte:(max)=11111111=255

        (min)=00000000=0

        0.........255 byte:

-----

size=1 Byte

range=-128 to 127 byte b=10;//ok

byte b=-128;//ok

byte b=-130;//error

byte b=128;//error short:

-------

size=2 Bytes

range= -32768....0.....32767 short s=32000;//ok

short s=33000;//error int:

-----

size=4 Bytes

range= -210cr....0.....210cr long:

-----

size=8 Bytes float:

-------

size=4 Bytes

range= -210.00cr....0.....210.00cr double:

-------

size=8 Bytes char:

------

size=2 Bytes Range:0....255(ascii)........65535 ASCII:(American std code For


information interchage)
characters  : '/0'...' '...'#'...'0','1'....'A','B'....'a','b'..... ASCII values:  
0....32....35.....48,49.....65,66.......97,98......255 ex:char
ch='a';//97==01100001 boolean:

--------

No size.

it jsut represents either true or false. ex: boolean b=true;

    boolean b=false; TypeCasting:

============

1)Implicit Typecasting

------------------------

Its also known as Upcasting or Widening.

Its supported by compiler and programers need not worry about it. Ex:

-128...0....10....127

int a=10;//ok

int a=(int)10;//compiler code short s=126;//ok

short s=(short)126;//cc -32000...0....32000

double d=1000;//ok

double d=(double)1000;//cc

Sopln(d);//1000.00 int x='a';//ok

int x=(int)'a';//cc

Sopln(x);//97 2)Explicit Type casting

------------------------

Its also known as Downcasting or Narrowing.Its not supported by compiler,i.e

programers have to specify it explicitly. byte b=125;//ok

byte b=130;//error

byte b=(byte)130;//ok ET

Sopln(b);//-126 -128,-127,-126,-125......-2,-1,0,1,2,3......127,-128,-127,-
126(130)....0....127,-128..... byte b=10.50;//error

byte b=(byte)11.990;//ok ET

Sopln(b);//11 Literals:

---------
EX:int x=10;

-----------

int=primitive datatype

x=identifier/variable

10=constant(or)literal Integral literals:

-----------------

int x;

Sopln(x);//0

int x=10;//ok

short s=20;//ok

float f=350;//ok

long l=100L;//ok

long l=34444l;//ok

int i=10L;//error

double d=2344.98; floating point literals:

------------------------

Every floating point literals in java is of double type by default. float f;

Sopln(f);//0.0

float f=10.50;//error

float f=10.50F;//ok

float f=33.00f;//ok

double d=22.33F;//ok

double d=10.49;//ok Character literals:

-------------------

char c;

Sopln(c);//blank

char c='a';//ok

char c=a;//error

char c="a";//error
char c=97;//ok

char c=(char)97;//cc

Sopln(c);//a

char c='ab';//error

char c='\n';//ok Boolean literals:

----------------

The default value For boolean is false.

Ex:

boolean b;

Sopln(b);//false boolean b=true;//ok

boolean b=false;//ok

boolean b=True;//error

boolean b=0;//error

boolean b="true";//error String literals:

================

Default value For String(Object) is null.

String s;

Sopln(s);//null String s=100;//error

String s=tree;//error

String s="tree";//ok

String s='a';//error

String s="a";//ok

String s="100";//ok Important Notes:

================

Object class:

=============

Object class is the topmost class in java.

Every class in java is the child class of Object class either directly 

or indirectly(User defined and pre defined classes). 

JDK,JRE and JVM:


=================

JDK(Java development kit):JDK is used to develop and run java


applications. JRE(Java runtime environment):JRE is used to run java
application.  JVM(Java virtual machine):JVM provides the environment to
interpret(read)

the bytecodes line by line and provides the output in human understandable

form. Classses and Objects:

----------------------

Class is a user defined datatype.

Object is an instance(variable) of a class. For:

----

class Account

}; int x;//x is a variable of interger datatype

x=10; Account a;//a is an instance(variable) of Account class

a=new Account(); Account a=new Account();//a is an object of Account


type                                                                                
       

Java.lang package:
------------------
This is the default package which will get imported by the compiler
internally For every java program.

Arrays:
=======
Array is a set of similar datatypes.

1D Array:
---------
Ex:
int x[10];//error
int x[];
x=new int[4];
or
int x[]=new int[4];
x[0]=10;
x[1]=10.40;//error
x[1]=20;
x[2]=30;
x[3]=33;
x[4]=44;//error

int x[]={10,20,30,40};
String s[]={"tree","hi",.....};

char c[]=new Char[2];


c[0]='a';
c[1]='3';

1D array can be declared in 3 ways:

int x[];
int []x;
int[] x;

2D Array(Arrays of Array)
---------------------------
EX:1)
int x[][]=new int[2][2];

x[0][0]=10;
x[0][1]=20;

x[1][0]=30;
x[1][1]=40;

Ex:2)
int[] x[]=new int [2][];
x[0]=new int[3];
x[0][0]=10;
x[0][1]=20;
x[0][2]=30;

x[1]=new int[1];
x[1][0]=40;

2D Arrays can be decl. in 6 ways:

int x[][];
int [][]x;
int []x[];
int[][] x;
int[] []x;
int[] x[];

String Class:
------------
String s=new String("hello");
or
String s="hello";

length variable v/s length() method:


====================================
length is a variable used to identify the length of an array.

Ex:
int x[]={11,22,33,44,55};

int i;
for (i=0;i<x.length;i++)
{
System.out.println(x[i]);//11,22,33,44,55
}

length() method is used to find the length of a String.

String s="hello";
System.out.printl(s.length());//5

For-each Loop:
==============
Ex:1)
String s[]={"hello","tree","hiii"};
int i;
for (i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
Ex:2)
String s[]={"hello","tree","hiii"};
for(String x : s)
{
System.out.println(x);
}
Note: "For each String variable x in the array s"

Ex:3)
int s[]={22,33,44444444};
for(int pavan : s)
{
System.out.println(pavan);
}

Arrays:
=======
Array is a set of similar datatypes.

1D Array:
---------
Ex:
int x[10];//error
int x[];
x=new int[4];
or
int x[]=new int[4];
x[0]=10;
x[1]=10.40;//error
x[1]=20;
x[2]=30;
x[3]=33;
x[4]=44;//error

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

String s[]={"tree","hi",.....};

char c[]=new Char[2];


c[0]='a';
c[1]='3';

1D array can be declared in 3 ways:


int x[];
int []x;
int[] x;

2D Array(Arrays of Array)
---------------------------
EX:1)
int x[][]=new int[2][2];

x[0][0]=10;
x[0][1]=20;

x[1][0]=30;
x[1][1]=40;

Ex:2)
int[] x[]=new int [2][];
x[0]=new int[3];
x[0][0]=10;
x[0][1]=20;
x[0][2]=30;

x[1]=new int[1];
x[1][0]=40;

2D Arrays can be decl. in 6 ways:

int x[][];
int [][]x;
int []x[];
int[][] x;
int[] []x;
int[] x[];

String Class:
------------
String s=new String("hello");
or
String s="hello";

length variable v/s length() method:


====================================
length is a variable used to identify the length of an array.

Ex:
int x[]={11,22,33,44,55};

int i;
for (i=0;i<x.length;i++)
{
System.out.println(x[i]);//11,22,33,44,55
}

length() method is used to find the length of a String.

String s="hello";
System.out.printl(s.length());//5
For-each Loop:
==============
Ex:1)
String s[]={"hello","tree","hiii"};
int i;
for (i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
Ex:2)
String s[]={"hello","tree","hiii"};
for(String x : s)
{
System.out.println(x);
}
Note: "For each String variable x in the array s"

Ex:3)
int s[]={22,33,44444444};
for(int pavan : s)
{
System.out.println(pavan);
}

Types Of Variables:
===================
Based on the value represented by the variables they are divided into 2 types:
1)primitive variables:
----------------------
int x=10;
float y=33.33;
here x and y are primitive variables.

2)Reference variables:
----------------------
String s1=new String();
here s1 is reference variable pointing to an Object of String Type.

Based on the behaviour and declaration the variables are divided into 3 types:
1)instance variables
2)static variables
3)local variables

1)instance variables:
----------------------
*They are declared outside the method,blocks and constructors.
*They are stored in heap area of the memory.
*They are varied from object to object.i.e if any objects makes any changes to an
instance
variable that will not get reflected to the other objects.
*JVM assigns default value for instance variables.
*Instance variables and methods cannot be accessible directly from static
area but can be accesible directly from instance area.But by using the objects
we can access instace variables and methods from static area.
*The access modifiers which are applicable for instance variables are
public,private,
protected,<default> and final.

EX:1)
class Test
{
int x=10;
void m1()
{
System.out.println("instance method");
}
public static void main(String args[])
{
System.out.println(x);//error
m1();//error
Test t1=new Test();
System.out.println(t1.x);//10
t1.m1();//instance method
t1.m2();//10...instance method
}
void m2()
{
System.out.println(x);//10
m1();//instance method
}
}
EX:2)
class Test
{
int x=10;

public static void main(String args[])


{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(t1.x);//10
System.out.println(t2.x);//10
System.out.println(t3.x);//10

t2.x=20;

System.out.println(t1.x);//10
System.out.println(t2.x);//20
System.out.println(t3.x);//10
}
}
Ex:3)
class Test
{
int x;
float y;
String z;

public static void main(String args[])


{
Test t1=new Test();
System.out.println(t1.x);//0
System.out.println(t1.y);//0.0
System.out.println(t1.z);//null

}
}
2)Static variables:
--------------------
*They are declared outside the method,blocks and constructors.
*They are stored in method area of the memory.
*JVM assigns default value for static variables.
*They are not varied from object to object,i.e when we declare any static variable
a single class level copy will get created which will be reference from every
object
of that class.So by using any object if we make any changes to that static
variables
that will get reflected to other objects also.
*static variables and methods can be accessible directly from both instance as well
as
static areas.
*The access modifiers which are applicable for static variables are public,private,
protected,<default> and final.

Ex:1)
class Test
{
static int x=10;
static void m1()
{
System.out.println("static method");
}
public static void main(String args[])
{
System.out.println(x);//10
m1();//static method
System.out.println(Test.x);//10
Test.m1();//static method
Test t1=new Test();
System.out.println(t1.x);//10
t1.m1();//static method
}
void m2()
{
System.out.println(x);//10
m1();//static method
}
}
Ex:2)
class Test
{
static int x;
static float y;
static String z;

public static void main(String args[])


{
Test t1=new Test();
System.out.println(t1.x);//0
System.out.println(t1.y);//0.0
System.out.println(t1.z);//null

}
}
Ex:3)
class Test
{
static int x=10;

public static void main(String args[])


{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(t1.x);//10
System.out.println(t2.x);//10
System.out.println(t3.x);//10

t2.x=20;

System.out.println(t1.x);//20
System.out.println(t2.x);//20
System.out.println(t3.x);//20
}
}

Local variables:
----------------
*They are declared inside the methods,blocks and constructors.
*They are stored in stack area of the memory.
*JVM doesnot assigns any default values for local variables.
*Ther are not accessible outside the method,block and constructors where they are
declared.
*The only modifier which is applicable for local variables is final.

EX:1)
class Test
{

public static void main(String args[])


{
int x=10;//local variable
System.out.println(x);//10

}
}

Ex:2)
class Test
{

public static void main(String args[])


{
int x;
System.out.println(x);//error

}
}
Ex:3)
class Test
{
static void m1()
{
int y=10;
}
public static void main(String args[])
{

System.out.println(y);//error

}
}
Ex:4)
class Test
{
public static void main(String args[])
{
public int x=10;//error
private int y=20;//error
final int z=30;//ok

}
}

Main method:
===========
public static void main(String[] arguments)
{
}

public: Its public because the JVM should be able to call this method from
anywhere.
------
static: Its static because the JVM should call this method before the creation of
objects.
-------
void : Its doesnot return anything.
-----
main: method name
----
String: predefined class
-------

Command line arguments: These are used to change the behaviour of main method.
=======================
Ex:1)
class Test
{
public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);

}
}
Output:
-------
input: java first second third
output: first second third
Ex:2)
class Test
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
System.out.println("The square of "+x+" is "+(x*x));

}
}
//int x=Integer.parseInt("10");//10
//double d=Double.parseDouble("10.50");//10.50

String Concatination( + operator):


----------------------------------
class Test
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=30;
String name="Harish";
String name2="Naveen";
System.out.println(a+b+c);//60
System.out.println(a+b+c+name);//60harish
System.out.println(a+b+name+c);//30harish30
System.out.println(a+name+b+c);//10harish2030
System.out.println(name+a+b+c);//harish102030
System.out.println(name+name2);//harishnaveen

}
}

var-arg methods:(Variable arguments meythods):


==============================================
Ex:
void add(int...x)
{

}
without var-arg method:
---------------------
class Test
{
static void add(int x,int y)
{
System.out.println(x+y);
}
static void add(int x,int y,int z)
{
System.out.println(x+y+z);
}
static void add(int w,int x,int y,int z )
{
System.out.println(w+x+y+z);
}
public static void main(String args[])
{
add(10,20);
Test.add(10,20,30);
add(10,20,30,40);

}
}
with var-arg method:
--------------------
class Test
{
static void add(int...x)//int x[]
{
int sum=0;
for(int value:x)
{
sum=sum+value;
}
System.out.println(sum);
}
public static void main(String args[])
{
add(10,222);//x[0]=10,x[1]=222
Test.add(10,20,333);//x[0]=10,x[1]=20,x[2]=333
add(11111,20,30,40);//x[0]=11111,x[1]=20,x[2]=30,x[3]=40

}
}

Java Coding Standards:(Industry Standards)


==========================================
variables:
----------
int sun=10;//okkkkkkkkkkkk
int Sun=10;
int SUN=10;

int sunmoonmars=20;
int SunMoonMars=20;
int SUNMOONMARS=20;
int sunMoonMars=20;//okkkkkkkkkkkkk
int Sunmoonmars=20;

methods:
----------
void sun(){}//okkkkkkkkkkkk
void Sun(){}
void SUN(){}

void sunmoonmars(){}
void SunMoonMars(){}
void SUNMOONMARS(){}
void sunMoonMars(){}//okkkkkkkkkkkkkk
void Sunmoonmars(){}

class:
------
class sun
class Sun//okkkkkkkkkk
class SUN

class sunmoonmars
{
};
class SunMoonMars//okkkkkkkkkk
{
};
class SUNMOONMARS
{
};
class sunMoonMars
{
};
class Sunmoonmars
{
};

Scanner Class and BufferedReader Class:


=======================================
Output:
-------
Enter Your name:Harish

Enter any two numbers for addtion:10 20

Welcome Harish
The addtion od 10 and 20 is 30

Scanner:
---------
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
String name;
int a,b,sum;
System.out.print("Enter your name :");
//name=scan.next();//scans a single word
name=scan.nextLine();//scans a whole line

System.out.print("Enter any 2 nos for addition :");


a=scan.nextInt();
b=scan.nextInt();
sum=a+b;

System.out.println("Welcome "+name);
System.out.println("The addition of "+a+" and "+b+" is "+sum);

}
}
BufferedReader:
---------------
import java.util.Scanner;
import java.io.*;
class Test
{
public static void main(String args[])throws Exception
{
//InputStreamReader isr=new InputStreamReader(System.in);
//BufferedReader br=new BufferedReader(isr);
//[OR]
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name;
int a,b,sum;
System.out.print("Enter your name :");
name=br.readLine();//reads the whole line

System.out.print("Enter any 2 nos for addition :");


a=Integer.parseInt(br.readLine());//"10"==>10
b=Integer.parseInt(br.readLine());
sum=a+b;

System.out.println("Welcome "+name);
System.out.println("The addition of "+a+" and "+b+" is "+sum);

}
}

OOP Concepts(Object Oriented programming):


==========================================
Data Hiding:
============
Hiding the data from an outside world.
"private" access modifier is used to achieve Data Hiding.

Ex:1)
class Test
{
private int x=10;

public static void main(String args[])


{
Test t=new Test();
System.out.println(t.x);//10

}
}
Ex:2)
class Hello
{
private int x=10;
};
class Test
{
public static void main(String args[])
{
Hello h=new Hello();
System.out.println(h.x);//error

}
}
Abstraction:
============
Showing only the outer functionalities to the users meanwhile hiding the internal
complex details.
Ex:ATM machine.

Encapsulation:
==============
Binding variables and methods into a single unit called class is known as
Encapsulation.
Ex:
class Test
{ //members
int x=10;//variable OR member variables
void m1()//method OR member functions
{
Sopln("Good Morning");
}
};

Inheritance:(IS-A Relationship)
===============================
Inheritence is nothing but inheriting one's class properties in another class.
The main objective of inheritence is code reusabilty.
Inheritence can be achieved by using extends keyword in java.

EX:
class A
{
m1()
{
Sopln("good morning");
}
m2()
{
Sopln("good evening");
}
};
class B extends A//inheriting A's class properties in B class
{//3 methods
m3()
{
Sopln("good night");
}
};

EX:1)
class A
{ void m1()
{ System.out.println("Good Morning"); }
void m2()
{ System.out.println("Good Afternoon"); }
};
class B extends A
{ void m3()
{ System.out.println("Good Evening"); }
};
class Test
{
A a1=new A();
a1.m1();//GM
a1.m2();//GA
a1.m3();//error

B b1=new B();
b1.m1();//GM
b1.m2();//GA
b1.m3();//GE

A a2=new B();//parent reference can be used to hold child class object


a2.m1();//GM
a2.m2();//GA
a2.m3();//error

B b2=new A();//error
};
Note:
-----
Parent reference variable can be used to hold child class object, but in case of
inheritance
by using that parent reference we cant call child specific methods because the
method resolution
(method execution) is always taken care by compiler based on reference type.

HAS-A Relationship:
===================

public class Main{


public static void main(String args[])
{ int count=0;
System.out.println("Arguments :");
for(String argument:args)
{
System.out.println(argument);
count=++count;
}
System.out.println("The number of arguments is "+count);
}
}
import java.io.*;
import java.util.*;
public class Main{
public static void main (String[] args) throws Exception{
int i;

Scanner scan=new Scanner(System.in);


System.out.println("Enter n :");
int n=scan.nextInt();
int integers[]=new int[n];
String strings[]=new String[n];
System.out.println("Enter numbers :");
for(i=0;i<n;i++)
{
integers[i]=scan.nextInt();
}
System.out.println("Enter strings :");
for(i=0;i<n;i++)
{
strings[i]=scan.next();
}
System.out.println("Displaying numbers");
for(int x:integers)
{
System.out.println(x);
}
System.out.println("Displaying strings");
for(String x:strings)
{
System.out.println(x);
}

}
}

HAS-A Relationship:
===================
The main objective of Has-A relationship is code reusabilty.
There is no specific keyword to implement Has-A relationship but usually we do it
through
using "new" keyword.
Has-A relationship is also known as Composition & Aggregation.
-------------------------

Composition:
------------
Without existing container object there is no chance of existing contained object
then both
of them are said to be strongly associated.This phenomenon is known as Composition.

Ex:Inner class
--------------
class University
{
class Deparments
{
};
};

Aggregation:
-----------
Without existing container object there is a chance of existing contained object
then both
of them are said to be weakly associated.This phenomenon is known as Aggregation.

Ex:Car HAS-A Engine


-------------------
class Engine
{
void m1()
{
Sopln("US engine");
}
void m2()
{
Sopln("Uk engine");
}
.......
.......
void m100()
{
Sopln("Australia engine");
}
};
class Car
{
Engine e1=new Engine();
e1.m2();//UK engine
};

Polymorphism:
=============
Polymorphism is a phenomenon in which the same entity can exist in two or more
forms.
The main objective of Has-A relationship is code reusabilty.

Ex: method Overloading and method Overriding.


----------------------------------------------

Method Signature in Java:


------------------------
In C language:
-------------
void add(int x,int y);
----------------------
void-return type
add-function name
int x,int y-arguments lists
These 3 are part of method signatures

In Java:
--------
void add(int x,int y);
----------------------
void-return type
add-function name
int x,int y-arguments lists
In case of Java return type is not part of method signature

Ex: add(int x,int y);


----------------

Method Overloading:
-------------------
In java,if any 2 methods are said to be overloaded if and only if both methods
having the same
name and different argument lists atleast in their order.

Ex:
1)
void m1(int x);
void m1(float x);
//ok
2)
void m1(int x,float y);
void m1(float x,int y);
void m1();
//ok
3)
void m1()
void m1(int x)
//ok
4)
void m1(int x,float y);
void m1(int y,float x);
//error
Ex:
---
class A
{
static void m1(int x)
{
System.out.println("Int argument "+x);
}
static void m1(float y)
{
System.out.println("Float argument "+y);
}
};
public class Test{
public static void main (String[] args)
{
A.m1(10);//int-argument 10
A.m1('L');//int-arg 76
A.m1(10.50f);//float-arg 10.50
//A.m1(10.30);//error
A.m1(22L);//float-arg 22.00
//A.m1("100");//error
//A.m1();//error

}
}

Method Overriding:
------------------
In Java,if any 2 methods are said to be overrided if anf only if both overriding
and overidden
methods are having the same method signatures with different implementations.
Method Overriding is a phenomenon in which parent class method will be
reimplemented in the
child class.

Ex:
class Parent
{
void property()
{
Sopln("Gold+Cash+Land");
}
void car()//overriden method
{
Sopln("Maruthi-800");
}
};
class Child extends Parent
{
void car()//overriding method
{
Sopln("Benz");
}
};
EX:
class Parent
{ void m1(){System.out.println("Good Morning");}
void m2(){System.out.println("Good Afternoon");}
};
class Child extends Parent
{ void m2(){System.out.println("Good Evening");}
void m3(){System.out.println("Good Night");}
};
class Test
{ public static void main(String [] hhh)
{
Parent p1=new Parent();
p1.m1();//GM
p1.m2();//GA
//p1.m3();//Error
Child c1=new Child();
c1.m1();//GM
c1.m2();//GE
c1.m3();//GN
Parent p2=new Child();
p2.m1();//GM
p2.m2();//GE
//p2.m3();//error
//Child c2=new parent();//error
}
};
Note:
-----
Parent reference variable can be used to hold child class object, but in case of
overriding
by using that parent reference if we call overriden method then child specific
method will be
called because the method resolution (method execution) is always taken care by JVM

based on runtime object.

Static Blocks:
--------------
These are the blocks which will get executed only once at the time of class
loading,i.e
before the execution of main method.
Static blocks are used for initialization purposes.
Ex:
static
{
Sopln("this is a static block");
}
Ex:
class Test
{
static
{
System.out.println("Static block 1");
}
public static void main(String [] hhh)
{
System.out.println("Inside the main method");
}
static
{
System.out.println("Static block 2");
}
};
Instance Blocks:
----------------
Instance blocks will get executed for each and every object creation before the
execution of
constructors.
Instance blocks are used for initialization purposes.
Ex:
{
Sopln("This is an instance block");
}
Ex:

class Test
{
Test()
{
System.out.println("This is a constructor");
}
public static void main(String [] hhh)
{
System.out.println("Inside the main method");
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();

}
{
System.out.println("Instance block 1");
}
{
System.out.println("Instance block 2");
}
};
Constructors:
-------------
Constructors are used to initialize the objects which are just created.
Constructors will be having the same name as class name and it doesnot have any
return type
not even void.
Suppose if we are not specifying any constructors in our program then compiler
itself by
default creates one No argument constructor with empty implementation and calls
that
no argument constructor internally whenever we create the objects,i.e constructors
will get executed for each and every object creation.

Ex:
class Test
{
Test()
{
Sopln("This is a constuctor");
}
};

Ex:

class Test
{
Test()
{
System.out.println("This is a constructor");
}
public static void main(String [] hhh)
{

Test t1=new Test();


Test t2=new Test();
Test t3=new Test();

};

Ex:
//with out using constructors
class Student
{
int rollno;
String name;

public static void main(String [] hhh)


{
Student s1=new Student();
s1.rollno=100;
s1.name="raju";
Student s2=new Student();
s2.rollno=101;
s2.name="suman";
////////
////////
Student s100=new Student();
s100.rollno=200;
s100.name="harish";
System.out.println(s1.rollno+"..."+s1.name);
System.out.println(s2.rollno+"..."+s2.name);
System.out.println(s100.rollno+"..."+s100.name);

};

Ex:
//Using constructors
class Student
{
int rollno;
String name;
Student(int rn,String nm)
{
this.rollno=rn;
this.name=nm;
}
public static void main(String [] hhh)
{
//Student s=new Student();//error
Student s1=new Student(100,"Raju");
Student s2=new Student(101,"Suman");
////////
////////
Student s100=new Student(200,"harish");
System.out.println(s1.rollno+"..."+s1.name);
System.out.println(s2.rollno+"..."+s2.name);
System.out.println(s100.rollno+"..."+s100.name);

};

Inner Classes: A class inside a class.


--------------
Ex:
class Outer
{
class Inner
{
void m1()
{
System.out.println("Inner class method");
}
};
};
class Test
{ public static void main(String [] hhh)
{
Outer o = new Outer();
Outer.Inner i=o.new Inner();
i.m1();//ICM
//[or]
Outer.Inner i1=new Outer().new Inner();
i1.m1();//ICM
//[or]
new Outer().new Inner().m1();//ICM
}
};

You might also like