Java Notes bca 4th sem


Understanding first Java Program:
First program in java:-
Class simple
{
public static void main (String args[])
{
System.out.println("hello java");
}
}
Output
Hello java
Class:-
It is a keyword that is used to declare class in java.
Public:-
It is a keyword that is an access modifier that declare the main method as unprotected and there for making it accessible to all other address.
Static:-
It is a keyword if we declare any method as static it is known as static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM(Java virtual machine).

Void:-
 It is a return type of the method between it does not return any value.
Main:-
It represents start up of the program.
String [] args:-
It is used for command line arguments.
System.out.println ():-
It is used to print statement.
Way to write java program:-
·       By changing sequence of modifier method prototype is not changed e.g. static public void main (string arg[]).
·       Sub script notation in java array can be used after type before variable or after variable.
Public static void main (string arg [])
Public static void main (string [] arg)
Public static void main (string [] args)
Compiling the program:-
To compile the Deepak Program, Execute the compiler, javac, specifying the name of the source file on the command line.
C:\>javac Deepak.java (enter)
C:\java Deepak (enter)
History of java
Java Is used in internet programming, mobile device, E-business solution etc.
There are given the major point that describes the history of java.
1.    James gosling mike Sheridan and patrik maughton initiate the java language project is java 1991.the small team of sun engineers called green team.
2.    Originally design for small embedded system in electronic application like step top boxes.
3.    Firstly it was called green talk by James  gosling and file extension was gt.
4.    After that it was called oak.
5.    Oak is a symbol of strength.
6.    In 1995 oak was renamed as “java”.
Feature of Java
1.    Simple:-
Java language is a simple because syntax is based on c++ remove many confusing feature that is explicit pointer, operator overloading etc. no need to remove unreferenced objects because there is automatic garbage collection in java.
2.    Objects oriented:-
Opps is a methodology that simple software development and maintenance by providing some rules.
Basic concept of oops are
a.     Object
b.    Class
c.     Inheritance
d.    Polymorphic
e.     Abstraction
f.      Encapsulation


3.    Platform independent:-
A platform is a hardware and software environment in which program runs. There are two types of platform. 
·       Software
·       Hardware
Java provides software based platform.
It has two components.
a.     Runtime or java runtime environment .
b.    API (application programming interface).
Java code can be run on multiple platforms that are windows, Linux etc.mac/os.
Java code is compiled by compiler and converted into byte code. This byte code is platform indepented code platform that is write one and run anywhere (WORA).

 








4.    Secured :-
Java is secured because
·       No explicit pointer
·       Program run inside virtual machine send box with java secured feature it enables us to developed virus free, temper free system.
                  Java program always run in java runtime –time environments with almost null instruction with system os.Hence it is more secure.
5.    Robust:-
 Robust simply means strong. There are lacks of pointer that avoid security problem. There is a automatic garbage collection in java. There is exception handling all these points make java robust.
6.     Architecture. Neutral:-
There is no implementation dependent features that is size of primitive types is set.
7.     Portable: -
We may carry the java byte code to any platform.
8.    High-performance:-
Java is faster than traditional interpretation since byte code is close to native code still somewhat slower than a compiled language.
9.    Multi Threaded:-
A threaded like a separate program executing can correcting multi threaded means handling multiple task simultaneously.
JAVA VIRTUAL MACHINE(JVM)
     It is a abstract machine that provided run time environment (RTE) in which java byte code can be executed.
     jvm are available for many hardware and software platform. it is specification that is provided by SUN and other company.

JVM perform the following operations

·       Loads code
·       Verifier code
·       Execute code
·       Provide run time environment
Internal Architecture of JVM
It contains class loader,memory(class)area,execution engine etc.
v Class loader: -
It is a sub system of jvm that is used to load class files.
v Class (method) area:-
It store pre-class structure such as the runtime field, method data etc.
v Heap:-
 It is the runtime area in which objects are allocated.
v Execution engine:-
It contains virtual processor.
v Interpreter:-
Read byte code then execute the instruction.
v Just in time(JIT) compiler:-
It is the compiler parts of byte code that reduce the amount of time needed for compilation.
Variable in java
It is a name of reserved area allocated memory.

10
 
                                                 Reserved area

Note:-That is represented any value.
Types of variable: - There are three types of variable.
1.    Local variable
2.    Instance variable
3.    Static variable
1.Local variable:-
A variable that is declared inside the method is called Local variable.
2. Instance variable:-
A variable that is declared inside the class but outside the method is called instance variable. It is not declared as statics.
3. Static variable:-
A variable that is declared as static is called static Variable, it cannot be local.              
Data type in Java:-
There are two types of data types.
v Primitive  data type
v Non-primitive data type
Primitive  data type :-
·       Boolean →Boolean
·       Numeric
·       Character →char
           Integral                    integer                 Floating point
Byte ,Short ,Int ,Long                                          Float , double


Non-primitive data type:-
·       Array
·       String etc.
Data type
Default value
Default size
Boolean
False
1 bit
Char
100000
2 byte
Byte
0
1 byte
Short
0
2 byte
Int
0
4 byte
Float
0.of
4 byte
Long
0.Lo
8 byte
Double
0.od
8 byte

Note :- Java used Unicode system and 100000 is the lowest range of
             Unicode.
Unicode system in java:-
 It is a universal international standard character encoding that    represents most of the world’s language. In Unicode system java holds two bytes so java also uses two bytes for char.
Operation in java:-
They are used manipulate primitive data types operators in java fall into 8 different categories.
1.    Assignment operator(=)
2.    Arithmetic operator (+,-,*,/,++,--)
3.    Relational operator (>,<,≤,≥,=,|,=)
4.    Logical operator (&&,||,&,!,˄,˅)
5.    Bit wise operator(&,˄,>>)
6.    Compound assignment operator(+,=,-,*,/,etc)
7.    Conditional operator (?, :)
8.    Type operator

1.    Assignment operator (=) :-
Java assignment operator statement has the following syntax:-
Variable =expression
 a= 5;
Program:-

Class assignment
{
Public static void main(String args[])
{
int i,j;
i=10;
j=5;
System.out.println ("i="+i);
System.out.println ("j="+j);
}
}
Output:-
J=5 ,J=5

2.    Arithmetic operator: - It is used to construct mathematical expression.java provide all basic arithmetic operators these can operate on any built in numeric data type. we cannot use these operators on Boolean expression.

Program:-
class floatpoint
{
public static void main(String args[])
{
float a=20.5f,b=6.4f;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a+b="+(a+b));
System.out.println("a-b="+(a-b));
System.out.println("a*b="+(a*b));
System.out.println("a/b="+(a/b));
System.out.println("a%b="+(a%b));
}
}
Output
A=20.5
B=6.4
A+b=26.9
a-b=14.1
a*b=131.2
a/b=3.203125
a%b=1.2999997
3. Relational operator:-These are used to compare two quantities.
Program:-
class Relation
{
public static void main(String arg[])
{
float a=15.0f,b=20.75f,c=10.0f;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("a<bis"+(a<b));
System.out.println("a>is"+(a>b));
System.out.println("a==cis"+(a==c));
}
}
Output
A=15.0
B=20.75
C=10.0.
     A<is true
b>Is false
4.Logical Operation :-The logical operation && and || are used when we want to from compound condition by computing two or more relation.
that is 
a>b && x== 0
if(age >55 && salary<1000)
if(number<0 || number>1000)

5.conditional operator:- this operator is used to condition expression of the form.
exp1,exp2, exp3
it is also known as ternary operator. this operator consist of three operand.The goal of the operator is to decide which value should be assign to the variable.
program:

class test 
{
public static void main(String arg[])
{
for (x=10;x<20;x++)
{
System.out.println("value of x is"+x);

}}}

output

6. Bit wise operator:
Java define several bit wise which can be applied to integer type ,long,int,short,char,byte,bit wise operator works on bits and perform bit by bit operator.

program:

class Test
{
public static void main(String arg[])
{
int a,b;
a=60;
b=13;
a=00111100;
b=00001101;
System.out.println("value of a is "+a);
System.out.println("value of b is "+b);
}

}
output
Object in java:-
an entity that has state and behavior is known as an object e.g.chair,market,bike,table etc.
There are three components
  1. state:-It is represent data of an object.
  2. Behavior:-It is represent the behavior (functionality)of an object such as deposit,withdraw.
  3. Identity:-Object identity is typically implement via a unique I/O.
