New 2
New 2
CORE JAVA
`````````
infosys
wipro
tcs
...
java:
`````
what is java?
->desktop application
->distributed application
both types
->sun microsystem
->jse-java standard edition(core java)
->desktop/standalone applications
acrobatic reader,
antivirus,
calculator,
mspaint
internet/distibuted applications
facebook.com
flipkart.com
gmail.com
etc..
internet based applications results are sharable across the globe &
standalone applications
android ->
programmers:
java program
scjp
ocjp
url: www.oracle.com
cmd:/>java -version
types of applications
1.development environment
2.runtime environment
dhaaps
to connect -> runtime environment
rk
->jvm
oracle
www.oracle.com
class <classname>
{
public static void main(String[] args)
{
System.out.pritln("welcome to java sessions");
}//closing main method
}//class closing
compiler
java compiler ?
java compiler is the system defined java program which is running in the
background.
C:\Program Files\Java\jdk1.8.0_221\bin
javac Test.java
java Demo
note:
while we are compiling the java program we should always gives filename
while we are executing/running the java program we should always
gives classname.
note: can we give both filename and class name are same?
yes
example:
``````````
class Demo
{
.java
filename.java
compile
execute
path:
`````
path is the location where java predefined tools are available.
C:\Program Files\Java\jdk-19\bin
1.temporarily
2.permanently
if you set the path only in user variable , it will be effected only
to that particular user itself.
javac <filename>.java
******
this intermediate code makes java a platform independent language.
*******
.c
.exe
windows
.class file generated based on the class name not based on the filename
jvm
cmd:/> e:
e:/>
27years far
but still java is maintaining it's popularity
1.simple
2.object oriented
3.portable
4.platform independent
5.secured
6.Robust
7.Interpreted
8.Architectural neutral
9.High performance
10.Multithreaded
11.Distributed
12.Dynamic
object oriented:
```````````````
xyz
programming language
->oopl
->inheritance
->polymorphism
->abstraction
->encapuslation
software /application
it is a combination of different objects that incorporate both data and behaviour.
Student
Robust:
````````
strong
java is strong
atm machine
account-> 5000
architectural neutral:
``````````````````````
int -> 4 bytes
portable:
``````````
portable = pi + an
distributed:
`````````````````
RMI
EJB
spring ,springboot,microservices
facebook.com
multithreaded:
````````````````
multiple threads
thread:
separate progam executing parallely.
we can write java programs that deal with many tasks at once
by defining multiple threads.
->main memory
->RAM
-high performance
->secured
inheritance
polymorphism
abstraction
encapuslation
-omg organization
note:
every java program should starts with by defining the class.
class:
``````
class is a collection of
-variables
-methods into a single unit.
note:
without main() we can compile the java program but we can't execute
the java program
since java execution / jvm internally calls the main() when you
execute the java program.
variables:
``````````
100 in some specified user defined name
inetrnally java will allocate some address (system defined address)
purpose of variable:
datatype:
3.we are not allowed to use varaible names as java reserved words.
5.blank spaces are not allowed while we are declaring the variables.
4 categories of datatypes
1. integer
2. characters
3.float category
4.boolean category
note:
`````
A primitive type is predefined by the language and is named by a reserved keyword.
note:
all the java reserved keywords must be always in lower case only.
note:
every datatype is maintaining two things
1.range
2.memory size
byte b = 100
-2^n-1 to (2^n-1) - 1
where n -> no.of bits occupied by the datatype
range of the byte datatype.
-2^7 to (2^7) -1
-128 to 127
is the range of the byte datatype.
byte b =128;
character category:
````````````````````
to store single character we have to use character category data.
note:
to store single character it is mandatory to store with in single quotes.
class Demo
{
System.out.println(stname);
1.inheritance
2.polymorphism
3.abstraction
4.encapuslation
to achieve above principles we are using two concepts in java
1. class
2. object
class:
``````
class is a collectio of variables and methods into a single unit.
that single unit is known as class.
every java program should starts with by defining the class only.
class <classname>
{
//vairables
//methods
java doesn't support non member variables and non member methods
variable:
class is
-variables
-methods
method:
``````
method is the place where we are writing the logic
to perform some operation based on the requirement.
note
if you want to define your own logic , define your own method.
syntax
```````
[accessmodifier] <returntype> <methodname>([if any parameters])
{
//logic
}
ex:
if a method is not returning any value to represent that we are using one return
type i.e void
int getAge()
{
return 23;
}
if a method is returning any value, using return keyword we are allowed to return
the value.
note:
return type and return value must be compatible with each other
sum(4,5);
String getStudentName()
{
return "rama";
}
->define the method which takes two string parameters and gives
concatination of the string?
getConcatination("rama","krishna");
ramakrishna
example:
`````````
class Student
{
//variable declaration
static int stid=100;
static String stname ="Rama";
//method definition
public static void display()
{
System.out.println(stid);
System.out.println(stname);
class Employee
{
static int empId =100;
static String empName="manikbasha";
//define the method
class is a collection of
-variables
-& methods into a single unit.
-> object
object:
``````
instance of a class is known as object.
instance:
````````
allocating suffficeint amount of memory space for the
properties of the class.
syntax:
class-
collection of
variables and methods into a single unit.
object
-instance of a class is known as object
-allocating sufficient amount of memeory space for the
properties of the class.
jvm
note:
using object, we can access the properties and as well as
we can update the values based on the requirement.
example:
``````````
class Product
{
int productId = 100;
String productName ="soap";
p.getProductDetails();
define Student class with stid, stname and update the values
with your own name using object?
we can create multiple objects for a single class, where each object is having
their own address.
example:
````````
class Product
{
int productId = 100;
String productName ="soap";
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
College
1000 students
note:
`````
example:
`````````
class Employee
{
//variables
int empId=100;
String empName="rama";
double empSalary=9878.87;
//method
public void getEmpDetails()
{
System.out.println("====================");
System.out.println("employee id is: " + empId);
System.out.println("employee name is : " + empName);
System.out.println("employee salary is: " + empSalary);
}
//main method
public static void main(String[] args)
{
System.out.println(obj1);
System.out.println(obj2);
}
}
is it possible or not?
//variables
int empId=100;
String empName="rama";
double empSalary=9878.87;
//method
public void getEmpDetails()
{
System.out.println("====================");
System.out.println("employee id is: " + empId);
System.out.println("employee name is : " + empName);
System.out.println("employee salary is: " + empSalary);
}
//main method
public static void main(String[] args)
{
obj1.empId=101;
obj1.empName="manik";
obj1.empSalary=8989.99;
}
}
note1:
``````
from static area, to access non-static properties using object name we can access
note2:
``````
from static area or non-static area, to access static properties using
below way we can access
note:
``````
whenever we create the object, memory locations will be created for
non-static or instance properties not for static properties.
q?
when should we declare any property as static property?
example:
````````
class Employee
{
//non-static variables
int empId=100;
String empName="rama";
double empSalary=9878.87;
//static property
static String companyName="infosys";
System.out.println("-------------------");
System.out.println("employee id : " + empId);
System.out.println("employee name: " + empName);
System.out.println("employee salary: " + empSalary);
System.out.println("employee company name: " + companyName);
//main method
public static void main(String[] args)
{
//static area
Employee obj = new Employee();
System.out.println("employee id: " + obj.empId);
System.out.println("employee name: " + obj.empName);
System.out.println("employee salary:" + obj.empSalary);
companyName="TCS";
obj.getEmployeeDetails();
}
}
introduce ide:
integrated development environment
myeclipse
netbeans
intellij
etc..
click on file
|
new
|
project
|
java project
|
project name: corejava
|
uncheck module-info.java
|
click on finish
|
class
|
name: Test1
|
click on finish
3.Auto completion- one of the best features , you don’t have to remember all.
4.Refactoring
//varaibles declaration
int stid;
String stname;
void setValues()
{
stid=100;
stname="Rama";
void display()
{
System.out.println("student id is : " + stid);
System.out.println("Student name is : " + stname);
}
obj.setValues();
obj.display();
}
}
constructor:
````````````
constructor is a special member method
purpose:
`````````
to initialize the object
object ->data
to initalize the data
note:
whenever we create the object corresponding constructor will be
invoked to intilzie the values.
example :
`````````
//varaibles declaration
int stid;
String stname;
/*public Student()
{
stid=0;
stname=null;
}*/
Student()
{
stid=100;
stname="Rama";
}
obj.display();
}
}
types of constructors:
`````````````````````````
->default constructor
->parameterized constructor
2.parameterized constructor:
//varaibles declaration
int stid;
String stname;
}
public void display()
{
System.out.println("Student id is : " + stid);
System.out.println("Student name is: " + stname);
}
obj.display();
}
}
note:
default constructor is always availble in only one form
but we can define multiple parameterized constructors
example:
````````
//parameterized constructor
public Student(int x)
{
System.out.println("iam single parameterized constructor");
}
this:
````
'this' is a java reserved keyword used for the following
two purposes.
purpose:
it is always pointing to current class object.
example:
``````````
int stid;
String stname;
//calling display()
obj.display();
}
}
constructor chaining:
example:
````````
public Student()
{
//call the parameterized constructor of the same class
this(100);
public Student(int x)
{
}
}
note:
cosntructor call must be the first executable statement inside a
constructor otherwise we will get compile time error.
note:
if we keep on calling the constructors we will get compile time error
saying that recursive constructor invocation is not possible.
public Student()
{
//call the double paramterized constructor
this(100,200);
System.out.println("iam default constructor");
}
public Student(int x)
{
this(100);
System.out.println("iam double parameterized constructor");
}
}
}
note:
if statement:
``````````````
this staement is used to evoluate a condition.
1.simple if statement
2.if-else statement
3.if-elseif ladder
4.nested if statement
1.simple if statement:
``````````````````````
syntax:
if(condition)
{
//statemetns
}
example:
````````
if(x+y>20) {
System.out.println("x+y is greater than 20");
}
}
}
2.if-else statement:
````````````````````
a block is a concept of in between { and }
if
{
syntax:
if(condition){
//statement1;//executes when condition is true
}
else{
statement2 ;//executes when condition is false.
}
example:
`````````
int x=10,y=20;
if(x+y<20) {
System.out.println("x+y is less than 20");
}
else
{
System.out.println("x+y is greater than 20");
}
}
}
if-else-if ladder:
`````````````````````
it contains
1 if block
1 else block
syntax:
if(condition1)
{
statement1;//executes when condition 1 is true
}
else if(condition2)
{
statement2;//executes when condition2 is true
}
else if(condition3)
{
statement3;//executes when conditio3 is true
}
else
{
statement4;//executes when all the condistions are false.
}
example:
`````````
String city="Agra";
if(city=="Chennaih") {
System.out.println("city is chenniah");
}
else if(city=="Hyderabad")
{
System.out.println("city is Hyderabad");
}
else if(city=="pune")
{
System.out.println("city is pune");
}
else
{
System.out.println(city);
}
}
}
nested if statement:
```````````````````
in nested if statement, the if staetment can contain a if
syntax:
if(condition1)
{
staetment1;//executes when condition1 is true
if(condition2)
{
statement2;//executes when condition2 is true
}
else
{
statement3;//executes when condition2 is false.
}
}
example:
`````````
int a=10,b=20;
if(a==10)
{
if(b!=20)
{
System.out.println("dhaaps");
}
else
{
System.out.println("ramakrishna");
}
}
}
}
switch statement:
````````````````
3.the case value must be unique, in case of duplicate value it will give you
compile time error.
syntax:
```````
switch(expression)
{
case value1:
//code to be executed
break;//optional
case value2:
//code to be executed
break;//optional
....
default:
//code to be executed if all case values are not matched
example:
````````
int number=40;
switch(number)
{
//case statements
case 10:System.out.println("10");
break;
case 20:System.out.println("20");
break;
case 30:System.out.println("30");
break;
default:System.out.println("not in 10,20 or 30");
}
}
}
loop statements:
`````````````````
Loops in Java is a feature used to execute a particular part of the program
repeatedly if a given condition evaluates to be true.
-for loop
-while loop
-do while loop
for loop:
`````````
purpose:
this for loop is used to iterate a part of the program several/multiple times.
2.condition
3.increment/decrement
4.statement
syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
example:
```````
//program for displaying first 10 numbers using for loop
public class Test1 {
}
}
example:
`````````
//program for displaying first 10 numbers using for loop
public class Test1 {
}
}
10
example:
``````````
//program for displaying first 10 numbers using for loop
public class Test1 {
for(int i=1;i<=10;i++) {
if(i%2==0)
{
System.out.println(i);
}
}
}
example:
````````
//program for displaying first 10 numbers using for loop
public class Test1 {
for(int i=1;i<=10;i++) {
if(i%2!=0)
{
System.out.println(i);
}
}
}
The inner for loop executes completely whenever outer for loop
executes.
once control comes from outerfor loop to inner for loop, it executes inner for loop
until the condition became false, once condition false
again it goes back to outerfor loop then comes to inner loop like this
flow is going on.
example:
````````
//program on nested for loop
public class Test2 {
// loop of i
}
}
/*output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3*/
output:
````````
*
* *
* * *
* * * *
* * * * *
example:
`````````
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
output:
````````
* * * * * *
* * * * *
* * * *
* * *
* *
*
this enhanced for loop introduced from java 1.5 version onwards.
purpose:
``````````
it provides an alternative approach to traverse the array or collection in java.
int a[]={100,200,300};
sysout(a[0]);
sysout(a[1]);
note:
if the array length is 'n'
maximum index is 'n-1'
because array index starts from 0 th location
for(datatype variable:actualvaraible)
{
int a[]={10,20,30,40,50};
for(int b:a)
{
System.out.println(b);
}
example:
`````````
class Test4
{
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]);
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
for(int b:a)
{
System.out.println(b);
}
}
}
answer:
```````
syntax:
labelname:
for(intialization;condition;increment/decrement)
{
//code to be executed
}
example:
`````````
//program on nested for loop
public class Test2 {
bb:
for (int j = 1; j <= 3; j++) {
if(i==2&&j==2) {
break aa;
}
System.out.println(i + " " +j);
}
}
}
}
/*output:
1 1
1 2
1 3
2 1
*/
syntax:
```````
while(condition)
{
//code to be executed;
increment/decrement ;
}
example:
````````
//initialization
int i=1;
//while loop
while(i<=10)
{
System.out.println(i);
i++;
}
}
//initialization
int i=10;
//while loop
while(i>=1)
{
System.out.println(i);
i--;
}
}
do while loop:
``````````````
do while loop is used to iterate a part of the program repeatedly,until the
specified condition is true.
if the number of iteration is not fixed and you must have to execute
the loop at least once, it is recommended to use a do-while loop.
syntax:
```````
do{
} while(condition);
example:
````````
int i=1;
do {
System.out.println(i);
i++;
} while (i>=10);
jump statements:
````````````````
Jump statements are one of the types of control statements in Java that directs the
flow of execution in a program.
break
continue
break statement:
````````````````
it is encountered inside a loop,
the loop is immediately terminated and the program control resumes at the next
statement following the loop.
-for loop,
-while loop
-do while loop
syntax:
jump-statement;
break;
example:
````````
example:
`````````
3 assignments:
continue statement:
````````````````````
it is used in loop control structure when you need to jump
to the next iteration of the loop immediately.
it can be used with all types of loops such as for,while and dowhile
note:
it continues the current flow of the program and skips the remaining
code at the specified condition .
for(int i=1;i<=10;i++)
{
if(i==5){
continue;
}
sysout(i)
}
1
2
3
4
6
7
8
9
10
syntax:
jump-statement;
continue;
example:
````````
`
public class Test8 {
}
}
assignment:
```````````
use continue statement in labelled for loop?
use continue statement in while loop?
use continue staetment in do while loop?
-manually
-automatically
it is done automatically.
example:
`````````
int x=7;
//automatically converts the integer type into long type
long y = x;
note:
in case of narrowing type casting, we might get a chance to lose the data in the
explicit conversion .
double->float->long->int->short->byte
if we do not perform casting then the compiler gives you compile time
error.
example:
``````
double d= 234.5656;
int i = (int)l;
}
}
oops principles:
````````````````
->inheritance
->polymoprhism
->abstraction
->encapsulation
inheritance:
```````````
inheritane is the process of taking the properties from one class
to another class
class
i have some logic is there
note:
whenever we applied the concept of inheritance, it is highly
recommended to create the object for child class not for parent class
if we create the object for parent class, memory locations will be created only for
parent class properties.
so that , with the parent class object we are allowed to access only
parent class properties
whenever we crete the object for child class, memory locations will
be created for both parent and child class properties.
so with this child class object, we are allowed to access
both parent and child class proeprties.
1.reusability
2.code redundancy will be decreased
3.performance of the application will be improved.
types of inheritances:
`````````````````````
in java, we have 5 types of inheritances
A
|
B
multilevel inheritance:
it contains
A
|
B
|
C
hierarchy:
`````````
class A
{
}
class B extends A
{
}
class C extends B
{
}
in one context, B class is acting as sub class or child class
multiple inheritance:
`````````````````````
A B C D ....
hierarchy:
```````````
class Z extends A,B,C,D,...
{
}
in java, through classes multiple inheritance is not possible
why?
class A{
sum()
}
class B {sum();}
hierarchical inheritance:
B C D E ....
hierarchy:
`````````
class A
{
}
class B extends A
{}
class C extends A{}
class D extends A{}
....
hybrid inheritance:
````````````````````
it is the combination of any two possible inheritance
types.
A
|
B
|
C D E
hierarchy:
``````````
class A{}
class B extends A{}
class C extends B{}
class D extends B{}
class E extends B{}
assignments:
do one one program on top of each and every
inheritance type.
note:
when you apply inheitance concept, it is
highly recommende to create the object for
child class.
A.java:
```````
//parent class cum business logic class
public class A {
public A()
{
System.out.println(this.hashCode());
}
public void sum(int x, int y)
{
System.out.println("sum is : " + (x+y));
}
B.java
````````
//child class cum business logic class cum executin logic class
public class B extends A {
public void sub(int x, int y)
{
System.out.println("substraction: " +(x-y));
}
obj.sum(2, 3);
obj.sub(5, 4);
}
note:
using extends keyword, we are allowed to extend from single class
to single class only not from more than 1 parent class,if we try for that, we will
get compile time error.
polymoprhism:
`````````````
defintion:
In computer science, it describes the concept that you can access objects of
different types through the same interface
1.method overloading
2.method overriding
method overloading:
```````````````````
method name is same
but signature is different
signature:
advantage:
This provides flexibility to programmers so that they can call the same method for
different types of data.
example:
`````````
}
public static void main(String[] args) {
Demo1 obj = new Demo1();
obj.sum(10,20);
obj.sum(2.3,3.4);
}
note:
to achieve the concept of method overloading one class is enough.
assignment:
-no.of parameters
-order of parameters
method overriding:
````````````````````
note:
to achieve the concept of method overriding minimum we require
two classes with parent-child relation.
note:
why should we go for this method overriding?
answer:
if i don't want to use existing logic or original logic which is available inside
parent class,
then i should go for method overriding because inside the child class
we will get a chance to override the exisitng logic
or
if i want my own logic then i can go for method overriding.
The @Override annotation denotes that the child class method overrides the base
class method.
If the annotated method does not actually override anything, the compiler issues a
warning.
A.java:
````````
//PARENT CLASS
public class A {
B.java:
```````
//child class
public class B extends A{
@Override
public void sum(int x, int y)
{
System.out.println("substraction: " +(x-y));
}
polymorphism
method overloading
method overriding
1.compiletime polymoprhism
example:
````````
//object declaration
Demo1 obj ;//available at compiletime
/*
* object referencing:
* the address of the memory location
* where the object is allocated) *
*/
obj= new Demo1();//available at runtime
obj.sum(10,20);
obj.sum(2.3,3.4);
2.runtime polymoprhism
->the polymoprhism can be decided at runtime based on the object type not based
on the reference varaible.
note:
whenever we call any method, if that method is not available inside
child class, automatically control will look for that method inside
parent class this is the behaviour.
note:
````
which class object we are creating, that class method will be executing is the
concept of runtime polymoprhism.
A.java:
```````
//PARENT CLASS
public class A {
B.java:
```````
//child class
public class B extends A{
@Override
public void sum(int x, int y)
{
System.out.println("substraction: " +(x-y));
}
//case:3
//child object type to parent object type conversion
//automatic conversion
//upcasting
//obj is of A type
A obj;//obj is available at compiletime
obj.sum(4, 3);
what is debugging:
`````````````````
Debugging is the process of finding and resolving defects
or problems with in a computer program that prevent correct
operation of computer software or a system.
It's a must have skill for any developer because it helps to find bugs that are not
visible during code reviews or that only happens when a specific condition occurs.
abstraction:
````````````
advantage:
using this we can achieve the concept of security
->abstract class
->interface
abstract class:
purpose:
`````````
Java Abstract class is used to provide common method implementation to all the
subclasses or to provide default implementation
Demo2.java:
`````````````
@Override
public void sum(int x, int y) {
System.out.println("sum is: " +(x+y));
Demo3.java:
```````````
//implementaion class of Demo1
public class Demo3 extends Demo1 {
@Override
public void sum(int x, int y) {
System.out.println("substraction is: " +(x-y));
obj.sum(3, 4);
note:
``````
when we inherit the abstract class, in the implemenation class we
have to implement all the abstract methods,if we didn't provide
atleast for one abstract method our implemenation class also
will become abstract class.
yes we can define and we can make it execute also by using super()
syntax.
super:
```````
super is oen of the java reserved keyword
int x=100;
//child class
//Demo2.java
//Demo3.java
//execution logic class
public class Demo3 {
obj.display();
}
}
//Demo2.java:
``````````````
super.display();
}
}
Demo3.java:
```````````
//execution logic class
public class Demo3 {
obj.display();
class A
{
public A()
{
}
}
class B extends A
{
public B()
{
}
note:
writing the super() is optional to call the parent class
default constructor.
Demo1.java:
```````````
//parent class
public class Demo1 {
//user defined default constructor
public Demo1()
{
Demo2.java:
````````````
public Demo2()
{
note:
for every constructor , java compiler will add super() as a first
statement.
Demo1.java:
````````````
//parent class
public class Demo1 {
public Demo1(int x)
{
System.out.println("parameterized constructor-Demo1");
}
Demo2.java:
```````````
Demo3.java:
```````````
//execution logic class
public class Demo3 {
}
interface:
``````````
interface is a collection of only abstract methods.
syntax:
interface <interfacename>
{
//abstract methods;
}
note:
by default interface methods are public abstract, we no need to use
these keywords explicitly.
Bank.java:
```````````
//method declaration
double getRateOfInterest();
Icici.java:
````````````
CityBank.java:
`````````````
@Override
public double getRateOfInterest() {
// TODO Auto-generated method stub
return 5.5;
}
Demo3.java:
``````````
//execution logic class
public class Demo3 {
//runtime polymorphism
Bank obj = new Icici();
System.out.println("icici rateof interest is : " +
obj.getRateOfInterest());
note:
11 methods
clone()
finalize()
hashCode()
equals()
toString()
getClass()
wait()(3)
notify()
notifyAll()
single/simple inheritance
class Test1
{
}
note:
if you are just displaying any java class object internally it invokes
toString() accordingly we will get the output.
example:
````````
package com.infotech.object;
//example on Object class few methods
public class Test1 {
System.out.println(obj);
System.out.println(obj.hashCode());
System.out.println(obj1.hashCode());
System.out.println(obj.getClass());
System.out.println(obj.equals(obj1));
note:
``````
for every new object, hashcode value is different
encapsulation:
``````````````
it is the process of wrapping up of variables and methods into a
single unit.
Student.java:
``````````````
//encapsulated class
public class Student {
//private variables
Test10.java:
````````````
//set the student id and student name value into my student object
//by calling setter methods
st.setStid(100);
st.setStname("Ram");
//by calling getter methods we are able to access the stid & stname
System.out.println("student id is : " + st.getStid());
System.out.println("student name is : " +st.getStname());
}
Student.java:
``````````````
package com.infotech.object;
@Override
public String toString()
{
return stid + " " +stname;
Test2.java:
```````````
package com.infotech.object;
System.out.println(obj1);
note:
`````
whenever we display any java class object, internally it invokes
toString() , if we override toString() inside our class then it will be executed
otherwise Object class toString() gets executed which gives
classname@hashcode value.