Java Fast Track
Java Fast Track
.exe file contains machine language instructions. .class file contains byte code instructions.
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)
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?
Garbage collector is automatically invoked whie the program is being run.It can be also called as gc()method.
Comments : comments are the description about the features of a program.3 types of comments in java
1)single line comments
Single line comments :These comments are for marking a single line as a comment .These comments start
with double slash symbol(//).
Multi line comments: these comments are used for represent several lines as comments.these comments start
with /* and end with*/
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
{
System.out.println("Hello World!");
Output:
Identifier: an identifier is any thing in java program either method name or variable name or classname or
lable name
Rules of identifiers:
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()
2 types
To store objects
byte 1 bytes
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
secondary datatypes:
Array,string
Operators
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: - = += -= *= /= %=
7. Bitwise Operator: -
a) Bitwise Compliment: - ~
c) Bitwise or: - |
d) Bitwise xor: - ^
Arithmetic Operators: - These operators perform basic arithmetic calculations like addition, subtraction, etc…
Ex: - a = 13, b = 5
1. + Addition a+b 18
2. - Subtraction a–b 8
3. * Multiplication a*b 65
Unary Operators or Unary minus (-) Operator: - This operator negates the value of a variable. (Negation
means converting – value into + value vice versa).
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+14
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
++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.
Ex: - int y = x;
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.
if(a==100||b=50)…………...;
if(!(x==1))……………………;
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.
Syntax1: - if(condition)
statement1;
[else statement2;]
class Demo
int x;
x = -15;
if(x==0)
System.out.println(“It is zero”);
else if(x>0)
else
System.out.println(x+“is negative”);
C:\rnr\javac Demo.java
C:\rnr\java Demo
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.
statements;
}while(condition);
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);
class Demo
int i = 2;
while(i<=10)
System.out.println(i);
} (or)
class Demo
int i = 2;
while(i<=10)
{
System.out.println(i +=2);
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: -
statements;
System.out.println(i);
Note: - We can write for loop without exp1 or exp2 or exp3 or any two expressions or all three expressions.
class Demo
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.
{ statements; {
} }
Note: - We can write a for loop inside another for loop. This type for loop is called Nested for loop.
statements;
Switch Statement: - This statement is useful to selectively execute a task from a group of available tasks.
Syntax: -
switch(var)
------------
------------
class Demo
switch(color)
break;
break;
break;
break;
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
boolean x = true;
bl1: {
bl2: {
bl3: {
System.out.println(“Block 3”);
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
if(i>5)continue;
System.out.println(i);
C:\rnr\javac Demo.java
C:\rnr\java Demo
Output: -
Ex: - //Continue
class Demo
if(i<5)continue;
System.out.println(i);
C:\rnr\javac Demo.java
C:\rnr\java Demo
Output: -
10
5
return statement: -
Syntax: - return;
Syntax: - return x;
return y;
return (x+y);
class Demo
int x = 1;
System.ot.println(“Before return”);
if(x==1)return;
System.out.println(“After return”);
import java.io.*;
class Accept
System.out.println("enter a character:");
Char ch=(char)br.read();
System.out.println("you entered:"+ch);
import java.io.*;
class Accept1
BufferedReaderbr=new BufferedReader
(newInputStreamReader(System.in));
System.out.println("enter a name:");
String name=br.readLine();
System.out.println("you entered:"+name);
import java.io.*;
class Accept2
System.out.println("you entered:"+num);
import java.io.*;
classFibo
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[];
class Arr1
{
//declare and initialize the array
Int arr[]={50,60,55,67,70};
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
BufferedReaderbr=new BufferedReader
(new InputStreamReader(System.in));
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);
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
BufferedReaderbr=new BufferedReader
(newInputStreamReader(System.in));
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;
for(inti=0;i<n;i++)
System.out.println(arr[i]);
Matrix addition:
import java.util.Scanner;
class AddTwoMatrix
int m, n, c, d;
m = in.nextInt();
n = in.nextInt();
first[c][d] = in.nextInt();
second[c][d] = in.nextInt();
System.out.print(sum[c][d]+"\t");
System.out.println();
Output:
import java.util.Scanner;
class MatrixMultiplication
int m, n, p, q, sum = 0, c, d, k;
m = in.nextInt();
n = in.nextInt();
first[c][d] = in.nextInt();
p = in.nextInt();
q = in.nextInt();
if ( n != p )
else
multiply[c][d] = sum;
sum = 0;
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
import java.util.Scanner;
class TransposeAMatrix
int m, n, c, d;
m = in.nextInt();
n = in.nextInt();
matrix[c][d] = in.nextInt();
int transpose[][] = new int[n][m];
transpose[d][c] = matrix[c][d];
System.out.print(transpose[c][d]+"\t");
System.out.print("\n");
---------------------
Introduction to OOPS
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.
If 30 functions are there we have to call from main function only .it is called one step designing
Using this type of approach you can’t develop bigger and complex projects.
Because
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
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.
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.
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.
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:
Class:a class is a group name that specify properties and actions of objects.
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:
5)polymorphism:
If a method or a variable or an object exhibits different behaviour in different context is called polymorphism.
Or
Class/object:
Ex1:
class Person
String name;
int age;
void talk()
{
System.out.println("Hello am :"+name);
System.out.println("my age"+age);
class Demo
p1.name="raj";
p1.age=20;
p1.talk();
//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.
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
Type3:
Constructor: a constructor is similar to a method that is used to initialize the instance variables of a class.
Syntax:
Person(){
Ex:
Person(){
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
Methods are highly use ful to the programmer to make programing easy.
Parts of methods:
2)method body
returntype name(para1,para2,---)
ex:
void sum()
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;
class Sample
//instance variables
//parameterized constructor
Sample(double a,double b)
x=a;
y=b;
void sum()
double z;
z=x+y;
System.out.print("sum"+ z);
class Methods
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.
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’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
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.
Ex:
class Static
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.
.class file given to classloader sub system.which perform the following steps.
b)then it verify whether all byte code instructions are proper or not.
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.
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.
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
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
//Method Overloading
class Sample
int d = a+b+c;
Class Poly
s.add(10,20);
s.add(10,20,30);
------------------------------------------------------------Moviee.java------------------------
void fight();
void dance();
Javac Moviee.java
--------------------------------------------------------------------------------
SrkMoviee.java----------------------------------------
System.out.println("Srk dance");
System.out.println("Srk fight");
--------------------------------------------------------------------------------
UpMoviee.java-----------------------------------------------
{
public void dance(){
System.out.println("Up dance");
System.out.println("Up fight");
srk.dance();
srk.fight();
up.dance();
up.fight();
Type casting
converting one datatype into another datatype is called type casting or casting.
1)primitive datatype or fundamental datatype: these data type represent a single value or single entity.
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.
byte,short,char,int,long,float,double
Lower-----------------------------------higher
Output:
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
When all the objects share the same feature(method)then we should write a concrete method in the class.
Usage:When the objects need different implementations(body)for the same method then we should write an
abstract method.
An abstract class and abstract methods should be declared using keyword abstract.
(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
int regno;
//to store regno
Car(int r)
regno=r;
void fillTank()
//all cars will have steering but diff cars will have diff steering
//all cars will have breaking but diffcars will diff break mechanism
Javac Car.java
Maruthi(int regno)
super(regno);
}
}
Javac Maruthi.java
Santro(int regno)
super(regno);
Javac Santro.java
class Usecar
Car c;
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
please stop it
abstract class:
2)an abstract class contains instance variable and concrete methods inaddition to abstract methods.
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.
It is invalied.
INTERFACE
interface:
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.
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.
Types of inheritance:
Single
Multiple
Single inheritance:
single inheritance
Multiple inheritance:
Creating sub classes from multiple (more than one) superclasses is called multiple inheritance .
Class Father
Class Mother
Class x
Class y
Class z
2)java programmer can achieve mult inheritance with the help of multiple
interfaces.
Ex:
3)a java programmer can achieve mult inheritance by reusing single inheritance several times.
Class Z extends B
//multiple inheritance
interface Father
float HT=6.2f;
void height();
interface Mother
float HT=5.0f;
void height();
class Multi1
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.
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
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
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.
class Test2
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
class Test2
System.out.println("start");
try{
System.out.println(10/0);
}catch (ArithmeticException e)
System.out.println("start3");
o/p
start