Example:-
Pen is an object ,it is name is Flair,color is white etc.known as its state.It is used to write ,so writing its behavior.
Object is an instance of a class
class is a template or blue print from which object are created so object is the instance (result) of a class.
Class in java:-
It is a group of object that has common properties.it is a template or blue print from which objects are created.
Java loops:-
There are many loops are used in java.
(a)while loops:-
syntax:
while(Boolean expression)
{..................
..................../statement
}
..................
..................
Example
class test 
{
public static void main(String arg[])
{
for (x=10;x<20;x++)
{
System.out.println("value of x is"+x);
}}}
                                     output
(b) The do-while loop:
A do-while loop is similar to a while loop except that a do-while loop is execute at least one time.
syntax:
do
{
..................
................../statement
}
while (Boolean expression);

Program:-
class Test
{

public static void main(String arg[])
{
for x=10;
do
{
System.out.println("value of x is"+x);
x++;
}
while (x<9);
}}
 output
Value of s is 10


Note:-While loop is a entry control loop.do-while loop is a exit control loop.for loop is a entry control loop.
3.For loop:-
The for loop is another entry control loop. The general form of for loop is
For(initialization; test condition ,update)
{
……………….
………………./statement
}
Example:
Class ForTest
{
Public static void main(String arg[])
{
int x;
For(x=10;x<20;x++)
{
System.out.println ("value of x is"+x);
}
}
}
Output
Value of x :10
……………
X:19
Enhanced for loop in java:
As of java 5 the enhanced for loop was introduced. This is mainly used for arrays.
(1)          Declaration :-
The newly declared block variable, while is of a type compatible with the elements of array we are accessing. The variable will be available within the for block and its value would be the same as the current array elements.
(2)          Expression:
This evaluate to the array. we need to loop through the expression can be an array variable or method call that return an array.
Example:

class Test
{
public static void main(String args[])
{
int[]numbers={10,20,30,40,50};
for(int x:numbers)
{
System.out.println(x);
}
System.out.println(",");
}
}
Output
10,20,30,40,50

The break statement:-
       It is used to stop the entire loop. The break statement must be used inside any loop or a switch statement.
      The break statement will stop the execution of the inner most loop and start executing the next line of code after the block.

Syntax:-
Break;

Program:-
class Test
{
public static void main(String args[])
{
int[]numbers={10,20,30,40,50};
for(int x:numbers)
{
if(x==40)
{
break;
}
System.out.println(x);
}
}
}
Output
10
20
The continue statement:-
It is used in any of the loop control structure. It caused  the loop to immediately jump to the next iteration of the loop.
 In a for loop ,the continue causes flow of control to immediately jump to the update statement.
In a while loop or do/while loop flow of control immediately jump to the Boolean expression.

Syntax:
            Continue;
Program:
 class Test
{
public static void main(String args[])
{
int[]numbers={10,20,30,40,50};
for(int x:numbers)
{
if(x==40)
{
continue;
}
System.out.println(x);
}
}
}
Output

                                  10,20,30,40,50




Type casting:-
One data type is converted to another data type.
Assigning a value of one type to a variable of another types is known as type casting.
In Java, there are two types of casting:
Program:-

Int a=10;
Byte y=(byte) a;
In Java, there are two types of casting:

Widening Casting (automatically):-
It is also called automatically type casting.it take place the two type are compatible.
The target types are larger than the source type.

byte -> short -> char -> int -> long -> float -> double

Program:-
public class MyClass {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }
}
                           Output


9
9.0

Narrowing Casting (manually) – 

double -> float -> long -> int -> char -> short -> byte
when we are assigning a larger type value to variable of smaller type. then we need to perform explicit casting.

Program:-

class Test
{
public static void main(String args[])
{
double d=100.04;
long l=(long)d;
int i=(int)l;
System.out.println("double value"+d);
System.out.println("long value"+l);
System.out.println("int value"+i);
}
}
                Output
Double value =100.4
Long value=100
Int value=100


Array in java:

An array is a collection of similar data types.it is also called static data structure because size of array must be specified at the time of its declaration.
Index of array starts from zero to size one.





Types of array:
There are two types of array.
1     Single dimensional array:-
It has one row and multi column.it is also called linear array.

Syntax:

Data type[] array name;
        Or
      type var-name[];
          OR
      type[] var-name;
Instantiating an Array in Java:
When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:
     Array name = new data type (size);
