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

Del java day 1

Uploaded by

pragatiraichan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Del java day 1

Uploaded by

pragatiraichan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 116

Date 4/5/2023

java has 4 categories


1. core java
2. advanced java(JDBC)
3. frameworks
4. android application development

core java
section 1(basic programming)
1. java components(javac, jvm, jre)
2.installation of java
3.sample program, compilation, execution of the java program
4.variables and operators
5. control statements
6. function
7. array(only introduction)
8. string(only introduction)

section 2(object oriented programming language(OOPs))


1. class and object
2. blocks(search on google)
3. constructor
4. composition
5.inheritance
6. method overloading
7. method overriding
8. type casting
9. abstract class and abstract methods
10.java interface
11. abstraction
12. encapsulation
13. polymorphism
14. java bean classes
15. singleton class

section 3(java library)


1. members of object class
2. indepth of strings
3. Exception handling
4. indepth of arrays
5. collection framework
6. multi threaded programming

Topic 1
java components(javac, jvm, jre)
JDK(java development kit(javac+jre))

JRE-Java runtime environment

There are two types of java runtime environment


1. Private JRE(it runs on a single machine or on a single computer)
2. Public JRE(It runs on a server machine or on multiple devices)

Java is platform independent

NOTE: Java is platform independent and dependent on JRE

JAVA editions

1. J2SE(core java)-----java 2nd version Standard Edition--------standalone


application(notepad,VLC,Icon,Internet Explorer)

2. J2EE(advance java)-----java 2nd version Enterprice Edition----web application(which requires


internet)
3. J2ME(android application development) java 2nd version micro edition---mobile applications

JDK versions
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8(most recommended version of jdk)
.
.
.
1.19

Text editors
1. Notepad
2. Notepad ++
3. Edit Plus

IDE(integrated Development Environment)

1. Eclipse(most recommended)
2. Netbeans

Topic 2 .installation of java DONE

1.Variable name-----JAVA_HOME
Varibale value-----address of jdk

2.Variable name----JRE_HOME
Variable value-----address of jre

3.Varibale name-----path
Variable value-----address of bin folder under jdk

Stpes to be followed

 Go to this Pc
 Right click on the white screen
 Click on properties
 Click on advanced system setting
 Click on environment variables
 In system variable section
 Click on new and use first variable name and value as given
 And follow all the three varibales

Topic 3.sample program, compilation, execution of the java


program

Class ClassName//declaration of the class


{//class body started

Public static void main(String args[])//declaration of main method


{//main method body started

//Java statements;

}//main method body ended

}//class body ended

{
Body/contaxt/definition block
}

System.out.println(value);

This is a java statement which is used to print the value on the screen

Value types

1. Number
A. Int
Eg. 123,45
B. Float
Eg. 12.34
2. Char
Eg
‘a’,’5’,’*’

3. Boolean
Eg.
True/false
4. String
Eg.
“abc123”,”123abc”,”**@#)”

Eg 1. sample program(open notepad and write the same program)

Class Program1
{
Public static void main(String arg[])
{

System.out.println(“main method started”);


System.out.println(1234);
System.out.println(12.34);
System.out.println(‘j’);
System.out.println(“Java”);
System.out.println(true);

System.out.println(“main method ended”);


}
}

After writing this program


Save this program to desktop by name Program1.java

Go to command prompt typing cmd to the search box


1. Change the dorectory
Cd desktop
Desktop>

Compile the program

Desktop>javac Program1.java
Desktop>java Program1
Topic 4. Variables and operators

Variable?

Used to store the value

Declaration of varibale

Syntax

Data_type identifier;

Eg.

Int id;
 Data_type represents the type of value is to be
stored in the variable

 Identifier represents the variable name

Data types in Java language

1. Byte
2. Short
3. Int
4. Long

All the above data types represents integer values

5. Float
6. Double

5, 6 represents the floating point values

7. Char

Represents character value

8. Boolean
Represents boolean value

NOTE:
String is value type or a class in java but not a datatype

Variable initialization

Syntax

Variable_name =value;

Eg. Of variable initialization

Id=12;

Eg of variable declaration and initialization

Class Program2
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
//variable declaration
Int empId;
String Empname;
Double EmpSalary;
//varibale initialization

empId=1234;
EmpName=”ramesh”;
EmpSalary=25000.00;

//displaing all the values on the screen

System.out.println(empId);
System.out.println(EmpName);
System.out.println(EmpSalary);

System.out.println(“main method ended”);

}
}

OutPut
Print statement in Java

There are two types of print


statement in java

1.
System.out.println(‘j’);
System.out.println(‘k’);
System.out.println(‘l’);
Output
J
K
L
|(cursor will be here) in case of
Println

2. System.out.print(‘j’);
System.out.print(‘k’);
System.out.print(‘l’);

Output
Jkl_(cursor will beat next to the
character)

1. Assignment
Print

123Number
Number
Is
One two three

Systyem.out.println(“123Number”)
System.out.println(“Number”);
System.out.println(“is”);
System.out.print(“one”);
System.out.print(“Two”);
System.out.print(“three”);

3. Assignment
Print

Ramesh
Kumar
Sharma

Using single Print Statement

System.out.println(“Ramesh\
nKumar\nSharma”);

\n-----is used to break the line

4. Assignment
Print as

Ramesh Kumar Sharma


System.out.println(“Ramesh\
tKumar\tSharma”);

\t----for leaving one tab

1 tab=4 spaces

5. Assignment

Print as

I am a “software” engineer

System.out.println(“I am “software”engineer”);//error

Correct way is

System.out.println(“I am a \”software\” Engineer”);


Operators

+ (plus operator)

1. Addition
2. Concatnation

Eg.
1. 10+10=20( addition operator)
2. “abc”+”xyz”=abcxyz(Concatnation
operator)
3. 123+”pqr”=123pqr(concatnation)
4. 20+20+”number”=40Number(add
& concatnation)
5. “number”+20+20=number2020(c
oncatnation)
6. “number”+(20+20)=Number40(ca
ncatnation and addition)
Eg. Of plus(+) operator

