0% found this document useful (0 votes)
92 views

Java Fast Track

The document discusses various features of the Java programming language. It describes how Java is platform independent unlike C and C++. It also discusses the differences between .exe and .class files, why Java is suitable for internet programming, object-oriented concepts like classes and objects, why pointers are eliminated in Java, the difference between functions and methods, how memory is allocated by the JVM, garbage collection in Java, and just-in-time compilation. The document also covers Java programming basics like comments, naming conventions, data types, and operators.

Uploaded by

SNEHA SNDHU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Java Fast Track

The document discusses various features of the Java programming language. It describes how Java is platform independent unlike C and C++. It also discusses the differences between .exe and .class files, why Java is suitable for internet programming, object-oriented concepts like classes and objects, why pointers are eliminated in Java, the difference between functions and methods, how memory is allocated by the JVM, garbage collection in Java, and just-in-time compilation. The document also covers Java programming basics like comments, naming conventions, data types, and operators.

Uploaded by

SNEHA SNDHU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Features Of Java:

C,C ++ are called platform dependent languages.Java is called platform Independent.

-difference between an executable file and a class file?

.exe file contains machine language instructions. .class file contains byte code instructions.

-Why java is suitable for internet?

It is system independent run any type of system on internet.and it is eliminates a lot of security problems for
data on internet

Object: object are key to understanding object-oriented technology every object have state and behavior.for
ex Dog is a object Dog have state(name,color) and behavior(barking,wagging tail)

Class:a class is a blueprint Or template for creating different objects.

-Why pointers are eliminated from java?


Pointer lead to confusion for a programmer.

Pointer may crash program easily.a

Pointer break security.

-What is different between a function and a method?

A method is a function that is written in a class.we do not have functions in java.instead we have methods.This
means whenever a functions is written in java.it should be written inside the class only

But inc++ we can write the functions inside as well as outside.so in c++ they are called member functions and
not methods.

-Which part of Jvm will allocate the memory for a java program?

Class loader subsystem of JVM will allocate the necessary memory needed by the java program.

-Which algorithum is used by garbage collector to remove the unused variables or objects from memory?

Mark and sweep algo.

-How can you call the garbage collector?

Garbage collector is automatically invoked whie the program is being run.It can be also called as gc()method.

-What is JIT compiler?

Is part of jvm which increases the speed of execution of a java program.

3.First Step Towards Java Programming

Comments : comments are the description about the features of a program.3 types of comments in java
1)single line comments

2)multi line comments

3)java documentation comments

Single line comments :These comments are for marking a single line as a comment .These comments start
with double slash symbol(//).

Ex://this is my comment of one line

Multi line comments: these comments are used for represent several lines as comments.these comments start
with /* and end with*/

Ex:/*this is multi line comment.this is line one

This is line two of the comment.

This is line three of the comment*/

Java documentation comments:these comments start with /** and end with */

This is used to provide description for every feature of java program.it is mostly used in API(Application
programming interface).

First example:
java.lang.*;

class Test
{

public static void main(String[] args)

System.out.println("Hello World!");

Output:

4.Naming Conventions And DataTypes

Identifier: an identifier is any thing in java program either method name or variable name or classname or
lable name

Rules of identifiers:

1)Wecan use a to z ,A to Z,0 to 9,_ ,$

If we are using any other we will get compile time error.

2)can not start with digit.

Test123

123Test(nv)

3)there is no length limit for java identifiers but not recommended to use more than 15 char.

A package represents a sub directory that contains a group of classes and interfaces.name of package in java
are written in small letters as:

java.lang.*;

java.io.*;
class name and interface names start with a capital letter as:Test

method names first word of a method name is in small letters;then from second word onwards each new word
starts with a capital letter as shown here:println(),readLine(),getNumberInstance()

Datatypes:type of a data which can be stored into a variable is called datatype.

2 types

1)primitive or primitive(8) store the values2)reference type or secondary

To store objects

byte 1 bytes

short 2 bytes

int 4 bytes

long 8 bytes

float 4 bytes

double 8 bytes , boolean , char

secondary datatypes:

Array,string

Operators