Program:
class Array {
public static void main(String args[]) {
int a[];
a = new int[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
System.out.println(a[0]); 
System.out.println(a[1]); 
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
System.out.println(a[5]);
}
}
                                              Output
10
20
30
40
50
Declaration, instantiation and initialization of array:-
We can declare ,instantiation and initialization the java array together by
Int a[] ={33,25,37,40};
2     Multi dimensional  array:- 
Data stored in row and column based index (also known as matrix form).
 
Syntax:-
int[][] intArray = new int[10][20];
int[][][] intArray = new int[10][20][10];
 
Program:-
class Array
{
public static void main(String arg[])
{
int arr[][]= new int[3][4];
int i, j, k = 0;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
{
arr[i][j] = k;
k++;
}
for(i=0; i<3; i++){
for(j=0; j<4; j++)
System.out.println(arr[i][j] + " ");
System.out.println();
}
}
}
                                                                Output
0 1 2 3 4 5 6 7 8
Program:-2
class Array {
public static void main(String args[]) {
int[][]arr = new int[3][3];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
arr[2][0] = 7;
arr[2][1] = 8;
arr[2][2] = 9;
for(int i=0;i<arr.length;i=i+3)
System.out.println(arr[0][0]);
System.out.println(arr[0][1]);
System.out.println(arr[0][2]);
System.out.println(arr[1][0]);
System.out.println(arr[1][1]);
System.out.println(arr[1][2]);
System.out.println(arr[2][0]);
System.out.println(arr[2][1]);
System.out.println(arr[2][2]);
}
}
                                      Output:-
 
 
Program:3
class Array 
{ 
public static void main(String args[]) { 
int twoD[][]= new int[4][5]; 
int i, j, k = 0; 
for(i=0; i<4; i++) 
for(j=0; j<5; j++) { 
twoD[i][j] = k; 
k++; 
} 
for(i=0; i<4; i++) { 
for(j=0; j<5; j++) 
System.out.print(twoD[i][j] + " "); 
System.out.println(); 
} 
} 
}
                                                                            Output :-
 

Mathematical function:-
Sin (x) return the Sin of the angle x in radius. 
Cos (x) return the cos of the angle x in radius. 
Tan (x) return the Tan of the angle x in radius. 
A sin(y) return the angle whose Sin is y.
A cos (y) return the angle whose cosine is y.
A tan(y) return the angle whose Tangent is y.
Pow(x,y) return raised to y(xy)
Log (x) return the nature logarithm of x.
Sqrt (x) return the square root of x.
Max(a,b) return maximum a and b.
Min(a,b) return minimum of a and b.
Abs(A) return the absolute value of a.
Program:
class Math1
{
public static void main(String arg[])
{
double x;
x=Math.max (22,33);
System.out.println("maximum value of 22,33 is"+x);
x=Math.sqrt(64);
System.out.println("The squar root of 64 is"+x);
x=Math.abs(-55);
System.out.println("absolute value of -55 is"+x);
x=Math.pow(16,3);
System.out.println("The cube of 16 is"+x);
x=Math.log(3);
System.out.println("The natural log of 3 is"+x);
}
}
                                                             Output
Maximum value of 22,33 is 33.0
The square root of 64 is 8.0
Absolute value of -55 is55.0
The cube of 16 is 4096.0
The log of 3 is 1.098612288
 
Labeled Loops:-
in java we can give a lable  to a block of statements.
A lable is any valid java variable name,to give a lable toa a loop, place it before the loop with colon at the end.
Syntax of Labelled loop
               http://www.tutorialdost.com/images/Labelled-Loop.png
 
If we want to jump outside a nested loop or to continue a loop that is outside the current one. then we may have to use the labeled break and labeled continue statement. 
 
Program:-
class outer
{
public static void main(String arg[])
{
int m=1,n=1;
for(m=1;m<11;m++)
{
for(n=1;n<11;n++)
{
System.out.println(" "+m*n);
if(m == n);
}
}
}
}
                                                             Output:-
                                                 2 to 10 table
Program :-2
class loop1
{
public static void main(String arg[])
{
int i=1;
loop1:for(i=1;i<100;i++)
{
System.out.println("**");
if(i>10)
break;
int j=1;
loop2:for(j=1;j<100;j++)
{
System.out.println("**");
if(j==i)
break;
continue loop1;
}
}
System.out.println("Term nation by break");
}
}
                                                 Output
 
program:-3
class loop1
{
public static void main(String arg[])
{
int i=1;
loop1:for(i=1;i<100;i++)
{
System.out.println(" ");
if(i>10)
break;
{
System.out.println("*");
continue loop1;
}
}
System.out.println("term nation by break");
}
}
                                                             Output
Program:4
class deepak
{
public static void main(String args[]) 
{
outer: for (int i=0; i<10; i++) 
{
for(int j=0; j<10; j++) 
{
if(j > i) 
{
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
                                                   Output:
Program:-5
class deepak
{
public static void main(String args[]) 
{
loop: for (int i=1; i<10; i++) 
{
for(int j=1; j<10; j++) 
{
if(j > i) 
{
System.out.println(" ");
continue loop;
}
System.out.print("*");
}
}
System.out.println();
}
}
                                                             Output

Class:-
Class provided a converted method for packing together a group of logically related data items and functions that work on them.
In java data items are called fields and function are called methods.
 
Defining a class:
Syntax:-
Class classname extends super classname
{
Fields declaration;
Methods declaration;
}
 
Field declaration:-
Data is encapsulated in a class by placing data field inside the body of the class definition.These variable are called instance variable.
They are created whenever an object of the class is instanciated.
 
Program:
Class rectangle
{ 
Int length;
Int width;
}
Method declaration:
Methods are declared inside the body of class but immediately after the declaration of instance variable.
Syntax:
Data type method name(parameter list )
{
Method body
}
 
Create object:-
An object in java is essentially a block of memory that contains space to store all the instance variable.
Creating an object is also referred to as instantiating an object.
Object in java are created using ‘new’keyword.
The new operator create an object of the specified class and return reference to that objects.
Example:
Rectangle  rect1;//declaring an object
Or
Rect1=new Rectangle rect1;//instant late
Or
Rectangle rect1= new rectangle();
 
Accessing class member:
We can not access the instance variable and methods directly.
To do this we must use the object and dot(.)operator.
Objectname.variablename  = value;
Objectname.methodname (perimeter);
Here objectname is the name of object variable name is the instance variable inside the object.
Program:
class B
{
public static void main(String... ar)
{
A ob= new A();
System.out.println(ob.a);
}
}
 
Output
 
Constructor :
Java support a special type method called a constructor that enable an object to initialize itself. when it is created. constructor have same name as the class name itself. They do not specify a return type not even void.

Rules for creating constructor:
1.    Constructor name must be same as it’s class name.
2.    Constructor must have no return type.
Types of constructor:
 1).Default constructor:-
A constructor that has no parameter is known as default constructor.
2).Parameterize constructor:-
A constructor that have parameter is known as parameterize constructor.
Class name(parameter)
Example :-
class Rectangle
{
int length,width;
Rectangle(int x,int y)
{
length=x;
width=y;
}
int Rectarea()
{
return(length*width);
}
}
class Rectarea
{
public static void main(String arg[])
{
Rectangle Rect1=new Rectangle(10,15);
int Area1=Rect1.Rectarea();
System.out.println("Area is" + Area1);
}
}
                                                 Output
Area 150
Default constructor program:-
class Student
int id;  
String name;  
  
void display()
{
System.out.println(id+" "+name);
public static void main(String args[])
Student s1=new Student();  
Student s2=new Student();  
s1.display();  
s2.display();  
}
                                                 Output
                   0 Null
                   0 Null
 
Explanation:-
In the above class, we are not creating any constructor so compiler provides we a default constructor. Hare 0 and Null values are provided by default constructor.
class parameter
{
int length,breadth;
parameter()
{
length=0;
breadth=0;
}
parameter(int x,int y)
{
length=x;
breadth=y;
}
void cal_parameter()
{
int parameter;
parameter=2*(length+breadth);
System.out.println("The parameter of Rectangle is"+parameter);
}
}
class raju
{
public static void main(String arg[])
{
parameter p1=new parameter();
parameter p2=new parameter(5,10);
p1.cal_parameter();
p2.cal_parameter();
}
}
                                                 Output
The  parameter of rectangle is 0
The  parameter of rectangle is 30
Method Overloading:-
If two or more method in a class have same name but different parameters, it is also known as method over loading.
If two or more method have same name and some parameter list but different in returns types are not said to be overloading method.
                                  Different ways of methods overloading
1.Method overloading by changing the data type of arguments:
class deepak
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(float a,float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
 Calculation cal=new Calculation();  
  cal.sum(8,5);  
  cal.sum(8,9);  
}
}
                                                 Output
 
Example:-
class Calculation2
void sum(int a,int b)
{
System.out.println(a+b);
void sum(double a,double b)
{
System.out.println(a+b);
public static void main(String args[])
Calculation2 obj=new Calculation2();  
obj.sum(10.5,10.5);  
obj.sum(20,20);  
                                                                Output 
 
 
2.Method overloading by changing no. of arguments: 
class deepak
{
void find(int a,int b)
{
System.out.println("Area is"+(a+b));
}
void find(int a,int b,int c)
{
System.out.println("Area is="(a*b*c));
}
public static void main(String args[])
{
 Area.a=new Area();  
  A.find(20,30);  
  A.find(2,4,6);  
}
}
                                                          Output
Area is 600
Area is 48
 
Static Members:
We can declare instance variable and instance method as a static members that are declare static is known as static member.
The static variable and static method are often referred to as class variables and class method. 
Example:-
Class A
{
Static int a;
}
Program:
class Mathoperation
{
static float mul(float x,float y)
{
return(x*y);
}
static float divide(float x,float y)
{
return x/y;
}
}
class mathapps
{
public static void main(String args[])
{
float a=Mathoperation.mul(4,5);
float b=Mathoperation.divide(9,5);
System.out.println("a="+ a);
System.out.println("b="+ b);
}
}
                                                             Output 
a=20.0
b=1.8
 Access Modifiers:
There are  four types of access modifiers.
a)    Private
b)    Public
c)Default
d)    Protected 
a).Private:-
The private access modifier is accessible within the class.
Example:
class A
{
private int data =40;
private void msg()
{
System.out.println("Hello java");
}
}
class Simple
{
public static void main(String arg[])
{
A a=new A();
System.out.println("a data");
//compile time error
}
}
 
Note:- A class cannot be private or protected except nested class.
b). public:
·         The public access modifier has the widest scope among all other access modifiers.
·         Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members.
Example:
//Java program to illustrate 
//public modifier 
package p1; 
public class A 
{ 
public void display() 
               { 
                               System.out.println("GeeksforGeeks"); 
               } 
} 
package p2; 
import p1.*; 
class B 
{ 
               public static void main(String args[]) 
               { 
                               A obj = new A; 
                               obj.display(); 
               } 
}
                                                             Output
GeeksforGeeks
 
 c).Default:
if we do not use any modifier,it is treated as default by default the default modifier is accessible only within package.
Example:-
class A
{
private int data =40;
private void msg()
{
System.out.println("Hello java");
}
}
class Simple
{
public static void main(String arg[])
{
A a=new A();
System.out.println("a data");
//compile time error
}
}
                                                             Output
 Compile time error
d).Protected:
It is a accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member method and constructor. It cannot be applied on the class.
Example:
//Java program to illustrate 
//protected modifier 
package p1; 
 
//Class A 
public class A 
{ 
protected void display() 
               { 
                               System.out.println("GeeksforGeeks"); 
               } 
}
//Java program to illustrate 
//protected modifier 
package p2; 
import p1.*; //importing all classes in package p1 
 
//Class B is subclass of A 
class B extends A 
{ 
public static void main(String args[]) 
{ 
               B obj = new B(); 
               obj.display(); 
} 
               
}
                                              Output 
GeeksforGeeks
                                                             Reading data from keyboard:
import java.io.*;  
class Deepak
public static void main(String args[])
Console c=System.console();  
System.out.println("Enter password: ");  
char[] ch=c.readPassword();  
String pass=String.valueOf(ch);//converting char array into string  
System.out.println("Password is: "+pass);  
}
Example:
import java.io.*;  
class Deepak
public static void main(String args[])throws Exception{  
  
InputStreamReader r=new InputStreamReader(System.in);  
BufferedReader br=new BufferedReader(r);  
  
System.out.println("Enter your name");  
String name=br.readLine();  
System.out.println("Welcome "+name);  
 }  
                                                             Inheritance:
