Basic Java
Basic Java
Concepts - Day 1
2
TCS Internal
CLASSES AND OBJECTS
3
TCS Internal
INTRODUCTION
4
INTRODUCTION
5
WHY JAVA ?
6
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because
it doesn't physically exist. It is a specification that provides a runtime environment in
which Java bytecode can be executed. JVM architecture in Java contains classloader,
memory area, execution engine etc.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of
JVM. It physically exists. It contains a set of libraries + other files that JVM uses at
runtime.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications and
applets. It physically exists. It contains JRE + development tools.
7
8
CLASSES
9
SCENARIO
10
CLASSES
Circle(class)
centre(field)
radius(field)
circumference()(method)
area()(method)
class ClassName
{
[fields declaration
[methods declaration]
}
11
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
14
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be
changed.
int data=50;
Types of Variables
There are three types of variables in Java:
local variable
instance variable 15
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory.
16
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
17
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
There are 8 types of primitive data types:
18
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -,
*, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
19
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(10>>2);//10/2^2=10/4=2
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5; 22
int c=20;
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check second condition if first condition is true. It
checks second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
23
}}
ADDING METHODS
24
ADDING METHODS
public class Circle {
26
TCS Internal
OBJECTS
Objects have-
1. State
2. Behavior
3. Identity- java uniquely identifies all objects
27
OBJECTS
28
Constructors
29
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Student(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
//main
Student s1 = new Student(111,"Karan");
Studen4 s2 = new Student4(222,"Aryan");
circle1 circle2
null null
32
ACCESSING OBJECT DATA
Similar to C syntax for accessing data defined in a
structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-
list)
33
ACCESSING METHODS IN CLASS
double area;
circle1.r = 1.0;
area = circle1.area();
34
USING CLASS
class MyMain
{
public static void main(String args[])
{
Circle circle1; // creating reference
aCircle = new Circle(); // creating
object
circle1.x = 10; // assigning value to
data field
circle1.y = 20;
circle1.r = 5;
double area = circle1.area(); //
invoking method
double circumf =
circle1.circumference();
System.out.println("Radius="+circle1.r+"
Area="+area);
System.out.println("Radius="+circle1.r+" 35
Circumference ="+circumf);
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
2) Method Overloading: changing data type of arguments
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;} 36
THIS
37
this
In java, this is a reference variable that refers to the current object.
It is better approach to use meaningful names for variables. So we use same
name for instance variables and parameters in real time, and always use this
keyword.
2)2) this: to invoke current class method – by compiler
//m();//same as this.m()
this.m();
3) this() : to invoke current class constructor.Rule: Call to this() must be the first
statement in constructor.
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
//main
A a=new A(10);
38
//reverse
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
40
STATIC
41
The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
class Student{
int rollno;
String name;
String college="ITS";
}
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
42
2) 2) Java
Java static
static method you apply static keyword with any method, it is known as
method-If
static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a
class.
A static method can access static data member and can change the value of it.
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
Student.change();//calling change method
Restrictions for the static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method
directly.
this and super cannot be used in static context.
43
3) Java static block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
4)Static class- A static inner class is a nested class which is a static member of the
outer class. It can be accessed without instantiating the outer class, using other
static members. Just like static members, a static nested class does not have
access to the instance variables and methods of the outer class.
public class Outer {
Java Arrays with Answers
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
} 44
}
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit, for example, a capsule which is mixed of several medicines.
encapsulation in java
We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You
can write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
45
The encapsulate class is easy to test. So, it is better for unit testing.
Read-Only class:
47
ACCESS MODIFIER
The access modifiers in java specifies accessibility (scope) of a
data member, method, constructor or class.
There are 4 types of java access modifiers:
1. Public - The public access modifier is accessible
everywhere. It has the widest scope among all other
modifiers.
2. Default – When the access modifier is not mentioned,
default is the modifier by default. The default modifier is
accessible only within package.
3. Protected - The protected access modifier is accessible
within package and outside the package but through
inheritance only.
4. Private - The private access modifier is accessible only
within class. It is the most restrictive access level.
Variables that are declared private can be accessed
outside the class using getter methods. 48
ACCESS MODIFIER
The scope of access modifiers in java
49
GETTER AND SETTER
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
} 50
ASSIGNMENT
QUE – 1: Constructor
Create a class Customer with below attributes:
id - int
name - String
dob - String
salary - double
email - String
age – int
Following Constructor needs to be created for the class
Customer:-
Create a default constructor which sets the default value as
the value of the attributes.
Create a MAIN Method to test the constructors mentioned
above.
51
ASSIGNMENT
QUE – 2: Constructor
52
ASSIGNMENT
QUE – 3: Static Members
number - int
acType - String
balance - double
noOfAccountHolders - int
numberCounter - int which is a static field and initialize to 0
53
ASSIGNMENT
54
CONDITIONAL OPERATIONS
55
TCS Internal
CONDITIONAL OPERATIONS
There are many scenarios in our everyday life, where we
need to take some decisions based on some criteria or
condition.
Decision making is one of the major part of Java also as it is
a programming language.
58
TCS Internal
IF-ELSE STATEMENT
if ... else –This statement provides a secondary path of
execution when the condition becomes false.
There can be nested if then else statement also.
OUTPUT:
Rohan is younger 59
TCS Internal
IF-ELSE STATEMENT
60
TCS Internal
SWITCH STATEMENT
Switch –A switch statement allows a variable to be tested for
equality against a list of values. Each value is called a case,
and the variable being switched on is checked for each case.
public class SwitchExample{
public static void main(String[] args) {
Customer c1 = new Customer(102,"Nisha",31,'F');
Customer c2 = new Customer(102,"Rohan",11,'M');
char gender = 'F';
switch(gender) {
case 'F' :
System.out.println("Female");
break;
case 'M' :
System.out.println("Male");
break;
default :
System.out.println("Not specified");}} }
OUTPUT:
Female
61
TCS Internal
SWITCH STATEMENT
62
TCS Internal
TERNARY OPERATOR
The conditional operator(or ?) is a ternary operator as it has
three operands and is used to evaluate boolean expressions,
much like an if statement except instead of executing a
block of code if the test is true, a conditional operator will
assign a value to a variable.
The first value (the one to the left of the colon) is assigned if
the conditional (boolean) test is true, and the second value
is assigned if the conditional test is false. In below example,
if variable a is less than b then the variable x value would be
50 else x =60.
63
TCS Internal
TERNARY OPERATOR
class TernaryOperatorExample{
public static void main(String[] args){
String younger = c1.getAge()<c2.getAge() ?
c1.getName() : c2.getName();
System.out.println(younger + " is younger");
}}
OUTPUT:
Rohan is younger
64
TCS Internal
ASSIGNMENT
65
ARRAYS AND ITERATIONS
66
TCS Internal
CONTENT
Data Types
Loops
Array
67
TCS Internal
DATA TYPES
68
DATA TYPES
69
PRIMITIVE DATA TYPES
A primitive type is predefined and is named by a reserved
keyword.
Primitive data types in java are:
71
LOOPS
• While
• Do-While
• For
• Enhanced for
72
WHILE LOOP
The while statement continually executes a block of
statements while a particular condition is true.
The syntax can be expressed as:
73
DO-WHILE LOOP
The difference between do-while and while is that do-
while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the
do block are always executed at least once.
The syntax can be expressed as:
OUTPUT:
12345
75
FOR-EACH LOOP
Its simple structure allows one to simplify code by
presenting for-loops that visit each element of an
array/collection without explicitly expressing how one
goes from element to element.
The syntax can be expressed as:
System.out.print(i);
}
} } 76
ARRAY
Java array is an object containing fixed set elements of
similar data type.
Array index starts from 0.
Array can be declared in the following ways:
– int a[]={33,3,4,5};//declaration,
instantiation and initialization
– int a[]=new int[5];//declaration and
instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
77
ARRAY DEMO
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and
instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the
property of
array
System.out.print(a[i]);
} }
OUTPUT:
10 20 70 40 50 78
ADVANTAGES OF ARRAY
Advantages of Array:
79
DISADVANTAGES OF ARRAY
Disadvantages of Arrays:
80
ASSIGNMENT
QUE – 1: Array
int - id
String - name
String - dob
double - salary
String - email
int – age
searchCustomerById(Customer[] objArray)
82
ASSIGNMENT
QUE – 2: Array
int - id
String - name
double - price
int – quantity
83
ASSIGNMENT
This method will take array of Item objects and name as input
and returns new array of Item objects for all values found with
the given name else return null if not found.
84
INHERITANCE AND POLYMORHISM
85
TCS Internal
INHERITANCE AND POLYMORPHISM
What is Inheritance?
Single Level Inheritance
Multi- Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multiple Inheritance
What is Polymorphism?
Static Polymorphism
Dynamic Polymorphism
86
TCS Internal
INHERITANCE
87
TCS Internal
INHERITANCE
Inheritance is one of the key features of Object Oriented
Programming.
89
TCS Internal
TYPES OF INHERITANCE
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
90
SINGLE INHERITANCE
1. Single Inheritance :
91
TCS Internal
SINGLE INHERITANCE
class Parent{
public void display(){
System.out.println("Parent class method");
}}
class Child extends Parent{
public void show(){
System.out.println("Child class method");
}}
public class TestMain {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.display();
child.display();
child.show();}}
OUTPUT:
Parent class is invoked
Parent class is invoked
Child class is invoked 92
TCS Internal
MULTILEVEL INHERITANCE
2. Multi-level Inheritance
In this inheritance, a derived class is created from
another derived class.
93
TCS Internal
MULTILEVEL INHERITANCE
class Grandparent {
public void display(){
System.out.println("Grandparent method is
invoked");
}}
class Parent extends Grandparent{
public void show(){
System.out.println("Parent method is invoked");
}}
class Child extends Parent{
public void write(){
System.out.println("Child method is
invoked");
}}
94
TCS Internal
MULTILEVEL INHERITANCE
public class TestMain {
public static void main(String[] args) {
Grandparent g = new Grandparent();
Parent p = new Parent();
Child c = new Child();
g.display();
p.show();
p.display();
c.write();
c.show();
c.display();}}
OUTPUT:
Grandparent method is invoked
Parent method is invoked
Grandparent method is invoked
Child method is invoked
Parent method is invoked
Grandparent method is invoked TCS Internal
95
HIERARCHICAL INHERITANCE
3. Hierarchical inheritance
In this inheritance, more than one derived
classes are created from a single base.
96
HIERARCHICAL INHERITANCE
class Parent {
public void display(){
System.out.println("Parent class method
invoked");
}}
class Child1 extends Parent{
public void show(){
System.out.println("Child1 class method
invoked");
}}
class Child2 extends Parent{
public void write(){
System.out.println("Child2 class method
invoked");
}}
97
HIERARCHICAL INHERITANCE
public class TestMain {
public static void main(String args[]){
Parent parent = new Parent();
Child1 child1 = new Child1();
Child2 child2 = new Child2();
parent.display();
child1.show();
child1.display();
child2.write();
child2.display() }}
OUTPUT:
Parent class method invoked
Child1 class method invoked
Parent class method invoked
Child2 class method invoked
Parent class method invoked
98
HYBRID INHERITANCE
4. Hybrid inheritance
This is combination of more than one inheritance.
99
MULTIPLE INHERITANCE
5. Multiple Inheritance
In this inheritance, a derived class is created from more
than one base class.
100
MULTIPLE INHERITANCE
Multiple Inheritance problem
Class A
play(){...}
Class B Class C
play(){...} play(){...}
So Java provides
INTERFACE for it
101
TCS Internal
ADVANTAGE OF INHERITANCE
102
DISADVANATAGE OF INHERITANCE
103
POLYMORPHISM
Polymorphism means many (poly) shapes (morph)
Allows to define one interface and multiple
implementations.
104
TCS Internal
TYPES OF POLYMORPHISM
105
TCS Internal
STATIC POLYMORPHISM
106
TCS Internal
METHOD OVERLOADING
Shape
Rectangle
Circle Square
Definition : Definition :
findArea(int Definition :
findArea(double findArea(int
length,int breadth) radius)
Implementation: side)
Implementation: Implementation:
area=length*breadth Area=3.14*radius Area=side*side
*radius
107
TCS Internal
DYNAMIC POLYMORPHISM
Also called as runtime polymorphism.
A call to an overriden method is resolved at runtime
rather than compile time.
Upcasting:The overriden method is called through
the reference variable of super class (Parent class).
class Parent{}
class Child extends Parent{}
108
TCS Internal
METHOD OVERRIDING
109
TCS Internal
STATIC vs DYNAMIC POLYMORPHISM
110
Less flexible as all things execute at More flexible as all things execute at run
TCS Internal
ASSIGNMENT
QUE – 1: Inheritance
int - id
String - name
double - price
int – quantity
111
ASSIGNMENT
Create a child class Vehicle for the above class with below
attributes:
int - number
String - name
double – price
The constructor should call the super constructor and set the
attributes of the parent class. Set the value of child attributes
to parameter values inside the constructor.
112
ASSIGNMENT
QUE – 2: Polymorphism
113
ASSIGNMENT
114
EXTRA ASSIGNMENTS
TOPIC: Classes and Objects
custId
accountId
creditCardCharges
Create another class CreditCardCompany which has a method
which takes Customer
object as parameter and returns the payback amount for the
credit card charges value
for that customer. Use below logic to calculate payback amount:
116
EXTRA ASSIGNMENTS
a) 0.25% for charges up to Rs. 500.
b) 0.50% for the next Rs.1000 (that is, the portion between Rs.
500 and Rs. 1500),
c) 0.75% for the next Rs.1000 (that is, the portion between Rs.
1500 and Rs. 2500),
d) 1.0% for charges above Rs2500.
118
EXTRA ASSIGNMENTS
int - number
String - acType
double - balance
int - noOfAccountHolders
119
EXTRA ASSIGNMENTS
sortAccountByNumber(Account[] objArray)
The method will sort the array based on number and return
the sorted array.
120
EXTRA ASSIGNMENTS
TOPIC: Inheritance and Polymorphism
Create a child class Vehicle for the above class with below
attributes:
int - number
String - name
double - price
121
EXTRA ASSIGNMENTS
122
Thank You