Operator: - An operator is a symbol that represents an operation. `

a+b ( a, b are operands, + is the operator)

Operand: - An operand is a variable on which operator acts upon.

An operator may act upon a single operand. It is called unary operator. If an operator acts upon two
operands is called binary operand. If an operator acts on three operands is called ternary operand.

Operators in Java: -

1. Arithmetic Operators: - + - * / %

2. Unary Operators: - - ++ --

3. Assignment Operators: - = += -= *= /= %=

4. Relational Operators: - < <= > >= == !=

5. Logical Operators: - && || !

6. Boolean Operators: - & | !

7. Bitwise Operator: -

a) Bitwise Compliment: - ~

b) Bitwise and: - &

c) Bitwise or: - |

d) Bitwise xor: - ^

e) Bitwise left shift <<


f) Bitwise right shift >>

8. Ternary Operator (Conditional Operator): - ?:

9. Dot Operator (.): -

a) To refer a class in a package: - java.util.Date

b) To refer a method in class: - math.pow() emp.getsal()

c) To refer a variable in a class: - Employee.name, emp.name

10. Instanceof Operator: - To test whether an object belongs to a class.

Ex: - emp instanceof Employee.

Arithmetic Operators: - These operators perform basic arithmetic calculations like addition, subtraction, etc…

Ex: - a = 13, b = 5

S. No. Operator Meaning Example Result

1. + Addition a+b 18

2. - Subtraction a–b 8

3. * Multiplication a*b 65

4. / Division a/b 2.6

Modulus operator (Remainder of


5. % a% b 3
division)

Unary Operators or Unary minus (-) Operator: - This operator negates the value of a variable. (Negation
means converting – value into + value vice versa).

Ex: - int x = -5;

System.out.printlin(x); -5

System.out.printlin(-x); 5

System.out.printlin(-(-x)); -5

System.out.printlin(-(-(-x))); -5

Increment Operator (++): - This operator increases the value of a variable by one.

Ex: - int x = 1;

++x 2

x++  3

x=x+14

Writing ++ before a variable name is called pre incrementation. Writing ++ after a variable name is
called post incrementation.

 In pre incrementation, incrementation is done first any other task is done next.
 In post incrementation any other task is done first, incrementation is done at the end.
Ex. 1: - int x = 1; int x = 1;

S.o.println(x); S.o.println(x)

S.o.println(++x); S.0.println(x++);

S.o.println(x); S.o.println(x);

Output Output

1 1
2 1
2 2

Ex. 2: - a = 1; a = 1;

b = 2; b = 2;

a = ++b; a = b++;

a=3 a=2

b=3 b=3

Ex 3: - What is the value of the following expression, if a = 7?

++a*a++; [ b ]

a) 49 b) 64 c) 56 d) 72 e) None of these

Decrement Operator (--): - This operator decreases the value of a variable by one.

int x = 1;

--x  0

x--  -1

x=x–1-2

Writing – before a variable is called pre decrementation, writing after a variable is called post
decrementation.

Assignment Operator (=): -

1. It is used to store a value into a variable.

Ex: - int x = 15;

2. It can store the value of variable into another variable.

Ex: - int y = x;

3. It can store the value of an expression into a variable.

Ex: - int z = x + y – 10;

Note: - At the left hand side of assignment we should use only one variable.

Compact Notation: -

a = a + 10  a +=10

b = b – 100  b -=10
j=k*j j *=k

i = i/10;  i/=10

p = p%10  p%=10

Relational Operators: - These operators are useful to compare two quantities. They are used to constant
conditions.

> < >= <= == !=

Ex: - if(a>b)………..;

if(a==100)……;

if(x!=y)………...;

Logical Operators: - These operators are useful to combine more than one condition. Combining more than
one condition called Compound condition.

&& - and|| = or ! - not

Ex: - if(a>b && b>c)……………...;

if(a==100||b=50)…………...;

if(!(x==1))……………………;

Control Statements in Java

Control Statements: - Control statements modify the flow of execution and give better control for the
programmer on the flow of execution. Without control statements programmers can not able to write better
programs.

1. if…else statement 4. for loop 7. continue statement

2. do….while loop 5. switch statement 8. return statement

3. while loop 6. break statement


 A loop can be executed repeatedly. A statement can be executed once only.
If…else statement: - This statement performs a task (one or more statement) depending upon whether a
condition is true or not.

Syntax1: - if(condition)

statement1;

[else statement2;]

Ex: - //Test if a given number is +ve or –ve

class Demo

public static void main (String args[ ])

int x;

x = -15;

if(x==0)

System.out.println(“It is zero”);

else if(x>0)

System.out.println(x+ “is positive”);

else

System.out.println(x+“is negative”);

C:\rnr\javac Demo.java

C:\rnr\java Demo

Output: - -15 is negative.

Syntax 2: -

if(condition1)

if(condition2)

if(condition3)

statement1;

else statement2;

else statement3;

else statement4;

Do…while loop: - This loop repeatedly executes a group of statements as long as a given condition is true.

 Storing starting value into the variable is called initialization.


Syntax: - do
{

statements;

}while(condition);

Ex: - //To display numbers from 1 to 10

C:\rnr\javac Demo.java

C:\rnr\java Demo

Output: - 1 2 3 4 5 6 7 8 9 10

While loop: - This loop repeatedly executes a group of statements as long as a condition is true.

Syntax: -

while(condition)

(statements);

Ex: - //To display even numbers up to 10

class Demo

public static void main(String args[ ])

int i = 2;

while(i<=10)

System.out.println(i);

i = i + 2; or i +=2; [ ∵ i += is called compact notation]

} (or)

//To display even numbers up to 10

class Demo

public static void main(String args[ ])

int i = 2;

while(i<=10)
{

System.out.println(i +=2);

Q) Do…while and while loops, which loop is efficient? *****

Ans: - While loop is efficient. Right from beginning of the execution it provides control to the programmers.

for loop: - This loop repeatedly executes a group of statements as long as a condition is true.

Syntax: -

for(exp1; exp2; exp3)

statements;

exp1 is initialization expression,

exp2 is checking condition expression as long as the condition is true.

exp3 is modifying the value of variable.

Ex: - for(int i = 1; i<=10; i++)

System.out.println(i);

Note: - We can write for loop without exp1 or exp2 or exp3 or any two expressions or all three expressions.

Ex: - //Demo of for loop

class Demo

public static void main(String args[ ])

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

System.out.println(i);

}
} (or)

int i = 1;

for( ; ; )

System.out.println(i);

i++;

if(i>10)break;

Infinite loop [for( ; ; )]: - Infinite loop is a loop, which executes forever. These are drawback of
programs. It is a bad programming.

for( ; ; ) do{ while(true)

{ statements; {

statement; }while(true); statements;

} }

Note: - We can write a for loop inside another for loop. This type for loop is called Nested for loop.

Ex: - for(int i = 1; i<=3; i++)

for(int j = 1; i<=4; j++)

statements;

Switch Statement: - This statement is useful to selectively execute a task from a group of available tasks.

Syntax: -

switch(var)

case value1: statement1;

case value2: statement2;

case value3: statement3;

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

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

case valuen: statementn;

[default: default statement;]


}

Ex: - //Using Switch

class Demo

public static void main(String args[ ])

char color = ‘g’;

switch(color)

case ‘r’: System.out.println(“Red”);

break;

case ‘g’: System.out.println(“Green”);

break;

case ‘b’: System.out.println(“Blue”);

break;

case ‘w’: System.out.println(“White”);

break;

default: System,out.println(“No Color”);

 Switch statement more suitable for menu driven programs.


Break: - Break is a statement, which is useful to come out from the loop. Break is useful to the come out of
the switch statement. It is used in three ways.

1. To come out of a loop.

2. It is used to come out of a switch block.

3. Break is used to goto end of a block1.

Syntax: - break blockname;

Q) goto statements are not available in java why? *****

Ans: - 1. goto statements are decreases the readability of a program.

2. goto statements form infinite loops.

3. goto statements make documentation2 of program very difficult.

1
Block: - Block represents a group of statements written in left and right braces.
2
Documentation: - Documentation is preserving a copy of a program for future use.
4. goto is not part of structured programming.

 Factorial representation of all the steps of an algorithm is a flow chart. Algorithm consists step by step
to solve a program.
Ex: - //break as goto

class Demo

public static void main(String args[ ])

boolean x = true;

bl1: {

bl2: {

bl3: {

System.out.println(“Block 3”);

if(x==true) break bl2;

System.out.println(“Block 2);

Systen.out.println(“Block 1”);

System.out.println(“Out of all);

Continue: - This statement continues the next repetition of a loop and sub sequent statements are not
executed.

Syntax: - continue;

Ex: - //Continue

class Demo

public static void main(String args[ ])

for(int i = 10; i<=1; i--)

if(i>5)continue;
System.out.println(i);

C:\rnr\javac Demo.java

C:\rnr\java Demo

Output: -

Ex: - //Continue

class Demo

public static void main(String args[ ])

for(int i = 10; i<=1; i--)

if(i<5)continue;

System.out.println(i);

C:\rnr\javac Demo.java

C:\rnr\java Demo

Output: -

10

5
return statement: -

1. It is used to come out of a method to the calling method.

Syntax: - return;

2. return statement can return a value to the calling method.

Syntax: - return x;

return y;

return (x+y);

Ex: - //return statement in main()

class Demo

public static void main(String args[ ]);

int x = 1;

System.ot.println(“Before return”);

if(x==1)return;

// or we can use as here System.exit(0); in the place of above statement return;

System.out.println(“After return”);

[ ∵ Where in System.exit(0), System is a class name and exit is a method.]

 What is the difference between System.exit(0) and System.exit(1)? *****


Ans: - System.exit(0) is represents normal termination.

System.exit(1) is represents termination with errors.

Input And Output

Accepting Input from the keyboard:

import java.io.*;

class Accept

public static void main(String[] args) throws Exception

// create Buffered Reader object to accept data from keyboard

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


//ask for char and read it

System.out.println("enter a character:");

Char ch=(char)br.read();

//display the charater

System.out.println("you entered:"+ch);

Accepting a string from keyboard:

import java.io.*;

class Accept1

public static void main(String[] args) throws Exception

// create Buffered Reader object to accept data from keyboard

BufferedReaderbr=new BufferedReader

(newInputStreamReader(System.in));

//ask for string and read it

System.out.println("enter a name:");

String name=br.readLine();

//display the string

System.out.println("you entered:"+name);

Accepting integer from keyboard:

import java.io.*;

class Accept2

public static void main(String[] args) throws Exception

// create Buffered Reader object to accept data from keyboard

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

//ask for integer and read it

System.out.print("enter an int value:");


int num=Integer.parseInt(br.readLine());

//display the int

System.out.println("you entered:"+num);

Generating Fibonacci numbers:

import java.io.*;

classFibo

public static void main(String[] args) throws Exception

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

System.out.print("Hw Many Fibo's?");

int n=Integer.parseInt(br.readLine());

long f1=0,f2=1;

System.out.println(f1);

System.out.println(f2);

long f=f1+f2;

System.out.println(f);

int count=3;

while(count<n)

f1=f2;

f2=f;

f=f1+f2;

System.out.println(f);

count++;

}}

Arrays
Introduction:
An array is an indexed collection of fixed no of homogeneous data elements.
The main limitation of array is fixed in size.
I,e once we created an array there is no chance of increasing or decreasing based on our
requirement .
This limitation we can overcome by using collections concepts.
Ex:int[] x=new int[1000];

Array declaration :
1)single dimensional array declaration:
3 ways to declare single dimention
1)int[]a;
2)inta[];
3)int []a;
Note:1) way is recommended(name is clearly separated from type)
Int[6] a;
Above code is NV
c.e:’]’ expected ,not a java statement
Note:at time of declaration we are not allowed to specify size
otherwise we will get compile time error.
Ex:int[] a;(V)
2)two dimensional array declaration:
1)int[][] a;
2)int a[][];
3)int [][]a;
4)int[] []a;
5)int[] a[];
6)int []a[];
Above all V
3)Three dimensional array declaration:
1. Int[][][] a;
2. Int [][][]a;
3. Int [] [][]a;
4. Int[] a[][];
5. Int[] []a[];
6. Int[][] a[];
7. Int[] []a[];
8. Int [][]a[];
9. Int [][]a[];

Program for single dim array:

class Arr1

public static void main(String[] args)

{
//declare and initialize the array

Int arr[]={50,60,55,67,70};

//display all the 5 elements

for(int i=0;i<5;i++)

System.out.println(arr[i]);

Pro: write a program which accepts the marks of a student into a 1D array from the keyboard and finds total
marks and percentage.

import java.io.*;

class Arr2

public static void main(String[] args)throws IOException

BufferedReaderbr=new BufferedReader

(new InputStreamReader(System.in));

System.out.println("How many subjects?");

int n=Integer.parseInt(br.readLine());

int[]marks=new int[n];

for(inti=0;i<n;i++)

System.out.print("Enter marks:");

marks[i]=Integer.parseInt(br.readLine());

int tot=0;

for(inti=0;i<n;i++)

tot=tot+marks[i];
System.out.println("Total marks="+tot);

float percent=(float)tot/n;

System.out.println("percentage="+percent);

/*C:\santosh kumar>javac Arr2.java

C:\santosh kumar>java Arr2

How many subjects?

Enter marks:12

Enter marks:21

Enter marks:23

Enter marks:32

Enter marks:44

Total marks=132

percentage=26.4

*/

Pro:write a program which performs sorting of group of integer values using bubble sort technique.

import java.io.*;

class Sort

public static void main(String[] args)throws IOException

BufferedReaderbr=new BufferedReader

(newInputStreamReader(System.in));

System.out.println("How many elements you want");

int n=Integer.parseInt(br.readLine());

int[]arr=new int[n];
for(inti=0;i<n;i++)

System.out.print("Enter elements:");

arr[i]=Integer.parseInt(br.readLine());

int limit=n-1;

boolean flag=false;

int temp;

for(inti=0;i<limit;i++)

for(int j=0;j<limit-i;j++)

if(arr[j]<arr[j+1])

temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

flag=true;

if(flag==false)

break;

else

flag=false;

System.out.println(" the soring elements are");

for(inti=0;i<n;i++)

System.out.println(arr[i]);

Matrix addition:
import java.util.Scanner;

class AddTwoMatrix

public static void main(String args[])

int m, n, c, d;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");

m = in.nextInt();

n = in.nextInt();

int first[][] = new int[m][n];

int second[][] = new int[m][n];

int sum[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

first[c][d] = in.nextInt();

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )


sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices

System.out.println("Sum of entered matrices:-");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

System.out.print(sum[c][d]+"\t");

System.out.println();

Output:

import java.util.Scanner;

class MatrixMultiplication

public static void main(String args[])


{

int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of first matrix");

m = in.nextInt();

n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");

p = in.nextInt();

q = in.nextInt();

if ( n != p )

System.out.println("Matrices with entered orders can't be multiplied with each other.");

else

int second[][] = new int[p][q];

int multiply[][] = new int[m][q];

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < p ; c++ )

for ( d = 0 ; d < q ; d++ )


second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < q ; d++ )

for ( k = 0 ; k < p ; k++ )

sum = sum + first[c][k]*second[k][d];

multiply[c][d] = sum;

sum = 0;

System.out.println("Product of entered matrices:-");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < q ; d++ )

System.out.print(multiply[c][d]+"\t");

System.out.print("\n");

}
import java.util.Scanner;

class TransposeAMatrix

public static void main(String args[])

int m, n, c, d;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");

m = in.nextInt();

n = in.nextInt();

int matrix[][] = new int[m][n];

System.out.println("Enter the elements of matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

matrix[c][d] = in.nextInt();
int transpose[][] = new int[n][m];

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

transpose[d][c] = matrix[c][d];

System.out.println("Transpose of entered matrix:-");

for ( c = 0 ; c < n ; c++ )

for ( d = 0 ; d < m ; d++ )

System.out.print(transpose[c][d]+"\t");

System.out.print("\n");

---------------------
Introduction to OOPS

C, pascal, fortan,COBOL are called procedure oriented languages.

Last 20 years we are using c language .why should switch to c++/java technology?

Ex:

Calculate payroll---------------------salemp------------------

Calculate payroll is the main task .if you want calculate payroll we need basic sal that is one task attendance is
other task. And accept pf ,hra,da ,etc.

This subtasks will be writing in the functions/procedures.

If 30 functions are there we have to call from main function only .it is called one step designing

That means main function that calls sub function.

Using this type of approach you can’t develop bigger and complex projects.

Because

1project-------30,000 sub functions

(calling 30,000 functions and integrating them it is big difficult)

1)Procedure oriented approach does not provide strong modular design.in this approach task are represented
by functions and procedures.

Later,these functions are combined and called from another main function this is called single step modular
design

What does it means?

We are developing a project we develop around 30000 lines of code till yesterday.one programmer came. And
added 500 lines of code. Then the code size becomes 30500 lines.

now suddenly all the team members of the project that could not understand. That means we lost control on
the code.

Somebody asked why (;)and why error or msg coming on the code.
We can’t explain previous day you understood but today not understand .because the program added 500 lines
of code .the code is out of our hand.

What will we do? It’s most happening thing in all projects

Sol: we need another approach even though writing lakhs of code also still error is there means

It showing ----error is in that package, error is in that class, error is in that method.

Am not losing the control of code even though 5 lakhs of code is there also. That type of methodology is
needed.

That technology is object oriented technology

To represent main task you will write a class. you can take 10 main classes also. each class represent the sub
task .in that sub task we can write methods.

2)In object oriented methodology each task is represented by methods in a class we can write several such
classes and they can be integrated using another main class.so it offers two step modular design which is
useful to handle bigger and complex projects.

3)programingdoesnot reflect human being life and hence un natural .we need another approach where
programing reflects human beings life and becomes natural .because of the above reasons computer scientists
developed a new methodology called object oriented programming system(oops).

Features of OOPS:

1)class/object

2)encapsulation

3)abstraction

4)inheritance

5)polymorphism

Class/object:

Entire oops concept are developed from human being life only in our life we see several things,we see animals,
we see buildings,---etc are called objects.

object is root concept .

What is an object?

An object is any thing that exists physically in the real world .an object contains properties and can perform
actions.
Ex:

Properties are represented by variables

Action are represented by methods

An object contains variables and methods.

IIQ:what is the difference between method and function?

Ans:a method is a function written in side a class.

Class:a class is a group name that specify properties and actions of objects.

A class also contains variables and methods .

What is the difference between class and object?

Class doesnot exist physically .but object exist physically.

A class is a model or plan to create the objects.

An object is an instance(physical form) of a class.

An object doesnot exist without a class but a class can exist with out any object.

Encapsulation:

Taking data and methods which act up on the data as a single unit is called encapsulation. A class is a example
for encapsulation.
Ex:

Ex:2

3)abstraction:

Hiding un necessary data from the user is called abstraction .we use keywords like private,public,protected etc.

4)inheritance:

Creating new classes based on existing classes is called inheritance.

Reusability of code is main advantage in inheritance.

Ex:we are inheritance some qualities from our parents.

5)polymorphism:

The ability to exists in various forms is called polymorphism.

If a method or a variable or an object exhibits different behaviour in different context is called polymorphism.

Or

One object exhibits multiple behaviours is called polymorphism.

Class/object:

Ex1:

class Person

String name;

int age;

void talk()

{
System.out.println("Hello am :"+name);

System.out.println("my age"+age);

//using person class

class Demo

public static void main(String[] args)

//create person class object

Person p1=new Person();

//initialize the instance variables using the refernce

p1.name="raj";

p1.age=20;

p1.talk();

//finding the hash code of object

//System.out.println(p1.hashCode());

Output:

C:\javaprg>javac Demo.java

C:\javaprg>java

Hello am :raj

my age20

8567361

When the programmer doesn’t initialize the instance variables, java compiler inserts additional code in to the
class where it initialises instance variables with default values

Shown below.

Date type Default value


Byte 0
Short 0
Int 0
Long 0
Float 0.0
Double 0.0
Char a space
String Null
any class type Null
Bollean False

Initializing the Instance Variables:

Type1:

We can initialize one class instance variables in another class using a reference of that class.

Ex:int x=10;

Type2:
we can initialize the instance variables at the time of their declaration ,directly

Note:constants should be initialized at the time of their declaration.

final keyword isused define constant.

final doble PI=3.14159;

Type3:

We can initialize the instance variable using a constructor .

Constructor: a constructor is similar to a method that is used to initialize the instance variables of a class.

Syntax:

Person(){

A constructor name and class name must be same.

A constructor with out any parameters is called default constructor .

Ex:

Person(){

A constructor with one or more parameters is called parameterised constructor.

Ex:Person(String s,int i){

A constructor does not return any result,not even void

A constructor is called only once,at the time of creating the object.

IIQ)what is constructor overloading?

Writing two or more constructor with the same name but with a difference in the parameters is called
constructor overloading.

Note:
When the programmer does not write any constructor ,java compiler internally adds a default constructor with
default values.

Method

A method represent a group of statements that performs a particular task.

Methods are highly use ful to the programmer to make programing easy.

Parts of methods:

A method contains two parts.

1)method header or method prototype

2)method body

method header or method prototype:

method header contains method name,method parameters and return type .

returntype name(para1,para2,---)

a parameter is a variable to receive data into a method or constructor

ex:

void sum()

double sum(double x,double y)

double sqrt(double x,int n)

double power(double x,int n)

long fact(int n)

floatcalculateTax(float sal)

method body:

a method body represents a group of statements containing the logic to perform the task.

Syntax:

Statements;

Note:If a method return value we should use return statement in the method body

Ex:return x;

return 1;

return(x+y-z)

returnobj;

returnarr;

Note: a method can return only one entity.


//understanding methods

class Sample

//instance variables

private double x,y;

//parameterized constructor

Sample(double a,double b)

x=a;

y=b;

//method to calculate sum of x and y

//method does not accept any value and

//doesnot return result

void sum()

double z;

z=x+y;

System.out.print("sum"+ z);

class Methods

public static void main(String[] args)

//createing the object and pass values 10,20 to constructor

Sample s=new Sample( 10,20);

//call the method and find sum of x,y

s.sum();

}
Output:

C:\javaprg>javac Methods.java

C:\javaprg>java Methods

sum30.0

a method that acts upon the instance variables is called instance method.

Instance methods are called using objectname.methodname

A static method is a method that doesnot act up one the instance varibales of a class.static method are
declared using the keyword static.

Static methods can be called using objectname.methodname and classname.methodname

Static methods can’t read instance variable because jvm first executes the static methods and then only it
creates objects.

Jvm’s preference:

1)static block

2)static method

3)createobj

4)instance methods

Static methods can access static variables.

Static variable should also declared as static.

IIQ:what is difference between instance variables and static variable?

Instance variable is a variable whose separate copy is available to every object .

If the instance variable is modified in an object it will not affect other objects.

The static variable is a variable whose single copy is shared by all the objects. if the static variable is modified
it will affect all the objects.

Instance variable are created on heap memory

Static variable are stored on method area.

Ex:

class Static

public static void main(String[] args)

System.out.println("static method");

static{

System.out.println("static black");
}

Output:

C:\javaprg>javac Static.java

C:\javaprg>java Static

static black

static method

JVM

Jvm is the heart of entire java program execution process.it is responsible for taking .classfile and convert each
bytecode instruction into machine language instructions that can be executed by the microprocessor.

First .java program is converted into a .class file consisting of byte code of instructions by the java compiler.

Java compiler is outside of the jvm

.class file given to classloader sub system.which perform the following steps.

a)first of all it loads the class file into memory

b)then it verify whether all byte code instructions are proper or not.

It is not proper then execution rejected immediately

c)instruction is proper then it allocates necessary memory to execute the program.

The memory divided into 5 parts called runtime data areas.

1)methodarea:method area is the memory block which stores the class code,code of the variables and code of
the methods in java program.
2)Heap:this is the area where objects are created.when everjvm loads a class ,amethod and a heap area are
immediately created in it.

3)javastacks:java method code is executed on method area.

4)pcregister:these are the registers which contain memory address of the instructions of the methods.if there
are 3 methods ,3 pc register will be used to track the instructions of the methods.

5)native method stacks:

Native methods are executed on native method stacks(it contain c/c++ functions)

Execution Engine :it contain interpreter and jitcompiler,which responsible for convert bytecode to machine code

Jit is used increase the speed of execution of java program.

Polymorphism

The ability to existing various form is called polymorphism.if a method or variable or object performs different
tasks is called polymorphism.

2 types of polymorphism

1) static polymorphism

2) dynamic polymorphism

**Polymorphism is achieved through interface concept.

//Method Overloading

class Sample

void add(int a, int b)

System.out.println("Sum of two = " +(a+b));

void add(int a, int b, int c)

int d = a+b+c;

System.out.println("Sum of three = " +d);

Class Poly

public static void main(String args[ ])

Sample s = new Sample();

s.add(10,20);
s.add(10,20,30);

------------------------------------------------------------Moviee.java------------------------

public interface Moviee{

void fight();

void dance();

Javac Moviee.java

--------------------------------------------------------------------------------
SrkMoviee.java----------------------------------------

public class SrkMoviee implements Moviee

public void dance(){

System.out.println("Srk dance");

public void fight(){

System.out.println("Srk fight");

--------------------------------------------------------------------------------
UpMoviee.java-----------------------------------------------

public class UpMoviee implements Moviee

{
public void dance(){

System.out.println("Up dance");

public void fight(){

System.out.println("Up fight");

public class Release

public static void main(String[] args)

SrkMoviee srk=new SrkMoviee();

srk.dance();

srk.fight();

public class Release

public static void main(String[] args)

UpMoviee up=new UpMoviee();

up.dance();

up.fight();

Type casting
converting one datatype into another datatype is called type casting or casting.

Datatype:type of data stored in to a variable I,e called datatype.

There are 2 types of data types

1)primitive datatype or fundamental datatype: these data type represent a single value or single entity.

Methods are not available to handle them

Ex:b,s,ch,i,l,f,d,b

2)advanced datatypes or referenced datatype:these datatype represent a group of values methods are also
available to handle them.
Ex:any array

Any class(ex:string,Employee)

Note:1)we can convert primitive datatype into another primitive datatype using type casting.

2)we can convert one advanced type into another advanced type using type casting.

3)but we can’t use casting to convert a primitive datatype into an advanced type and vice versa.

For this purpose we should use wrapper class methods.

Casting primitive datatypes:

a)widening:casting a lower datatype into a higher data type is called widening.

Is also called implicit casting(internally casting).

byte,short,char,int,long,float,double

Lower-----------------------------------higher

Note:Boolean is not possible to convert any other datatypes.

Ex; char ch=’A’;

int n=ch;----int n=(int)ch;

Output:

N=65 is the assci value of A

(typecasting is example for polymorphism of variable)

Ex2:int num=12;

float x=num;

-------------------------float x=(float)num;

Widening is safe this is the reason even though cast operator is not written ,java compiler will not display any
error.

b)narrowing:

converting a higher datatype into a lower data type is called narrowing.it is also called explicit casting.

Ex:1)int n=66;

Char ch=(char)n;

Int-----char

Higer----------lower

Ex:2)double d=12.987;

Int n=(int)d;

Double----int

Note:loosing 987

In narrowing some digits may be lost it is un safe operation.


.

A method with method body is called a concrete method or complete method.

When all the objects share the same feature(method)then we should write a concrete method in the class.

*A method without method body is called abstract method.

That means concrete X abstract

Usage:When the objects need different implementations(body)for the same method then we should write an
abstract method.

*A class that contains abstract methods is called abstract class.

An abstract class and abstract methods should be declared using keyword abstract.

Abstract means incomplete class.

We can’t create object to abstract class because incomplete class .

How can I use it?

(Generally procedure is when you write a class what used class to create object to that class that means
unless you create a object can’t be used that class

1)write a class

2)used a class means create a object

How to create object to abstract class

For this purpose I will write a subclass to this abstract class

Adv:common requirement of all objects full field.

Abstract class is more flexible than ordinary class.

abstract class Car

//all cars will have a reg no

int regno;
//to store regno

Car(int r)

regno=r;

//all cars will have fueltank

void fillTank()

System.out.print("take car key and fill fuel into tank");

//all cars will have steering but diff cars will have diff steering

abstract void steering(int direction);

//all cars will have breaking but diffcars will diff break mechanism

abstract void breaking(int force);

Javac Car.java

class Maruthi extends Car

Maruthi(int regno)

super(regno);

void steering(int direction)

System.out.println("maruthi uses manual steerinf");

System.out.println("please drive it");

void breaking(int force)

System.out.println("maruthi uses hydraulic breaks");

System.out.println("please stop it");

}
}

Javac Maruthi.java

class Santro extends Car

Santro(int regno)

super(regno);

void steering(int direction)

System.out.println("santro uses power steering");

System.out.println("please drive it");

void breaking(int force)

System.out.println("santro uses gas breaks");

System.out.println("please stop it");

Javac Santro.java

class Usecar

public static void main(String[] args)

//create objcts for maruthi,santro

Maruthi m=new Maruthi(9999);

Santro s=new Santro(1111);

Car c;

//use reference to refer to sub class object

c=s;//or c=m;

c.fillTank();

c.steering(2);

c.breaking(100);
}

C:\core>javac Usecar.java

C:\core>java Usecar

take car key and fill fuel into tanksantro uses power steering

please drive it

santro uses gas breaks

please stop it

abstract class:

1)an abstract class is a class with zero or more abstract methods.

2)an abstract class contains instance variable and concrete methods inaddition to abstract methods.

3)we cannot create an object to abstract class

4)but we can create a reference of abstract class type

5)all the abstract methods of the abstract class should be implemented (body) in its sub classes

6)if any abstract method is not implemented then that sub class should be declared as abstract

7)abstract class reference can be used to refer to the objects of its subclasses

8)when an abstract class is created it is the duty of the programmer to create subclasses for it.

9)a class cannot be declared both as abstract and final

Ex:final abstract class Myclass

It is invalied.

INTERFACE

An interface is a specification of method prototype.

Number of methods will have body.

all are abstract methods only.


A driver is a software that contains one or more implementation classes.

**note:abstract classes and interfaces are example for dynamic polymorphism

interface:

1)an interface is a specification of method prototype

2)an interface contains 0 or more abstract methods

3)all the methods of the interface are public and abstract by default.

4)an interface contains variable which are public,static and final by default.

5)we can’t create an object to an interface.

6)but we can create a reference of interface type.

7)all the methods of the interface should be implemented in its implementation classes.

8)if any method is not implemented then that implement class should be declared as abstract.

9)interface reference can be used to refer to the objects of its implementation classes.

10)once an interface is written any third party vendor can provide implementation classes.

*11)an interface cannot implement another interface.

*12)an interface can extends another interface

*13)it is possible to write class with in an interface

14)a class can implement multiple interfaces

Ex:class Myclass implement Inter1,Inter2--------

Types of inheritance:

Single

Multiple

Single inheritance:

Creating sub classes from a single super class is called

single inheritance

Multiple inheritance:

Creating sub classes from multiple (more than one) superclasses is called multiple inheritance .
Class Father

Class Mother

Class Child extends Father,Mother

//multiple inheritance is invalid in java

Class x

Class y

Class z

Class A extends x,y,z

Class B extends x,y,z

IIQ:why multiple inheritance is not available in java

1)mult inheritance leads to confusion for a programmer

2)java programmer can achieve mult inheritance with the help of multiple

interfaces.

Ex:

Class Z implement A,B

3)a java programmer can achieve mult inheritance by reusing single inheritance several times.

Class Z extends A,B //invalied in java


Class b extends A

Class Z extends B

Above are valid

Because of above reasons mult inheritance is not available directly in java.

//multiple inheritance

interface Father

float HT=6.2f;

void height();

interface Mother

float HT=5.0f;

void height();

class child implements Father, Mother

public void height()

System.out.print("child height"+ (Father.HT+Mother.HT)/2);

class Multi1

public static void main(String[] args)

child ch =new child();

ch.height();

Output

C:\javaprg>javac Multi1.java
C:\javaprg>java Multi1

child height5.6

Access specifiers

Access specifers are keywords which specify how to access are read the instance variables or class itself.

4 types of access specifiers

1) private

2) public

3) protected

4) default

1. private members of a class are not accessible in other classes. Either in the same package or another
package .so the scope of private specifers is class scope.
2. Public members of a class are available to other classes any where in the same package or another
package.scope of public specifies is global scope.
3. Protected members are accessible to the classes in the same package,butnot in the packages.
4. Default members are available to the classes of same package,but not in the other packages.*scope
of default spicier is package scope

Note:protected members are always available to the sub classes either in the same package or in another
package.

API

Api means application programming interface .it is a html file that contains description of all the features of a
software, a product, or a new technology.

Api document is useful to understand and utilize all the feature of a product efficiently .

BUG
A bug is an error in the java program. There are 3 types of errors

1. Compile time errors


2. Runtime errors
3. Logical errors.

Compile time errors:

These errors are in the syntax and grammer of the language .these errors are detected at compilation
time .by checking the program we can eliminates compile time errors.

Runtime errors:

These errors occur because of inefficiency of the computer system to execute a statement .these errors
are detected by jvm at the time of running the program.

Logical errors:

These are the errors in the logic of the program .these errors are not detected by the compiler or by the
jvm

By comparing the manually calculated result with the program output we can detect the logical errors.

Exception

An exception is a runtime error.that can be handled by a programmer.

*IIQ:what are checked exceptions?

The exceptions detected by java compiler at compilation time are called checked exception.

The exception detected by jvm at run time are called un checked exceptions.

All exception are represented as classes in java.

*Without exception handing code:

class Test2

public static void main(String[] args)

System.out.println("start");

System.out.println(10/0);

System.out.println("start3");

}
}

R.E(output)

C:\shiva>javac Test2.java

C:\shiva>java Test2

start

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Test2.main(Test2.java:7)abnormal and not graceful termination.

With exception handling code

class Test2

public static void main(String[] args)

System.out.println("start");

try{

System.out.println(10/0);

}catch (ArithmeticException e)

System.out.println("divided by zero is not valied");

System.out.println("start3");

o/p

start

divided by zero is not valied

start3Normal and graceful termination

You might also like