Mechanism of driving a new class from a old class is called inheritance. The old class is called base class and new class is known as sub class.
Inheritance allows subclass to inherited all the variable and method of their parent class. 
                                              Types of inheritance 
1.    Single inheritance:

 
 
  
  
  
  
  
  
  
  
  
  
  
  
 
 
 

 
 
Only one super class.
2.    Multiple inheritance:
 

 
 
 
Several super class with one sub class(java does not support it).
3.    Hierarchical inheritance:
One super class with multiple sub class.

 
 
4.    Multi level inheritance:
Drive from derived class.
We use interface instead multiple inheritance in java.

 
 
Defining a subclass:
 class
is a class which inherits a method or methods from a Java superclass.
A Java class may be either a subclass, a superclass, both, or neither!
The Cat class in the following example is the subclass and the Animal class is the superclass.
public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}
OutPut


Subclass Constructor:-
A sub class constructor is used to construct the instance variable of both the subclass and super class.
The sub class constructer uses the keyword super to invoke the constructer of the super class.
The keyword supper is used subject to the following conditions.
Supper may only be used within a subclass constructor method.
The call to super class constructor must appear as the first statement within the sub class constructor.
The parameter in the supper call must be order and type of the instance variable declares in the supper class.

Method overriding:-
A method in the subclass that has the same name, same arguments and same return type as a method in the super class, when that method is called the method defined in the sub class is invoked and executed instead of one in the super class. This process is known as method overriding.
Example:
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Output


Example:
Class super
{
Int x;
Super(int x);
This.x=x;
}
Void display()
{
System.ot.println(“super x=”+x);
}
}
Class sub extends super
{
Int y:
Sub(int x,int y)
{
Super(x);
This y=y:
}
Void display()
{
System.out.println(“super x=”+x);
System.out.println(“sub y=”+y);
}
}
Class overriding
{
Public static void main(string arg[])
{
Sub s1 =new sub(100,200);
S1.display();
}
}
Output
Super x=100
Sub y=200
Final Keyword in java:
 The final keyword in
java is used to restrict the user.
Final can be..
Variable
Method
Class
Final variable:
If we make any variable as final.we can’t change the value of this variable,means(it will be constant)
Example:
class Bike
{
final int speed=90;
void run()
{
speed=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();  
}
}
output
Compile time error
Final method:-
If we make any method as final then we cannot override the final method.
Example:
class car
{
final void run()
{
system.out.println("running");
}
class Duster extends car
{
void run()
{
system.out.println("running safely with 80kmph");
 
public static void main(String args[])
{
Duster D=new Duster();
D.run();   
}
}
                                                                            Output
Compile time error
 
Final class:-
If we make a class as final, we cannot extend it.
Example:
final class bike
{
}
class honda extend bike
{
void run()
{
system.out.println("running safely");
}
public static void main(String args[])
{
Honda h=new Honda();
h.run();   
}
}
                                                             output
compile time error
 
Finalizer  keyword in java:-
Java support a concept called finalization which is just opposite to initialize of object.it automatically free up the memory resource used by the object.object may hold other non object resource.
Such as file descriptor etc. the garbage collection cannot free these resource be must use a Finalizer method. 
Note:- it is similar to the destructor c++.
Example:-
class TestGC {
 
public static void main(String[] args) {
 
Runtime rt = Runtime.getRuntime();
 
System.out.println("Available Free Memory: " + rt.freeMemory());
 
for(int i=0; i<10000; i++ ) {
GC1 x = new GC1(i); 
}
 
System.out.println("Free Memory before call to gc(): " + 
rt.freeMemory());
System.runFinalization();
System.gc();
System.out.println(" Free Memory after call to gc(): " + 
rt.freeMemory()); 
 
}
}
 
class GC1 {
 
String str;
int id;
 
GC1(int i) {
this.str = new String("abcdefghijklmnopqrstuvwxyz");
this.id = i;
}
 
protected void finalize() {
System.out.println("GC1 object " + id + " has been finalized.");
}
 
}
                                                                            Output
 
This keyword:-
In java this is a reference variable to the current object.
                                              Uses of this keywords:
This keyword can be used to refer class instance variable. it there is a ambiguity between the instance variable and parameter this keyword resolves the problem of ambiguity.
Example:
class Student4{  
    int id;  
    String name;  
      
    Student4(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    s1.display();  
    s2.display();  
   }  
                                                             Output:-
111 Karan
222 Aryan 
 
‘This ()’constructor call can be used to invoke the current class constructor.
Constructor chaining:
Example:-
class Student5{  
    int id;  
    String name;  
    int age;  
    Student5(int i,String n){  
    id = i;  
    name = n;  
    }  
    Student5(int i,String n,int a){ 
System.out.println("default constructor is invoked"); 
    id = i;  
    name = n;  
    age=a;  
    }  
    void display(){System.out.println(id+" "+name+" "+age);}  
   
    public static void main(String args[]){  
    Student5 s1 = new Student5(111,"Karan");  
    Student5 s2 = new Student5(222,"Aryan",25);  
    s1.display();  
    s2.display();  
   }  
                                                             Output
Default constructor is invoked
Default constructor is invoked
111 Karan 
222 Aryan
 
This keyword can be passed as argument in the constructor call. We can pass this keyword in the constructor also.
Example :
class B
{
A obj;
B (A obj)
{
this.obj = obj;
}
void display()
{
System.out.println(obj.data);
}
}
class A
{
int data =10;
A()
{
B b = new B(this);
b.display();
}
public static void main(String args[])
{
A a = new A();
}
}
                                                             Output:
10
Abstract_class in java:-
A class that is declared with abstract keyword is known as abstract class. An abstract class is one that cannot be instantiated.
It contains at least one abstract method.
Example:
abstract class A
{
 abstract void callme();
 public void normal()
 {
  System.out.println("this is concrete method");
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme."); 
 }
 public static void main(String[] args)
 {
  B b=new B();
  b.callme();
  b.normal();
 }
}
                                                             output
This is call me.
 
Example :-
abstract class A
{
 abstract void callme(); 
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme."); 
 }
 public static void main(String[] args)
 {
  B b=new B();
  b.callme();
 }
}
                                                             output
this is call me.
Interface:
It support concept of multiply inheritance in java.
The interface is a mechanism to achive fully abstraction   in java. There can be only abstract method in the interface. it can not be insatiate just like a abstract class.
Defining interfaces:-
Interface interface name
{
Variable declaration
Method declaration 
}
The entire variable is declared as constants. method declaration will contain only a list of method without body.
Example:
Interface item
{
Static final int code=100;
Static final string name =”fan”;
Void display();
}
Extending interface:
Like classes interfaces can also be extended.
Syntax:-
Interface name 2 expends name1
{
Body of name2
}
Sub interface can not define the methods declare in the super interfaces.
It is responsibility of any class that implements that derived interface to define all the methods.
 
Implementing interface:
Interfaces are used as super classes whose properties are inherited by classes.
Syntax:-
Class class name implement.interface name
{
Body of class
}
 
Example:-
interface Area  //interface defined
{
    float pi=3.14F;
    float compute(float x, float y);
}
 
class Rectangle implements Area
{
public float compute (float x, float y)
{
return(x*y);
}
 
}
 
class Circle implements Area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
class InterfaceTest2
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area a;
a=rect;
System.out.println("Area of rectangle : "+a.compute(5,10));
a=cir;
System.out.println("Area of circle : "+a.compute(5,0));
 
}
}
/*
Area of rectangle : 50.0
Area of circle : 78.5
*/
                                                                            Output
Area of rectangle =
Area of cir=
Multiply inheritance in java:-
Example:
public class Main {
        
    public static void main(String[] args) {
         
          shape circleshape=new circle();
           
             circleshape.Draw();
    }
}
 
interface shape
 {
     public   String baseclass="shape";
      
     public void Draw();     
      
 }
 class circle implements shape
 {
 
    public void Draw() {
        System.out.println("Drawing Circle here");
    }
      
      
 }
                                                             Output
Drawing Circle here
Example :-
interface printable{  
void print();  
  
class A6 implements printable{  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
A6 obj = new A6();  
obj.print();  
 }  
                                                             Output
 
 
Example:
interface Printable{  
void print();  
  
interface Showable{  
void show();  
  
class A7 implements Printable,Showable{  
  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
                                               Output
Hello
Welcome
                                                             String :
 