System.out.println(10+10);//20
System.out.println(123+”abc”);//
123abc
System.out.println(“abc”+”pqr”);//
abcpqr
System.out.println(20+20+”Number
”);//40Number
System.out.println(“number”+20+2
0);//Number2020
System.out.println(“Number”+(20+
20));//Number40
Operators in Java
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Unary Operator
5. Bitwise operator(will be taught
later)

1. Arithmetic operator(+,-,*,/,%)

Eg.

Int a=10;
Int b=5;

System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//
0(remainder)

2&3
Relational and Logical operators

Note:
1. result of both the Relational and
Logical operator is Boolean true or
false.
2. Relational operator can work on
any type of value;
3. But logical operator works on
true or false values
Eg. Of relational
operator(<,>,<=,>=,==,!=)

Int a=10;
Int b=5;

System.out.println(a<b);//false
System.out.println(a>b);//true
System.out.println(a==b)//false
System.out.println(a<=b);//false
System.out.println(a>=b);//true
System.out.println(a!=b);//true

Logical
operators(AND(&&),OR(||),NOT(!))
Truth Table of AND Operator

Input && input Output


True && True = True
True && False=False
False && True=False
False && False=False

Note: in case of AND (&&) operator


we are getting True on if all the
values are true else false

Truth Table of Or(||) operartor


Input || input Output
True || True = True
True || False= True
False || True=True
False || False=False

NOTE: in case of Or operator we will


get true if either or all of the input
are true else false

We will get false if all the input are


false

Not(!)
Note : we will get opposite result to
the input

If input is true will we will get false


And if input is false we will get true.

OKay guys?

Eg. Of Logical Operator

Int a=5;
Int b=10;
Int c=5;

System.out.println(a==c &&
c==a);//True
System.out.println(a<b &&
c<b);//true
System.out.println(b>a &&
c<b);//True
System.out.println(a>b &&
b>c);//false
System.out.println(a==c
||c==a);//True
System.out.println(a<b ||
c<b);//true
System.out.println(b>a
||c<b);//True
System.out.println(a>b ||
b>c);//false

4. Unary operator
1. ++(increment (will increment the
value by 1))
2. --(decrement(will decrement the
value by 1))
Both comes in two types

1. Pre
2. Post

Like
1. pre inrement
2. Post increment

3. Pre decrement
4. Post decrement

Eg

Int x=0;
Int y=0;

System.out.println(x);//0
System.out.println(y);//0

X++;
++y;
System.out.println(x);//1
System.out.println(y);//1

X--;

--y;

System.out.println(x);//0
System.out.println(y);//0

NOTE:

It doesn’t matter if we are using the


operator in pre or post form
The result will be all alike
But if there is an expression than
the result will be changed and will
not be like previous examples

What is an expression?

An expression is a arithmetical
equation with more then one
operator

For example

Int x=0;
Int y=0;

Y=x++;//this is an expression
So here the result will be
completely changed

System.out.println(x);1
System.out.println(y);0

Eg. 2

Int x=0;
Int y=0;

Y=x++ + x + x++ + ++x;

System.out.println(x);//3
System.out.println(y);//5
Eg.3
Int x=0;
Int y=0;

X=x++;
X=x++;
X=x++;

System.out.println(x);//0

NOTE: if both the sides we have


same name variable then operation
will take place but increment and
decrement will be ignored
Eg. 4

Int x=0;
Int y=0;

X=++x;
X=++x;
X=++x;

System.out.println(x);//3

Control statements
There are two types of control
statements

1. Branching
2. Looping

Branching has two types


1. If
2. Switch
Looping has basically 3 types but we
will understand two of them

1. For (recommended to learn)


2. While(recommended to learn)
3. Do while loop

NOTE:there is an extra type of loop


in java that is Advanced Loop or
Enhanced loop or for each loop
Control statements

1. If

Syntax

If(condition)
{
// if body statements
}

NOTE: if body statements will be executed if the


condition is true.

2. If and else
Syntax

If(condition)
{
//if body statements
}
Else
{
//else body statements
}
NOTE: if the condition is true then if body statements
will be executed otherwise if the condition is false then
else body statements will be executed

Eg. Of if statement

Class ProgramName
{
Public static void main(String arg[])
{
System.out.println(“Main method started”);
Int x=5;

If(x>4)
{
System.out.println(“x is greater then 4”);
}

System.out.println(“Main method ended);


}
}

Output is
x is greater then 4

Eg of if and else
Class ProgramName
{
Public static void main(String arg[])
{
System.out.println(“Main method started”);
Int x=5;

If(x>7)
{
System.out.println(“x is greater then 7”);
}
Else
{
System.out.println(“x is smaller then 7”);
}

System.out.println(“Main method ended);


}
}

Output
x is smaller then 7

3. Else if Ladder(if multiple condition exists)

Eg. of else if ladder


Class ProgramName
{
Public static void main(String arg[])
{
System.out.println(“Main method started”);
Int x=7;

If(x>7)
{
System.out.println(“x is greater then 7”);
}
Else if(x==7)
{
System.out.println(“x equal to 7”);
}

Else
{
System.out.println(“x is smaller then 7”);
}

System.out.println(“Main method ended);


}
}

Output

X is equal to 7
4. Nested if(if inside if)

Syntax

If(condition1)-----outer if
{
//outer if body statements

If(condition2)------inner if
{
//inner if body statements
}
Else
{
//inner else body statements
}

}
Else
{
//outer else body statements
}

NOTE: if condition1 is true then Outer if Body


statements will be executed other wise if
condition1 is false then Outer else body
statements will be executed

If condition 2 is true then inner if body statements


will be executed else inner else body statements
will be executed.

Eg of nested if

Case: client has to withdraw money from bank


Condition is he can withdraw only if the pin code
number is correct and amount is less then account
balance

Variables required

1.accBal
2.Amt
3.Pin

Class ProgramName
{
Public static void main(String arg[])
{
System.out.println(“Main method started”);
double accBal=20000.00;
double amt=2000.00;
Int pin=1234;

If(pin==1234)
{
System.out.println(“pin is correct please enter the
amount”);

If(amt<accBal)
{
accBal=accBal-amt;
System.out.println(“withdrawal successful”);
}
Else
{
System.out.println(“insufficient balance”);
}

}
Else
{
System.out.println(“pin is incorrect”);
}

System.out.println(“Main method ended);


}
}
Switch Statement(if multiple conditions exists)

Syntax

Switch(expression)
{
Case 1:
//statement
Break;

Case 2:
//statement
Break;

Case n:
//statement
Break;

Deafult:
statement
}

Eg. Of switch statement


Class ClassName
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
Char Grade=’E’;

Switch(Grade)
{
Case ‘A’:
System.out.println(“First division”);
Break;

Case ‘B’:
Systement.out.println(“second division”);
Break;

Case ‘C’:
System.out.println(“third division”);
Break;

Case ‘D’
System.out.println(“you are failed”);
Break;

Case ‘E’:
System.out.println(“Get lost”);
Break;
Default:
System.out.println(“case mismatched”);

System.out.println(“main method ended”);


}
}

Looping

What is looping?

Answer: repeating the same task again and again


till the condition is true

Types of loops

1. For loop
2. While loop
3. Do while loop(do it yourself)
4. Advanced loop will be taught in the collection
framework topic

1. for loop syntax

For(initialization; condition;inc/dec)
{
//for loop body statements
}

Process of for loop

Eg. Of for loop

Print
hello java
5 times

Class ClassName
{
Public static void main(String arg[])
{

For(int I=0;I<5;I++)
{
System.out.println(“hello java”);
}

}
}
Output

Hello java
Hello java
Hello java
Hello java
Hello java

2. Assignment
Print as
12345
For(int I=1;I<=5;I++)
{
System.out.print(i+” ”);
}
3. Assignment
Print as
1
2
3
4
5
For(int I=1;I<=5;I++)
{
System.out.println(i);
}

4. Assignment
Print as
*****

For(int I=0;I<5;I++)
{
System.out.print(“*”);
}

5. Assigment
Print as
*
*
*
*
*

For(int I=0;I<5;I++)
{
System.out.println(“*”);
}

6. Assignment

Print as
*****
*****
*****
*****
*****

Class ClassName
{
Public static void main(String arg[])
{
For(int I=0;I<5;I++)
{
For(int j=0;j<5;j++)
{
System.out.print(“*”);
}
System.out.println()
}
}
}

7. Assignment
Print as
*****
* *
* *
* *
*****

Function

What is Function in java?


Answer: A set of java statements which are used to perform
some specific task is called as function/method

Types of functions
1. Built in functions(provided by the java language)
2. User defined functions(created by the programmer)

Part of function
There are two parts of functions
1. Declaration
2. Definition
Syntax of a function in java
<access specifier><modifier><return type>FunctionName(Arguments)//declaration
part
{

//definition of the function

Return parameter/output parameter;


}

NOTE: in the above syntax access specifier and modifier are


not mandatory also the arguments

But return type and functionName is mandatory

Okay?

For example

Create a function to calculate the area of Circle


Pi*r*r

Input parameters---------1(int)

Output parametrs---------1(float)

Float AOfcircle(int r)
{
Float pi=3.14f;

Float Area=pi*r*r;

System.out.println(“area of circle is”+Area);

Return Area;

Assignment(home)

1. Write a function to convert c to f.


2. Write a function to calculate the angle of a time (1:50) in an
analog watch
.

Eg. Of function

Class className
{
Public static void main(String args[])//main method
{
Display();//calling of function Hello
System.out.println(“we can call function any number of
times”);
Display();//calling of function Hello
}
Static void display()//function declaration(user defined
method)
{
System.out.println(“Hello”);//function definition
}
}

 Here in the above example there is a main method and one


user defined method in the class

 Where main method is a caller method which is calling the


display method

 And display method is a called method which is called in


the main method body.

Recursion

When a function calls itself is called as recursion function


NOTE: if the function is calling itself then the stack of JVM will
be overflow and it will generate stack overflow error

So if we re using recursion we must provide some conditions to


stop the function call .

NOTE: recursion are the best when based on condition and also
faster then normal function.

Example of Recursion(factorial example)

Class classname
{
Stactic Int fact(int n)
{
If(n==0)

Return 1;

Else
Return (n*fact(n-1));

Public static void main(String args[])


{
Int I, f=1;

Int num=5;

F=fact(num);

System.out.println(“factorial of the number is”+f);

}
}

array(only introduction)

What is an array
1. Array is a collection of similar
data
2. we have to declare the size of an
array before using it
3. It will store elements in an index
manner
4. The index ranges from 0 to size -1

There are two types of array

1. 1D array
2. 2D array

Declaration of the array

Syntax

Int arrayName[];//declared the


array
arrayName=new
int[size];//allocated the memory

NOTE: we can do declaration and


allocation of the memory of array in
the same line

Int arrayName[]=new int[5];

Initialization of array

arrayName[0]=10;
arrayName[1]=20;
arrayName[2]=30;

arrayName[3]=40;

arrayName[4]=50;
System.out.println(arrayName.lengt
h);//5

Example of array

Class ClassName
{
Public static void main(String)
{
//declaration of array
Int a[];
A=new int[5];

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

A[2]=30;

A[3]=40;
A[4]=50;

//print the forth element of the


array
System.out.println(a[3]);
//print the length of the array
System.out.println(a.length);//5

//print all the elements of the array


//using loop
For(int I=0;I<a.length;I++)
{
System.out.println(a[i]);
}
}
}

NOTE:Array has a property name length that holds the size of


an array and can be used as arrayname.length.

NOTE: we can not initialize the values after declaration, it can


be possible with declaration only.

Reading the input from the user

Step1: import java.util.Scanner;


Step2: Scanner sc1=new Scanner(System.in);
Step3: int n1=sc1.nextInt();------>used to read the integer value
from the user.
double d1=sc1.nextDouble();----->used to read the double value
from the user
Float f1=sc1.nextFloat();------->used to read the float value from
the user.

String s1=sc1.next();-------->used to read the String value from


the keyboard/user
String s2=sc1.nextLine();------->used to read multiple lines of
strings from the user/keyboard;
Import java.util.Scanner;
Class ClassName
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
Scanner sc1=new Scanner(System.in);
Int n1;
double d1;
Float f1;

System.out.println(“enter a integer number”);


n1=sc1.nextInt();

System.out.println(“enter a double value”);


d1=sc1.nextDouble();

System.out.println(“Enter a float value”);


F1=sc1.nextFloat();

System.out.println(“main method ended”);


}
}