    In java string is an object .string class used to create string object.
 
Creation of string object:-
We can create string object by two ways.
1-    By string literal:-
String literal is created by double quote “Deepak”

 
 

 
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 
 
 
 
  
 
 

 
 
 
 
Heap
Example:-String s=”Hello”
 
Note:- string object are stored in a special memory knowns as string constant pool .in side the heap memory.
2-    By New keyword:-
String S=new string (“welcome”)
                                                 Heap
Immutable string:-
 In java string objects are immutable. Immutable simply means unmodified or unchanged.            
Example:-
class raju{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
                                                 Output
   Sachin 
Example:-
class raju{  
 public static void main(String args[]){  
   String s="Sachin";  
   s=s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
                                                                Output 
    Sachin Tendulkar
                                              Method of string class in java:-
Method
Concatenating: - There are two methods to concatenate two or more string.
1-    Concate() method:-
String s=”Hello”;
String str=”java”;
String str2=s.concate(str):
String str1=”Hellow “ concate(“java”)
2-    + Operation:-
String str=”rahul”;
String str1 =”Sharma”;
String str2=str1+ str2;
String st=”Rahul”+”Sharma”;
Comparison strings:-
We can compare two given strings on the basis of content and reference. There
 are three ways to compare string objects.
1-    Equals() method:
It compare the original content of string. If compare value of string for equality string class provides.
(a)  Public Boolean equals(object another)
{………………
………………..}
(b)  Public Boolean equal ignore class (string another)
{……………….
………………..}
Example :-
class Test {
public static void main(String args[]) {
String S1 = "Raja";
String S2 = "Raj";
String S3 = new String("Raja");
String S4 = "Raj";
System.out.println(S1.equals(S2));
System.out.println(S1.equals(S3));
System.out.println(S1.equals(S4));
}
}
                                                             Output   
False   True False
 
Example:-
class simple {
public static void main(String args[]) {
String S1 = "Raja";
String S2 = "Raja";
String S3 = new String("Raj");
System.out.println(S1.equals(S2));
System.out.println(S1.equals(S2));
}
}
                                                             Output 
True  True    False   false
 
2-    == Operator:-
The == operator compare references not values.
Example:-
class simple {
public static void main(String args[]) {
String S1 = "Raja";
String S2 = "Raja";
String S3 = new String("Raja");
System.out.println(S1==S2);
System.out.println(S1==S3);
}
}
                                                          Output  
True
False 
3-    Compare to () Method:-
To compares values and return an it which tells if the values compare less than ,equal or greater than(<,==,>).
Suppose s1 and s2 are two string variable,
If  s1==s2:0
    S1>S2:positive 
    S1<S2:Negative
Example:-
class simple {
public static void main(String args[]) {
String S1 = "Raja";
String S2 = "Raja";
String S3 = "Deepak";
System.out.println(S1.compareTo (S2));
System.out.println(S1.compareTo (S3));
System.out.println(S3.compareTo (S1));
}
}
                                           Output 
   0   -  14    14
Substring in java:-
A part of string is called substring. We can get substring from the given string  object by using one of the two methods.
Public string substring (int start index):-
This method return new string object containing the substring of the given string from specified start index.
.0 1 2 3 4 – Start index
1 2 3 4 5 – End index
Public string substring (int start index.int end index)
This means method returns the new string object containing the substring of the given string from specified start index To end index.
Example:-
class simple
{
public static void main (String args[])
{
String S="Sachin Tendulkar";
System.out.println(S.Substring(6));
System.out.println(S.Substring(06));
}
} 
                                                             Output
Tendulkar 
Sachin
 To upper case ()method:-
Converts all of the characters in the string to upper case.
To lower case () method:-
Converts all of the characters in the string to lower case.
Example:
class simple 
{
public static void main(String args[]) {
String S = "Raja";
System.out.println(S.toUpperCase());
System.out.println(S.toLowerCase());
 
}
} 
                                               output 
Raja   raja raja
Example:-
class simple {
public static void main(String args[]) {
String S = "Raja";
System.out.println(S.toUpperCase());
System.out.println(S.toLowerCase());
 
}
}
                                                             Output
 
Starts with (string prefix):-
Tests,if this string starts with specified prefix.
 
End with (String suffix):-
Tests, if this string ends with the specified suffix.
Example:-
class simple {
public static void main(String args[]) {
String S = "Raja";
System.out.println(S.startsWith("Ra"));
System.out.println(S.endsWith("w"));
}
}
                                                                            Output 
True  false
 
Char A+() method:-
It returns the char value at the specified index.
 
Example:-
class simple {
public static void main(String args[]) {
String S = "Salman";
System.out.println(S.charAt(0));
System.out.println(S.charAt(3));
}
}
                                                             Output 
M
Length () method:-
It returns the length of string.
Example:-
class simple 
{
public static void main(String args[]) 
{
String S = “Salman”;
System.out.println(S.length());
 
}
}
                                                             Output
5
String buffer class:-
It is used to created mutable (modifiable)string. The string buffer class is as string except. It is mutable 0.i.e it can be changed.
Commonly used constructors of string buffer class:-
1-    String buffer ():-
Creates an empty string buffer with the initial capacity of 16.
2-    String buffer (string str):-
Create a string buffer with the specified string.
3-    String buffer (int capacity):-
Create empty string buffer with the specified capacity as length.
Methods of string buffer class:-
a)    Public synchronized string buffer append(strings):-
It is used to append the specified string with this strings.
b)    Public synchronized string buffer insert (int offset,strings):-
It is used to insert the specified string with this string at the specified position.
c)Public synchronized string buffer string replace (int start ,Index,End index,String str):-
It is used to replace the string from specified start index and end index.
d)    Public synchronized string buffer delete (int start index,int end index):-
It is used to delete the string from specified start index and end index.
e)    Public synchronized string buffer reverse ():-
It is used to reverse the string.
f) Public int capacity():-
It is used to return the current capacity.
g)    Public  void ensure capacity(int minimum capacity):-
It is used to ensure the capacity at least equal to the given minimum.
h)   Public char char A +(Int index):-.
It is used to return the character at the specified position.
i)  Public int length():-
It s used to return the length of the string that is total number of characters.
j)  Public string substring(int begin index):-
It is used to return the substring from the specified begin index.
k)Public string substring (int begin index,intend  index):-
It is used to return the substring from the specified begin index and end index.
Append ():-
Example:-
class appendDemo { 
public static void main(String args[]) { 
String s; 
int a = 42; 
StringBuffer sb = new StringBuffer(40); 
s = sb.append("a = ").append(a).append("!").toString(); 
System.out.println(s); 
} 
}
                                                          Output
Example:-
class appendDemo { 
public static void main(String args[]) { 
StringBuffer s = new StringBuffer("Hello"); 
s.append("java"); 
System.out.println(s); 
} 
}
                                                                            Output
Hello java
Insert:-

class appendDemo
{
public static void main(String args[]) {
StringBuffer s = new StringBuffer("Hello");
s.insert(1,"java");
System.out.println(s);
}
                                output
Hjavaello

Replace:-
class appendDemo
{
public static void main(String args[]) {
StringBuffer s = new StringBuffer("Hello");
s.replace(1,3,"java");
System.out.println(s);
}
}
Output

 Hjavalo
Delete:-
Example:-
class appendDemo
{
public static void main(String args[]) {
StringBuffer s = new StringBuffer("Hello");
s.delete(1,3);
System.out.println(s);
}
}
Output
Hlo
Ensure capacity:-
class StringBufferDemo {

   public static void main(String[] args) {
 
   StringBuffer buff1 = new StringBuffer("tuts point");
   System.out.println("buffer1 = " + buff1);

   // returns the current capacity of the string buffer 1
   System.out.println("Old Capacity = " + buff1.capacity());
   /* increases the capacity, as needed, to the specified amount in the
   given string buffer object */
   // returns twice the capacity plus 2
   buff1.ensureCapacity(28);
   System.out.println("New Capacity = " + buff1.capacity());

   StringBuffer buff2 = new StringBuffer("compile online");
   System.out.println("buffer2 = " + buff2);
   // returns the current capacity of string buffer 2
   System.out.println("Old Capacity = " + buff2.capacity());
   /* returns the old capacity as the capacity ensured is less than the
   old capacity */
   buff2.ensureCapacity(29);
   System.out.println("New Capacity = " + buff2.capacity());
   }
}
Output




Example:-
class A {
public static void main(String[] args) {
StringBuffer S = new StringBuffer();
System.out.println(S.capacity());
S.append("Hello");
System.out.println(S.capacity());
S.append("java");
System.out.println(S.capacity());
S.ensureCapacity(10);
System.out.println(S.capacity());
S.ensureCapacity(50);
System.out.println(S.capacity());
   }
}

Output

String builder class:-
The string builder class is used to create mutable (modifiable)string.The string builder class is same as string buffer class except that it is non-synchronized.
Constructor of string buffer class:-
(i)                          String builder():-
Create an empty string builder with the initial capacity of 16
(ii)                       String Builder(stringstr):-
Create a string builder with the specified string.
(iii)                    String builder(int length):-
Creates an empty string builder with the specified capacity as length.
Vector:-

It is a class contained in java. Util package.This class can be used to created generic(किसी टाइप का ऑब्जेक्ट )dynamic array is called vector that can hold the objects of any type and any numbers. The objects do not have to be homogeneous. vector are created like arrays.
Vector intrest =new vector();
Vector list=new vector(3);






Advantage of vector over array:-
1-   It is convenient to use vectors to stor objects.
2-   Vector can be used to stor a list of objects.
3-   We can add or delete objects from list as when required.
4-   We can not directly store simple data type in a vector.we can store object only.
5-   We can convert simple data type to objects by using wrapper class.
6-   The vector class support a no. of methods that can be used to manipulate the vector created. 


Method Call                                      Task Perform
List.add element(item)               Adds the item specified to the list
                                                               At the end.
List.element at(10)                               Gives the name of the 10th obj.return.
List.size();                                             gives the no.of object present.  
List.remove element(item)                  removes the specified item from the list.
List.remove element a+()                     remove the item store in the nth position of the list.
List.remove all elements(item)            remove the all stored items of the list.
List.copy into(array)                            copy is all the items from list to array.
List.insert element a+(item.n)             insert item at the nth  position.

Import java.util.*:-
Example:-

import java.util.*;
class VectorExample {

    public static void main(String[] args) {

        Vector<String> vc=new Vector<String>();

        //    <E> Element type of Vector e.g. String, Integer, Object ...

        // add vector elements
        vc.add("Vector Object 1");
        vc.add("Vector Object 2");
        vc.add("Vector Object 3");
        vc.add("Vector Object 4");
        vc.add("Vector Object 5");

        // add vector element at index
        vc.add(3, "Element at fix position");

        // vc.size() inform number of elements in Vector
        System.out.println("Vector Size :"+vc.size());

        // get elements of Vector
        for(int i=0;i<vc.size();i++)
        {
            System.out.println("Vector Element "+i+" :"+vc.get(i));
        }
    }
}
Output
      List of language
Ada
Basic   Fortran  c++
Cobol  java
Example :-
import java.util.Vector;

public class VectorExample {

    public static void main(String[] args) {

        Vector<String> vc=new Vector<String>();

        //    <E> Element type of Vector e.g. String, Integer, Object ...

        // add vector elements
        vc.add("Vector Object 1");
        vc.add("Vector Object 2");
        vc.add("Vector Object 3");
        vc.add("Vector Object 4");
        vc.add("Vector Object 5");

        // add vector element at index
        vc.add(3, "Element at fix position");

        // vc.size() inform number of elements in Vector
        System.out.println("Vector Size :"+vc.size());

        // get elements of Vector
        for(int i=0;i<vc.size();i++)
        {
            System.out.println("Vector Element "+i+" :"+vc.get(i));
        }
    }
}
Output


Command line argument:-
class com{ 
public static void main(String args[]){ 
System.out.println(args[0]); 
*Wrapper  class:-
 
                 Primitive
data type may be converted into object types by using wrapper class. It
contained in the “java lang”Package.
Wrapper classes for converting  simple type.

             Simple type                                       wrapper class
Int                                                     integer       
Float                                                 float
Char                                                 character
Double                                             double
Long                                                 Long
Boolean                                           Boolean
The wrapper class a no. of unique methods for handling primitive data types and objects.

Converting primitive no. to object numbers using constructor method:-
Constructor calling                     conversion action
Integer initial =new integer (i);      primitive integer to objects integer.
Float value object=new float(f);    primitive float to object float
Double value=new double(d);      primitive double to object double.
Long value=new long(i);               primitive long to object long.

Converting object number to primitive number using type value () method:-
Method calling                                       conversion action
Int i=int value int value();              object to primitive integer
Float f=int value float value();      object to primitive to float.
Double       “                                                        “
Long          “                                                        “

Converting number to string using to string();
Method calling                                      conversion action
Str =integer.to string(i)                 integer number to string                          

Converting string object to numeric object using value to ()method:
                 
Method calling                                      conversion action
Double value =double.value of(str)       convert string object to double.

Converting numeric string to primitive string using parsing method:
Method calling                                      conversion action
Int i=integer.pars int(str)                          string object to float.

Example:-




Multithreaded programming:-
Introduction :-
It is a process of executing multiple thread simultaneously.
Thread :-
It is basically light weight sub-process, a smallest unit in processing.
Advantage of multithreading in java:-
·       Thread are independent and we can perform multiple operation at same time.
·       We can perform many operation together so it save time.

Multitasking :-
It is a process to executing multiple task simultaneously.we use multitasking to utilize the cpu.multitasking can be achieved by two ways.

1-   Process based multitasking :-
(a)-Each process have it is own address in memory i.e each process allocate separate memory area.
(b)-Process is heave weight.
(c)-cost of communication between the process is high.
(d)-Switching from one process to another required some time for saving and loading REGISTER. Memory maps, updating list etc.
    2- Thread base multitasking (multithreading):-
(a)             Threads share the same address space.
(b)            Thread is light weight.
(c)             Cost of communication between the thread is low.

Creating threads:-
Threads are incremented in the form of object that contain a method called “run()”method.

Syntax:-
Public void run()
{
………………
………………(statement for implementing thread)
The run()method should be invoked by an object of the concerned thread.
There are two ways to create threads.
1-   Creating thread class
2-   Using run able interface
1-   Creating thread class:-
Define a class that extends thread class and overrides it’s run()method.
Extending the method class:-
·       Declare the class extend the thread class.
·       Implement run()method that is responsible for executing the body of method.
·       Create the method object and start ()method to initiate the thread execution.

Class thread extends thread
{
……………
……………}
Life cycle of thread (Thread states):-
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle is java new,runnable ,non-runnable and terminated. The life cycle of thread in java is controlled by java. The java thread states are as follows.

1-   New
2-   Runnable
3-   Running
4-   Non –runnable(blocked)
5-   Terminated

1-   New :- The thread is in new state if we create an instance of thread class but before the invocation of start()method.
2-   Runnable:-The thread is in runnable state after invocation of start()method but the thread scheduler has not selected it to be the runnable thread.
3-   Running:-The thread is in running state if the thread scheduler has selected it.
4-   Non-runnable (Blocked):-This is the state when the thread is still alive but is currently not eligible to run.
5-   Terminated:-A thread is in terminated or dead state when it is run()method exits.

Thread class:-
Thread class provides constructors and methods to create and perform operation on a thread. Thread class extends object class and implements runnable interface.
Commonly used constrictors of thread class:-
a)    Thread()
b)   Thread(string name)
c)    Thread(runnable r, string name)
d)   Thread(runnable r)

Commonly used methods of thread class:-
·       Public void run():-It is used to perform action for a thread.
·       Public void start():-Starts the execution of the thread .jvm calls the run()method on the thread.
·       Public void sleep(long mili second):-Cause the currently executing thread to sleep (temporarily case execution) for the specified number of milliseconds.
·       Public void join():-Waits for a thread to die.
·       Public void join(long millisecond):-Wait for a thread to die the specified milliseconds.
·       Public int get priority():-Returns the priority of the thread.
·       Public int setpriority()int:-Priority changes the priority of thread.
·       Public string get name:-Returns the name of the thread.
·       Public void setname(string name):-change the name of the thread.
·       Public Thread current thread():-Returns the reference of currently executing thread.
·       Public int getId():-Returns the id of the thread.
·       Public thread state get state():-Return the state of the thread.
·       Public Boolean is alive():-Tests if the thread is alive.
·       Public void yield():- Causes the currently executing thread object to temporally pause and allow other threads to execute.
·       Public void suspend():-It is used to suspend thread (deprecated).
·       Public void resume():-It is used to resume the suspend thread(deprecated).
·       Public void stop():-It is used to stop the thread(deprecated).
Example:-
class A extends Thread
{
public void run()
{
System.out.println("Thread is running");
}
public static void main(String args[])
{
multi m=new multi();
m.start();
}
}
Output
Thread is running

Example:-
class multi implements raunnable
{
public void run()
{
System.out.println("Thread is running");
}
public static void main(String args[])
{
multi m=new multi();
Thread n=new thread(m);
n.start();
}
}
Output

Thread is running
Thread scheduler in java:-
·       Part of jvm.
·       Decide which thread should be run.
·       There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
·        Only one thread at a time can run in a single process.
·       The thread scheduler mainly use preemptive or time slicing scheduler to schedule the threads.
*Sleep()Method:-
Example:-
class TestSleepMethod1 extends Thread{ 
 public void run(){ 
  for(int i=1;i<5;i++){ 
    try{Thread.sleep(500);
    }
catch (InterruptedException e)
{System.out.println(e);} 
    System.out.println(i); 
  } 
 } 
 public static void main(String args[]){ 
  TestSleepMethod1 t1=new TestSleepMethod1(); 
  TestSleepMethod1 t2=new TestSleepMethod1(); 
  
  t1.start(); 
  t2.start(); 
 } 
Output
11 22 33 44
Example:-. import java.lang.*;

public class ThreadDemo implements Runnable {

   Thread t;

   public void run() {
   for (int i = 10; i < 13; i++) {

   System.out.println(Thread.currentThread().getName() + "  " + i);
   try {
   // thread to sleep for 1000 milliseconds
   Thread.sleep(1000);
   } catch (Exception e) {
   System.out.println(e);
   }
   }
   }

   public static void main(String[] args) throws Exception {
   Thread t = new Thread(new ThreadDemo());
   // this will call run() function
   t.start();

   Thread t2 = new Thread(new ThreadDemo());
   // this will call run() function
   t2.start();
   }
}
Output
*Getname()method,set name(),get Id() method:-
Example:-
class multi extends Thread
{
public void run()
{
System.out.println("running...");
}
public static void main (String args[])
{
multi M = new multi();
multi N = new multi();
System.out.println("name of m;"+M.getName());
System.out.println("name of n;"+N.getName());
System.out.println("id of m;"+M.getId());
M.start();
N.start();
M.setName("raja");
System.out.println("after changing name of m:"+M.getName());
}
}
Output
Name of m:thread 0
Name of n :thread 1
Id of m       :8
Running after changing name of m:raja running.

*The current thread()method:-It is returns a reference to the currently executing thread object.
Syntax:-
Public static thread current thread():-
Example:-
class A extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{
A m=new A();
A n=new A();
m.start();
n.start();
}
}
Output
Thread 0
Thread  1

 Example:-
class A extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{
A m=new A();
A n=new A();
m.start();
n.start();
}
}
Output
Thread 0
Thread  1

*Priority of thread(Thread priority):-
Each thread have a priority ,priority are represented by a number between 1 and 10.in most cases, thread scheduler schedule the threads according to their priority(known as preemptive scheduling).

:-Three constants define in Thread class:-
1-   Public static int min.PRIORITY.
2-   Public static int NORM.PRIORITY.
3-   Public static int MAX. PRIORITY.
Default priority of a thread in 5 (Nor-Priority).The value of min-priority is 1 and the max-priority is 10.
        
Example:-
class A extends Thread
{
public void run()
{
System.out.println("running thread is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
A m = new A();
A n = new A();
m.setPriority (Thread.MIN_PRIORITY);
n.setPriority (Thread.MAX_PRIORITY);
m.start();
n.start();
}
}
Output
          Running thread name is : thread running thread priority is 10
Running thread name is : thread-
Running thread priority is :-1
Note: - Jcohsole:-all file is check

Deamon thread in java:-
It is a service provider thread that provides service to the user thread.its life depends on mercy of user thread i.e. when all the user thread dies.jvm terminates this thread automatically. There are many java Deamon thread running automatically i.e.gc(garbage collection)Finalizer.

:-Points to remember for Deamon thread:-
It provides services to user thread for background support task. It has no roll in life then to serve user thread.
It is life depends on use thread.
It is a low priority thread.

Why JVM terminates the Deamon thread, if there is no user thread:-
The sole purpose of the Deamon theread is that it provides services to user thread background supports task. If there is no user thread ,why should jvm keep running this thread that why jvm terminates the Daemon thread ,if there is no user thread.
Method for java Deamon thread by thread class:-
The java.lang thread class provides two methods for java Deamon thread.

Method                                                               Description
Public void set Deamon(Boolean status)         it is used to mark the current thread as Deamone thread or user thread.
Public Boolean in Deamon()                            it is used to check that current is Deamon.





Example:-
public class DaemonThreadExample1 extends Thread{

   public void run(){ 
            if(Thread.currentThread().isDaemon()){
                System.out.println("Daemon thread executing"); 
            } 
            else{ 
                System.out.println("user(normal) thread executing"); 
          } 
   } 
   public static void main(String[] args){ 
           
           DaemonThreadExample1 t1=new DaemonThreadExample1();
           DaemonThreadExample1 t2=new DaemonThreadExample1();  
         DaemonThreadExample1 t3=new DaemonThreadExample1();
                              
           //Making user thread t1 to Daemon
        t1.setDaemon(true);
                       
        //starting both the threads
        t1.start();
        t2.start();
        t3.start();
   }
}
Output
Daemon thread work
User thread work
User thread work

Joining a thread:-
Sometime one thread need to know when another thread is ending.
In java isalive() and join()are two different method. To check whether a
Thread has finished it is execution.
The alive()method return true if the thread upon which it is called is still
Running otherwise it returns false.
Format:-
Final Boolean is alive()but join()method is used more commonly than is
Alive()method. This method waits until the thread on which it is called
Terminates.
Final void join() throws interrupted execution. final void join (long mili-
Second)throw interrupt exception.
Is alive() methods:-
Example:-
public class TestJoinMethod1 extends Thread
{
public void run()
{

try
{
Thread.sleep(500);
}
catch(Exception r1)
{
System.out.println(r1);
}
System.out.println("i");
}
public static void main(String args[])
{
TestJoinMethod1 t1 = new TestJoinMethod1();
TestJoinMethod1 t2 = new TestJoinMethod1();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output
R1
TRUE
TRUE
R1
R2
R2
Thread without join()method
Example:-
public class TestJoinMethod1 extends Thread
{
public void run()
{
System.out.println("r1");
try
{
Thread.sleep(500);
}
catch(Exception r1)
{

}
System.out.println("i");
}
public static void main(String args[])
{
TestJoinMethod1 t1 = new TestJoinMethod1();
TestJoinMethod1 t2 = new TestJoinMethod1();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output
R1
R1
R2
R2
Thread withjoin()method
Example:-
class TestJoinMethod1 extends Thread{ 
 public void run(){ 
  {
   try{ 
    Thread.sleep(500); 
   }catch(Exception r1){System.out.println(r1);} 
  System.out.println("r2"); 
  } 
 } 
public static void main(String args[]){ 
 TestJoinMethod1 t1=new TestJoinMethod1(); 
 TestJoinMethod1 t2=new TestJoinMethod1();   
 t1.start(); 
 try{ 
  t1.join(); 
 }catch(Exception r1){System.out.println(r1);} 
 
 t2.start();   
 } 

output
r1
r2
r1
r2
Synchronization :- At times when more than one method try to access a shared resorce we thread at a time.The process by which this is achived is called synchronized.
synchronization in java is the capacity of control the access of multiple thread to any shared resource.
why we use synchronization the synchronization mainly used.
1-    To prevent thread intereference.
2-    To prevent considancy problem.
Types of synchronization.
Process synchronization.
Thread synchronization.
1-    Thread synchronization:- There are two types of synchronization.
Mutual exclusive:-
It helps keep threads from interfering with one another while sharing data.this can be done by three ways is java.
Ø By synchronized method
Ø By synchronized lock
Ø By static synchronization
Lock in java:-
synchronization is built arround an internal entity known as lock or monitor.
every objects has an lock associated with it a thread that needs consistance access to an objects.Field has to acquire the objects lock before accessing them and then release the lock when it is done with them.

if we declare any method as synchronized it is knowns as synchronized method ,synchronized method is used to lock an objects for any shared reason.
Example of java synchronized method:-
class Table{ 
 
 synchronized static void printTable(int n){ 
   for(int i=1;i<=10;i++){ 
     System.out.println(n*i); 
     try{ 
       Thread.sleep(400)
     }catch(Exception e){} 
   } 
 } 
 
class MyThread1 extends Thread{ 
public void run(){ 
Table.printTable(1)
 
class MyThread2 extends Thread{ 
public void run(){ 
Table.printTable(10)
class MyThread3 extends Thread{ 
public void run(){ 
Table.printTable(100)
class MyThread4 extends Thread{ 
public void run(){ 
Table.printTable(1000)
public class TestSynchronization4
public static void main(String t[]){ 
MyThread1 t1=new MyThread1()
MyThread2 t2=new MyThread2()
MyThread3 t3=new MyThread3()
MyThread4 t4=new MyThread4()
t1.start(); 
t2.start(); 
t3.start(); 
t4.start(); 
Output

 
 Program of synchronized method by using
annonymouse class:-
Example:-
class Table
 synchronized void printTable(int n){//synchronized method 
   for(int i=1;i<=5;i++){ 
     System.out.println(n*i); 
     try{ 
      Thread.sleep(400)
     }catch(Exception e){System.out.println(e);} 
   } 
 
 } 
 
public class TestSynchronization3
public static void main(String args[]){ 
final Table obj = new Table();//only one object 
 
Thread t1=new Thread(){ 
public void run(){ 
obj.printTable(5)
}; 
Thread t2=new Thread(){ 
public void run(){ 
obj.printTable(100)
}; 
 
t1.start(); 
t2.start(); 
Output
5
10 15 20 25 100 200 300 400 500

Synchronized block:-
It can be used to perform synchronization on any specific resource of the method.
syntax to use synchronized block:-
synchronized (object reference expression)
{
............
............//body
}
Example of synchronized block:-
class Table{ 
 synchronized void printTable(int n){//synchronized method 
   for(int i=1;i<=5;i++)
     System.out.println(n*i); 
     try{ 
      Thread.sleep(400)
     }
catch(Exception e)
{
System.out.println(e);} 
   } 
 
 } 
 
class MyThread1 extends Thread{ 
Table t; 
MyThread1(Table t){ 
this.t=t; 
public void run(){ 
t.printTable(5)
 
class MyThread2 extends Thread{ 
Table t; 
MyThread2(Table t){ 
this.t=t; 
public void run(){ 
t.printTable(100)
 
public class TestSynchronization2
public static void main(String args[]){ 
Table obj = new Table();//only one object 
MyThread1 t1=new MyThread1(obj); 
MyThread2 t2=new MyThread2(obj); 
t1.start(); 
t2.start(); 
Output

5 10 15 20 25 100 200 300 400 500
Static synchronized:-static method as synchronized the lock will be on class not on object.
t1                object 1
t2
t3                object 2
t4
Example:-
class Table{ 
 
 synchronized static void printTable(int n){ 
   for(int i=1;i<=10;i++){ 
     System.out.println(n*i); 
     try{ 
       Thread.sleep(400)
     }catch(Exception e){} 
   } 
 } 
 
class MyThread1 extends Thread{ 
public void run(){ 
Table.printTable(1)
 
class MyThread2 extends Thread{ 
public void run(){ 
Table.printTable(10)
 
class MyThread3 extends Thread{ 
public void run(){ 
Table.printTable(100)
 
 
 
 
class MyThread4 extends Thread{ 
public void run(){ 
Table.printTable(1000)
 
public class TestSynchronization4
public static void main(String t[]){ 
MyThread1 t1=new MyThread1()
MyThread2 t2=new MyThread2()
MyThread3 t3=new MyThread3()
MyThread4 t4=new MyThread4()
t1.start(); 
t2.start(); 
t3.start(); 
t4.start(); 
output

Inter thread communication:-
Java provied benifit of avoiding thread poling using inter thread communicated.the wait(),notify(),notify all(),of object class.These methods are implemented as final in object.All three method can be called only from within the synchronization.

Wait():-
tells calling threading to give us monitor and go to sleep untill other enter the some monitor and call notify.

Notify():-
wakes us thread that called wait()on some objects.

Notify all():-
wakes up all the thread that called wait ()on some object.
It is a machinism in which a thread is paused running in it critical section and another thread allow to enter (or lock) inthe some critical section.
Different between sleep() and wait().
  

              Wait()                                                                        sleep()
Wait () method release the lock.      sleep() method does not release the lock.
It is the method of object class.        it is the method of thread class.
It is the non-static method.               It is the static method.
It is should be notify or notify all      after the specified amount of time sleep is
() methods.                                          Complete.


Example :-




Interrupting thread:-
If any thread is sleeping or waiting state calling the interrupt ()method on the thread, breaks out the sleeping or waiting state throwing interrupted exception.
If the thread is not in sleeping or waiting state calling the interrupt ()method perform normal behavior and does not interrupt thread but sets the interrupt flag to true.
The threads provided by thread class for interrupting a thread:-
·       Public void interrupt()
·       Public static Boolean interrupted()
·       Public Boolean is interrupted()
Example of interrupting a thread that stop working:-

class TestInterruptingThread1 extends Thread{ 
public void run(){ 
try{ 
Thread.sleep(1000); 
System.out.println("task"); 
}catch(InterruptedException e){ 
throw new RuntimeException("Thread interrupted..."+e); 
 
 
public static void main(String args[]){ 
TestInterruptingThread1 t1=new TestInterruptingThread1(); 
t1.start(); 
try{ 
t1.interrupt(); 
}catch(Exception e){System.out.println("Exception handled "+e);} 
 
Output
Exception in thread  0
Java.lang runtime exception : thread interrupted
Java.lang interrupted exception: sleep interrupt a.run(a.java7)
Example of interrupting a thread that does not stop working:-

class TestInterruptingThread2 extends Thread{ 
public void run(){ 
try{ 
Thread.sleep(1000); 
System.out.println("task"); 
}catch(InterruptedException e){ System.out.println("Exception handled "+e); 
System.out.println("thread is running..."); 
 
public static void main(String args[]){ 
TestInterruptingThread2 t1=new TestInterruptingThread2(); 
t1.start(); 
 
t1.interrupt(); 
 
}  
                               Output
Exception handled java.lang
Interrupt exception :sleep
Interrupt thread is running.

Example of interrupting thread that behaves normally:-

If thread is not sleeping or waiting state calling the interrupt flag to true that can be used to stop thread. the java programmer later.

class TestInterruptingThread3 extends Thread{ 
 
public void run(){ 
for(int i=1;i<=5;i++) 
System.out.println(i); 
 
public static void main(String args[]){ 
TestInterruptingThread3 t1=new TestInterruptingThread3(); 
t1.start(); 
 
t1.interrupt(); 
 
Output
                                        1 2 3 4 5

Java exception handling:-
Exception:-
·       It is a problem that arises during the execution of a program.
·       In java exception is an event disrupts the normal flow of the program. It is an object which is thrown at runtime.
·       An exception may occur for many different reason include the following.
·       A user has entered invalid data.
·       A fill that needs to be open can not be found.
·       A network connection has been lost in the middle of communication.
Exception hierarchy:-
                       
                                      Throw able(object)
                   Exception                                                  error 
i/o exception                                              virtual machine error
sql exception                                             assertion error
run time exception (arithmetic exception, null and number format)
all exception types are sub classes of class throw able class, which is at top exception class hierarchy.
Run time exception is a sub class of exception under this class are automatically defined for program

                             Types of exception
Checked exception:-
It is a user exception that is typically a user error or a problem that cannot be forescen.

Unchecked exception:-
It is a run time exception un checked exception are ignored of complement.
Example :- arithmetic exception ,array index out of bound.

Error:-
  It is irrecoverable. If stack overflow virtual machine out of memory error is not possible handle in code.

Class A
{
public static void main (string arg[])
{
Int a=0;
Int b=7/a;
}
}
Output
                   Java.lang. arithmetic exception :/by zero
At uncaught exception. Main

Exception handling mechanism:-
There are five key word used to handle exception.
·       try
·       catch
·       finaly
·       throw

·       throws 


Try and catch:
Try use to guard a block of code in which exception may occur this block is called guarded region.
Enclosed the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.

Syntax of try with catch block:-
Try
{…………..
…………..}
Catch (exception class object)
{……………..
……………..}
Syntax of try with finally block:-
Try
{……….……….}
Finally
{………….
………….}

Catch block :-
It is used to handle it must be used just offer the try block.

Problem without exception handling:-

Comments

Popular posts from this blog

BCA IST SEM FOC MCQ BATCH 2023-24

BBA 1ST SEM FOC NOTES