Eg.

import java.util.Scanner;
class Input
{
public static void main(String arg[])
{
System.out.println("main method started");
Scanner sc1=new Scanner(System.in);
int age;
System.out.println("enter the age");
age=sc1.nextInt();

if(age>=18)
{
System.out.println("you can vote");
}
else
{
System.out.println("you cant vote");
}
System.out.println("main method ended");
}
}

Local Variable

Eg.

{
Int x=10;
System.out.println(x);//10
}
{
System.out.println(x);//error
}
Eg.

{
Int y=30;

{
Int x=20;
System.out.println(x);//20
System.out.println(y);//30
Y=40;
}
System.out.println(y);//40

SECTION 2(Object oriented Programming)

NOTE: Variables and Methods Is the Most important part of the OOPs

Java Class Definition body


Eg.

Class Demo1//class Declaration


{
Static int x=12;//static data member
Int y=42;//instance data member

Static void m1()//method declaration-----this is a static member method


{
-----
-----

}
Int m2()//instance member method
{
------
------

In java, class Definition is used to declare variables and methods

The variables declared in the class body are known as Member variable, it is also called as
fields/attributes and data members of the class

The functions defined in the class body is known as member functions


The member functions are defined to perform some operations on the member variables

Anything defined in the class body is know as member of the class

The members of the class can be of two types


1. Static
2. Instance(non-static)

Static members

 Static members of the class are declared by using static keyword

 Where as instance members are declared without using static keyword

NOTE: in java language file we can have any number of classes or class definition blocks ,while saving
the source file we can save with any class name after compilation the compiler generated
separate .class files for each and every class definition block

The JVM can execute one class at at a time provided the class must have the main method definition
and if not then JVM throws run time error

Eg.

Class Demo1
{
Int x=12;
Void m1()
{
System.out.println(“m1()”);
}

}
Class Demo2
{
Int y=12;
Void m2()
{
System.out.println(“m2()”);
}
}
Class Demo3
{
Int z=12;
Void m3()
{
System.out.println(“m3()”);
}
Public static void main(String arg[])
{
System.out.println(“Running Demo3 class”);
}
}

.(dot )operator

Members of the class can be accessed from any other classes either in the same source file or in the
different source file using . (dot) operator depending upon the access specifiers the members of the
class can be accessed from other classes.

Java provides 4 access specifiers


1. Private
2. Package level(default)
3. Protected
4. Public

V.Imp

To access the members of the class we must know the type of the member
(static or instance member)

Static members are accessed differently and instance members are accessed differently

1. Accessing static members


Syntax

className.staticMemberName

Eg.

Class Demo1
{
Static int x=12;

Static void m1()


{
System.out.println(“running static methods”);
}
}

Class MainClasss
{
Public static void main(String arg[])
{
System.out.println(“Main method started”);
System.out.println(Demo1.x);
Demo1.m1();
System.out.println(“main method ended”);
}
}

2. Accessing Non-static(instance members) members of the class


To access the instance members of the class we need to follow some steps

Step1: create an object/instance


Step2: create an object using new keyword or operator

Syntax

New ClassName();

Here
New is the keyword
And
className() is the contructor

Eg.

New Demo();//created a object of Demo class

New Sample();//created an object of sample class

Eg.
Class Demo
{
Int x=10;//instance data members

Void disp()//instance member method


{
System.out.println(“running disp() method”);
}
}

New Demo();//instance of Demo class


New Demo();//instance of Demo class
New Demo();//instance of Demo class

Above there are three instances of the demo class


Reference variable
1. A reference variable can be of
A. Class type
B. Interface type
C. Enumeration type
2. Reference variables are used to access the instance members of the class
3. For a reference variable we can either assign the null value or an object

Syntax

ClassName referenceVaribaleName;

Demo d1;//reference variable of Demo class


Sample s1;//reference variable of Sample class

Demo d2;//reference variable of Demo class


Demo d3;//reference variable of Demo class

Using the reference variable name we can access only the instance members of the class using the
below syntax

refereceVariable.instanceMember name;

Eg.
Class Demo1
{
Int x=10;//instance data member
Static int y=20;//static data member

Void disp()//instance member method


{
System.out.println(“Instance method ”);
}

Static void print()//static member method


{
System.out.println(“Static method”);
}
}

Class MainClass
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
System.out.println(“accessing static members of the class”);
System.out.println(Demo1.y);
Demo1.print();

System.out.println(“accessing instance members”);


Demo1 d1;//reference variable of Demo1 Class

D1=new Demo1();//creating an object of Demo1 class

System.out.println(d1.x);
D1.disp();

System.out.println(“main method ended”);


}
}
See the below scenario

int x;//declaration of a variable of datatype int


X=10;//initialization

We can comnbined both the declaration and initialization as together in a single line
Such as below

Int x=10;

Can we do like this?

Ans is Yes

Same as variable declaration and initiliazation we can do with reference variable declaration and point
objects

Eg.

Demo d1;//declaration of the reference variable

d1=new Demo();//assigning the object

Demo d1=new Demo();

Demo d1=new Demo();


Demo d2=new Demo();
Demo d3=new Demo();
Object

Eg

Class Pen
{
String color;
String name;
double price;

Void write()
{
System.out.println(“Pen writes”);
}
}

Pen p1=new Pen();


P1.color=”Black”;
P1.name=”cello”;
P1.price=25.00;
Pen p2=new Pen();

P2.color=”red”;
P2.name=”reynolds”;
P2.price=20.00;

JVM MEMORY
Or
Memory utilization in JVM

1. Java Heap Memory----> used to store instance members or non-static members


Memory utilization is random

2. Class area/Static pool area----> used to store static members of the class
Static members of the class are created in a pool
Memory allocation is random
3. Method Area---->used to store the method definition
Memory allocation is random
4. Stack area---->used for execution
Follows LIFO
Stores local variables

Loading
Initialization
Execution

Eg.

Class MainClass
{
Public static void main(String arg[])
{
System.out.println(“main method started);
Int x=10;//local variable not instance variable thus it will be stored in stack area
System.out.println(x);
System.out.println(“main method ended”);
}
}
Class Demo
{
Int x=10;

Static int y=30;

Void m1()
{
System.out.println(“running m1() method”);
}

Static Void m2()


{
System.out.println(“running m2() method”);
}

Class MainClass
{
Public static void main(String args[])
{
System.out.println(“main method started”);
System.out.println(Demo.y);
Demo.m2();

Demo d1=new Demo();


System.out.println(d1.x);
d1.m1();

System.out.println(“main method ended”);

}
}

Task

Perform a memory management of the above


program
Constructor
Syntax
<Access specifier> constructor_Name(args)// declaration of the declaration
{

//code to do initialization

Constructor name==className

Okay?

NOTE: No modifiers are required (X)


NOTE: no return type

Types of constructors

1. Compiler defined constructor(provided default initialization and the states of the object)
 No-argument ed constructor
 Default constructor
2. User defined constructor
 No- argument ed constructor
 Parameterized constructor

Eg. Default constructor(Compiler defined constructor)

Class Student
{

Int id;
String name;

Void display()//instance method


{
System.out.println(“student id is=”+id);
System.out.println(“student name=”+name);
}
}

Class MainClass
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
Student s1=new Student();

S1.display();

System.out.println(“main method ended”);


}
}

OUTPUT
Student id is=0
Student name is=null

Eg. Of user defined no-argumented constructor

Class Student
{
Int id;

String name;

Student()
{
Id=1234;
Name=”Ramesh”;
}

Void display()
{
System.out.println(“student id is=”+id);
System.out.println(“student name is=”+name);
}
}

Class mainClass
{
Public static void main(String args[])
{
System.out.println(“main method started”);
Student s1=new Student();
S1.display();
System.out.println(“main method ended”);
}
}

Output
Student id is=1234
Student name is=Ramesh

Eg. User defined parameterized constructor

Class Student
{
Int id;

String name;

Student(int arg1,String arg2)


{
Id=arg1
Name=arg2;
}

Void display()
{
System.out.println(“student id is=”+id);
System.out.println(“student name is=”+name);
}
}

Class mainClass
{
Public static void main(String args[])
{
System.out.println(“main method started”);
Student s1=new Student(1234,”Ramesh”);
S1.display();
System.out.println(“main method ended”);
}
}

Output
Student id is=1234
Student name is=Ramesh
Constructor overloading(same constructor is
written more then one time in same class
body with different arguments)

Eg. Of constructor overloading

Class Student
{
Int id;
String name;

Student()//zero argumented user defined constructor


{
Id=1000;
Name=”ramesh”;
}

Student(int arg1)//user defined argumented constructor with 1 int


argument
{
Id=arg1;
}

Student(int arg1, String arg2)//user defined argumented constructor


with 2 (int and String) arguments

{
Id=arg1;
Name=arg2;
}

Void display()
{
System.out.println(“student id is=”+id);
System.out.println(“student name is=”+name);
}
}
Class mainClass
{
Public static void main(String arg[])
{
System.out.println(“main method started”);
Student s1=new Student();//zero argumented user defined constructor
S1.display();

Student s2=new Student(10);//user defined argumented constructor


with 1 int argument

S2.display();

Student s3=new Student(11,”ramesh”);//user defined argumented


constructor with 2 (int and String) arguments
S3.display();

System.out.println(“main method ended”);


}
}

OUTPUT

Main method started


Student id is=1000
Student name is=Ramesh

Student id is=10
Student name is=Null
Student id is=11
Student name is=Ramesh

Main method ended

This Keyword

 Java language provide the this key word which actually holds the address of the current object.
 The reference of the object is called as current object.
 This keyword should be used in a non-static block or instance block
 This keywod is used to differentiate the instance variable from the local variable
When the names are same

Eg.

Class Demo
{
Int x=10;//instance variable

Void display()
{
Int x=20;//loacl variable
System.out.println(x);//20
System.out.println(this.x);//20
}
}

Constructor chaining
A constuctor can call another constructor of the class in the same class body using this() calling
statement

 Using this() calling statement we can call no-argument ed constructor OR parameterized


constructor

Eg.

This();
This(25);
This(2.5);
NOTE: v.v.v.v.v.v.v IMP

 Constructor calling statement or this() calling statement must be the first statement of the
constructor body

 Only one constructor calling statement or this() calling statement is allowed.


 Recursive constructor call is not allowed

Eg.

Class Demo
{

Int x;
Double y;

Demo(int arg1)
{
X=arg1;
}

Demo(int arg1,double arg2)


{
this(arg1);///constructor calling statement
Y=arg2;

Void display()
{
System.out.println(x);
System.out.println(y);
}
}

Class MainClass
{
Public static void main(String arg[])
{
System.out.println(“MMS”);
Demo d1=new Demo(10);
D1.display();
Demo d2=new Demo(20,2.3);

D2.display();
System.out.println(“MME”);

}
}

OUTPUT

MMS
10
0.0

20
2.3
MME

Relationships in java
1. Composition(has-a)
2. Inheritance (is-a)

1. Composition(has-a)
AN object is made of with the help of another object

Eg. Of has-a relationship

1. Mobile has-a battery


2. Account has-a balance
3. Department has-a student

Class X//you can consider this class as a battery class(contained


class)
{
Int x=10;//instance variable
Void disp()
{
System.out.println(“running disp() method of X class(instance
method)”);
}

Class Y//consider class as a mobile phone class(container class)


{

X x1=new X();

Double y=2.5;//instance variable

Void show()
{
System.out.println(“running show() method of Y class(instance
method)”);

NOTE: members of the class can be of two type


1. Static
2. Instance

Class Mainclass
{
Public static void main(String arg[])
{
Y y1=new Y();

System.out.println(y1.x1.x);
Y1.x1.disp();

System.out.println(y1.y);

y1.show();

}
}

Eg. 2

Class X//you can consider this class as a battery class(contained


class)
{
Int x=10;//instance variable

Void disp()
{
System.out.println(“running disp() method of X class(instance
method)”);
}
}

Class Y//consider class as a mobile phone class(container class)


{

Static X x1=new X();

Double y=2.5;//instance variable

Void show()
{
System.out.println(“running show() method of Y class(instance
method)”);

Class Mainclass
{
Public static void main(String arg[])
{

System.out.println(Y.x1.x);
Y. x1.disp();//this is similar to System.out.println();

}
}
Inheritance(is-a
relationship)
An object is having the properties of another object

For example: a smart phone is-a Type of phone


Engineer is-a type of Employee

Keypad phone(make calls , send sms)

Smartphone(make calls , send sms)

How can we extend the properties of another object ?

Using extends key word

The class which extends the properties from is called a sub class/child class/ derived
class
And the class from which the properties are extended is called as super class /parent
class/base class

Types of inheritance

There are 5 types of inheritance

1. Single inheritance
2. Multi-level inheritance
3. Multiple inheritance
4. Hierarchical
5. Hybrid inheritance(combination of two types of inheritance)
Single inheritance(there is only one super class and one sub class)

Class Demo
{
Int x=10;//instance type
Void disp()//instance type
{
System.out.println(“method of Demo class”);
}
}

Class Sample extends Demo


{

Double y=2.5;//instance type

Void show().//instance type


{
System.out.println(“method of Sample class”);
}
}

Class mainClass
{
Public static void main(String args[])
{
Demo d1=new Demo();

System.out.println(d1.x);
D1.disp();

Sample s1=new Sample();


System.out.println(s1.y);

S1. show();

System.out.println(s1.x);
s1.disp();

}
}
Class Demo//super class
{
Int x=10;//instance type
Void disp()//instance type
{
System.out.println(“method of Demo class”);
}
}

Class Sample extends Demo//sample is the sub class of Demo class and Super class
of Run Class

Double y=2.5;//instance type

Void show().//instance type


{
System.out.println(“method of Sample class”);
}
}

Class Run extends Sample //sub class of Sample class


{
char z=’a’;

Void view()
{
System.out.println(“method of Run class”);
}
}

Class mainClass
{
Public static void main(String args[])
{
Demo d1=new Demo();

System.out.println(d1.x);
D1.disp();
Sample s1=new Sample();
System.out.println(s1.y);

S1. show();

System.out.println(s1.x);
s1.disp();

Runb r1=new Run();


System.out.println(r1.x);
System.out.println(r1.y);
System.out.println(r1.z);
r1.disp();
r1.show();
r1.view();

}
}

Multiple Inheritance( java doesn’t support multiple inheritance directly);

WHY?

Answer-pending

Hierarchical Inheritance(one class can have multiple children)

Class Demo//(parent class)


{
Int x=10;
Void disp()
{
System.out.println(“method of Demo class”);
}
}

Class Sample extends Demo//sample is the child class of Demo


{
Double y=2.5;

Void show()
{
System.out.println(“method of sample class”);

}
}

Class Run extends Demo //run class is the child class of Demo class
{
Char z=’a’;

Void view()
{
System.out.println(“method of Run class”);
}
}

Class MainClass
{
Public static void main(String args[])
{
Demo d1=new Demo()
System.out.println(d1.x);
D1.disp();

Sample s1=new Sample()


System.out.println(s1.x);
S1.disp();

System.out.println(s1.y);
S1.show();

//Can we access the Run class properties using S1 reference variable?

//Answer is no

Run r1=new Run();

System.out.println(r1.x);
R1.disp();

System.out.println(r1.z);
R1.view();
// but we cant access Sample class properties using r1 reference variable

}
}

Hybrid inheritance (combination of two)

Here I am going to combined multilevel and hierarchical inheritance

Class Demo//(parent class)


{
Int x=10;
Void disp()
{
System.out.println(“method of Demo class”);
}
}

Class Sample extends Demo//sample is the child class of Demo


{
Double y=2.5;

Void show()
{
System.out.println(“method of sample class”);

}
}

Class Run extends Demo //run class is the child class of Demo class
{
Char z=’a’;

Void view()
{
System.out.println(“method of Run class”);
}
}
Class Test extends Sample
{
Int b=20;

Void print()
{
System.out.println(“method of Test class”)
}
}Class MainClass
{
Public static void main(String args[])
{
Demo d1=new Demo()
System.out.println(d1.x);
D1.disp();

Sample s1=new Sample()


System.out.println(s1.x);
S1.disp();

System.out.println(s1.y);
S1.show();

//Can we access the Run class properties using S1 reference variable?

//Answer is no

Run r1=new Run();

System.out.println(r1.x);
R1.disp();

System.out.println(r1.z);
R1.view();

// but we cant access Sample class properties using r1 reference variable

Test t1=new Test();

System.out.println(t1.x);

System.out.println(t1.y);
System.out.println(t1.b);

T1.disp();
T1.show();
T1.print();

//NOTE-But we cant access Run class properties using t1 reference variable;

}
}

Super keyword

Super keyword is used to access the super class member in the sub class when the
names are same

Eg.

Class Demo
{
Int x=10;//super class instance variable

}
Class Sample extend Demo
{
Int x=20;//sub class instance variable

Void display()
{
Int x=30;//local variable
System.out.println(x);//30
System.out.println(this.x);//20
System.out.println(super.x);//10

}
}
Super() calling statement

Super() calling statement is used to call the super class constructor in to the sub
class constructor body

RULE: there can be only one super() calling statement and that must be the first
statement of constructor body

Example

Class Demo
{
Int x;

Demo(int x)
{
This.x=x;
}

Class Sample extends Demo


{
Int y;

Sample(int x;int y)
{
Super(x);//this must be the first statement of the constructor body
This.y=y;
}
}

Why java doesn’t support multiple inheritance

The answer is
Method overloading
Having the same name methods but different in arguments and can be performed in the same class or
in super to sub class
Method overloading is bound to the method declaration part

Eg.
Class Demo
{
Void show()
{
System.out.println(“mehtod without argument”);
}
Void show(int x)
{
System.out.println(“mehtod with int argument”);
}

Void show(double)
{
System.out.println(“mehtod with double argument”);
}

Class MainClass
{
Public static void main(String args[])
{
Demo d1=new Demo();
D1.show();//mehtod without argument
D1.show(10);//mehtod with int argument
D1. show(2.5);//mehtod with double argument
}
}

Method overloading can be performed into super to sub classes also

Eg

Class Demo
{
Void show(int x)
{
System.out.println(“method with int argument of Demo class”);
}
}
Class Sample extends Demo
{
Void show(double y)
{
System.out.println(“method with double argument of sample class”);
}
}

Class mainClass
{
Public static void main(String arg[])
{
Sample s1=new Sample();
S1.show(10);//method with int argument of Demo class
S1.show(2.4);//method with double argument of Sample class
}
}

Merthod overriding(having the same name method in the sub class with same list of arguments and
same return type but different in definition) method overriding is bound to the definition

NOTE: there should be is-a relationship to perform method overriding and it can not be performed in
the same class

Class Demo
{
Void Show(int x)//declaration of the method
{
System.out.println(“method of Demo class”);
}
}
Class Sample extends Demo
{
Void Show(int x)//declaration of the method
{
System.out.println(“method of Sample class”);

}
NOTE while calling these methods it will always print the sub class method definition

Class Mainclass
{
Public static void main(String );
{
Sample s1=new Sample();
d1.show(10);//method of Sample class
}
}

Type casting
Info------------------------------------------------------>info

Cast/convert/change

One type of information is changed or casted to another type of information is called is type casting

Types of casting
1. Data type casting
2. Class type casting

1. Data type casting------------------converting one type of data type to anpother type of data is callled
as data type casting

2. Class type casting---------------- converting one class type into another class type is called class type
casting

Eg.1.

Int x=10;//type match

Here x is a variable of int type, and value in the variable is also int type;

Eg. 2.

Double y=2.5;// type match

Here y is a variable of double type, and value in the variable is also double type;

Eg.3.

Int x=(int)2.5;//type mismatch this is the example of narrowing


Here x is a variable of int type, and value in the variable is of double type;
Eg.4.

Double y=(double)10;//type mismatch


Here y is a variable of double type, and value in the variable is of int type;

Can be done like this

Double y=10;//type mismatch but wont give compile time error(widening)

NOTE: in case of type mismatch the compiler throws compile time error
Thats why we need to change the type of the data

Type of data type casting

1. Widening
2. Narrowing

Widening------------->converting a lower data type to higher data type is called as wideing and it can be
performed autometically.

Narrowing------------->converting a higher data type to lower data type is called as Narrowing and user
has to perform narrowing manually otherwise compiler will throw compile time error

NOTE:: the data type casting is not used in java

Class Type casting

To perform a class type casting there must be is-a


relationship or inheritance concept
Converting one class type into another class type is known as class type casting

Types
1. Upcasting
2. Downcasting

Upcasting
Converting sub class type into super class type is known as upcasting & this can be performed
automatically
Downcasting
Converting supar class type into sub class type is known as downcasting & this can’t be performed
automatically but user has to perform it manually otherwise JVM thorws ClassCastException

Example

Class Demo
{
Int x=10;

Void disp()
{
System.out.println(“method of Demo class”);
}
}

Class Sample extends Demo


{
Double y=2.5;

Void show()
{
System.out.println(“method of Sample class”);
}
}

Class MainClass
{
Public static void main(String args[])
{
Demo d1=new Demo();

System.out.println(d1.x);
D1.disp();

Demo d1=new Sample();//can be done automatically(upcasting )


Demo d1=(Demo)new Sample();//upcasting

Sample s1=(Sample)new Demo();//narrowing


}
}

abstract class and abstract methods


Concrete method
A method with the definition part is called as concret method

Abstract method

A method without definition is called as abstract method

Syntax of abstract method

<Access specifier><abstract keyword> returntype methodName();

Eg.
Abstract void m1();

Normal class

Eg.
Class ClassName
{
//Declare & initilize static/instance variable;
//Declare & define static/instance methods

//Write constructor

Abstract class

Abstract Class ClassName


{
//Declare & initilize static/instance variable;
//Declare & define static/instance methods

//Write constructor

//abstract method (not mandatory to write abstract method in the abstract class)

}
 NOTE: it is not mandatory to write an abstract method in the abstract class but if there is an
abstract method in the class then that class must be declared as abstract..

 We cant create an object of abstract class

 Also all the abstract methods must provide an implementation to the method or else the class
must be declared as abstract
Eg.

Abstract Class Demo


{
Int x=10;
Void m1()
{
System.out.println(“this is a normal concrete method”);
}

Abstract void m2();


}
Class Sample extends Demo
{
void m2()
{
System.out.println(“implementation of m2() method”);

}
}

Class mainClass
{
Public static void main(String args[])
{
Sample s1=new Sample();

S1.m2();//implementation of m2() method


}
}

java interface

It is a pure abstract body which helps us to achieve abstraction principal of Java

Declaration of interface

Interface InterfaceName
{

//Decalre static variable and that must declared as final

//Only abstract methods are allowed


//constructor is not allowed
}

Eg.

Interface Demo
{
Final static int x=10;

Abstract Void m1();

Abstract void m2();

Abstract void m3();

Public Abstract Class Sample implements Demo


{
Public Void m1()
{
System.out.println(“m1() method”);

Public Class Run extends Sample


{
Public Void m2()
{
System.out.println(“m2() method”);
}

Public Void m3()


{
System.out.println(“m3() method”);
}
}

NOTE: we cant create an object of neither Interface nor abstract classs

Class MainClass
{
Public static void main(String args[])
{
Run r1=new Run();
r1.m1();
R1.m2();
R1.m3();
System.out.println(Demo.x);
}
}

Understood?

Abstraction
Hiding the implementation/method definition and
providing the functionality to end user with the
help of interfaces is called as abstraction

It can be achieved with the help of interfaces

Interface is a medium or channel between two end


systems.

NOTE: all the real time applications are build using loose coupling(can be done throught the concept
of interfaces)

Okay?

Encapsulation
Protacting the data members of a class or interface

This is also known as binding the data members to the class body or interface body

Like

Int x=10;//it is not applicable in java X


Class Demo
{
--
--

Class Demo
{
Int x=10;

NOTE: if we want to access the class members outside the class body then we can go with java access
specifiers and can access the class members out side the class body

Okay

Java provides us 4 access specifiers

1. Private
2. Package
3. Protected
4. Public

1. Private:--------------variables, methods, inner class and constructor can be declared as private and
can be restricted into the same class where it is declared

Okay?

NOTE
Outer class and interface can never be declared as private

2. Package----------------------variables, methods, inner class and constructor can be declared as package


and can be restricted in the same package but not outside the package

NOTE a class can be declared as package level but it is not mandatory to put package access specifier
for the class because it is by default declared as package level

3. Protected------------- variables, methods, inner class and constructor can be declared as protected
and can be restricted into the same package and can be accessed outside the package while importing
then extending the classess
NOTE : outer class cant be declared as Protected

4. Public------------ variables, methods, inner class and constructor can be declared as public and can
be accessed anywhere in the package and out side the package

NOTE: and outer class and interface can be declared as public

By default a interface and its members are declared public

Okay

Polymorphism
A function or a program is behaving differently in its life cycle or phases

There are two types of polymorphism

1. Compile time/early binding/static binding


2. Runtime time./late binding/dynamic binding

1. Compile time polymorphism(it is built and caught at compile time)


Eg. Method overloading
Static methods

2. Runtime time polymorphism(this is caught at the runtime)


Eg. Method overriding
Instance methods

Java bean classes

Bean--------------------> information protected

Class declaration

 * class must be declared as public


 *all the data members(variables )must be declared as private
 * public constructor
 *public getters and setters methods to access the private data members

Singleton class
 we can create only one object of the the singleton class at a time
 Or the classs which doesn’t allow to create more then one object
 Constructor of the class is declared as private
Section 3
Java library----collection of classes and interfaces

Object class------it is a class in java.lang package and it is the root class of all the classes in the java
class hierarchy

Means all the classes must have a super class thart is Object class

Okay

For eg.

Class Demo
{
}
Class Sample extends Demo
{

For the sample class there is a super class(Demo)

What is the super class for Demo class?

Answer is Object class--------available in java.lang package (by default imported)

Members of Object class


There are nine methods of Object class
1. Public String toString ()
2. Public int hashCode()
3. Public boolean equals()

Are important methods

Eg.
Class Demo
{

toString () method provide us the fully qualified class name @ hexadecimal code

String class
 It is abailable in java.lang package
 By default this class is declared as final(we cant extend this class into sub classes)
 String class is immutable(means we cant change the value of the string object)
 We can create objects of string class in two ways(1. using new keyword, without using new
keyword)
 It has overloaded constructors
1. No argumented
2. String argumented
3. Char array argumented
String class has almost 16 methods

Eg.

Exception handling

an Exception is an event which may occur


during the program execution and may
terminate the normal execution of the
program.

Okay?

Exception Hierarchy
Keywords of Exception handling

1. try
2. Catch
3. Finally
4. Throw
5. Throws

Eg.
public class mainClass {

public static void main(String[] args)


{

int x=10;
int result=0;
try
{
result=x/2;//there is no
exception
}
catch(ArithmeticException arg)
{
System.out.println("cant divide
any number by zero");
}
System.out.println(result);
}
}

NOTE:
We can use multiple catch blocks but only one catch block can be used at a time

Finally block will always be executed if there is an exception or not

Throw keyword is used to throw an exception manually used in the method definition

Throws keyword is used to propagate a checked exception and is used with method declaration

Throwable----class(it has two methods )

1. Public string getMaggage()-----information about the exception


2. Public void printStackTrace()-----the stack details, reason of the exception, line of occurance

Eg.
package delPack;

public class mainClass {

public static void main(String[] args)


{

int x=10;
int result=0;
try
{
result=x/0;//there is no
exception
}
catch(ArithmeticException arg)
{
String msg=arg.getMessage();
System.out.println(msg);

arg.printStackTrace();
}
finally
{
System.out.println("I run
always");
}

System.out.println(result);
}
}

OUTPUT
Reasons of exceptions

Environment
Power is not there
Database
File not found

code
ArithmeticException
NumberFormat
ClassCastEcxception

Collection framework

Is a framework provided by java to work on data structures

Everything is created only we have to use it

Using the collection interface

Collection interface has three sub iunterfaces like


1. List-----duplicate, null, any type of object
2. Queue-----duplicate, not null, same type objects
3. Set-----no duplicate, null(only once), sorted order

Map is the separate interface -----no duplicate, not null, elements are sorted

List has three implementation classes


1. ArrayList(3 contructors)
2. LinkedList(one default constructors)
3. Vector(Legacy)out dated

Queue has two implementation classes

1. linkedList
2. PriorityQueue

Set Has three Implementation classes


1. HashSet
2. LinkedHashSet
3. TreeSet

Map has 3 implementtion classes(the only difference is map allows key, value pair data)

4. HashMap
5. LinkedHshMap
6. TreeMap

Steps to connect mysql database with java application

Requirements

1. Yop must have My sql Data base and you must remember the password
2. You must have JDK
3. And you may or might have eclipse
4. Must have mySQL connector to set up a jar file

To download mySQL connector

Follow the steps


Open the command prompt the follow the steps
In the lib folder paste the SQL connector jar file and in the src folder write the java code for the
connectivity

And then run the the java file using the below commands
Use the commands to compile an to run the code to the command prompt

For compilation

“javac-classpath\lib\mysql-connector-java-8.0.20.jar;.demo.java”.

For execution

“javac-classpath\lib\mysql-connector-java-8.0.20.jar;.demo”.

Create a database in the mysql database name dbname


Create a table inside database

We have to select all the records from the table using the command
Select * from tableName.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy