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

Basic Java

Uploaded by

Prasanth
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Basic Java

Uploaded by

Prasanth
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 122

Technology: Core Java

Concepts - Day 1

Copyright © 2013 TATA Consultancy Services Limited TCS Internal


1
CONTENT

Classes and Objects

Conditional Operations with Classes and Objects

Iterations and Arrays

2
TCS Internal
CLASSES AND OBJECTS

3
TCS Internal
INTRODUCTION

Java is an Object Oriented Programming(OOP) language

Objects are the basic program components.

A class comprises of objects and its behavior.


Contents
In Java, everything must be encapsulated in a class that
defines the “state” and “behavior” of objects.

4
INTRODUCTION

Objects are created from classes and objects use


methods to communicate between them.

A class serves as a template for an object and behaves


like a data type.
Contents
 Java program incorporates the basic OO(Object Oriented)
concepts such as Encapsulation, Inheritance, Abstraction
and Polymorphism.

5
WHY JAVA ?

Java is a open source programming language created by


Sun Microsoft overtaken by Oracle .
Java is a platform Independent: – Platform independent
means Java can run on any computer irrespective to the
hardware and software dependency. Java does not depend
on type of processor , RAM etc. Java will run on a machine
which will satisfy its basic needs.
Java is a secure Language
 Java is an Object Oriented Programming Language
Collection of Open Source libraries:- Apache, Google, and
other organization have contributed libraries, which
makes Java development easy, faster and cost effective.

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

A Class is a plan which describes the object. We can


call it as a blue print or template of how the object
should be represented.

A class is a collection of fields (data) and methods that


operate on that data.

Class can contain- data members, constructor, block,


methods, classes and interface

9
SCENARIO

An architect will have the blueprints for a house. Those


blueprints will be plans that explains exactly what
properties the house will have and how they are all laid out.
However it is just the blueprint, you can't live in it. Builders
will look at the blueprints and use those blueprints to make
a physical house. They can use the same blueprint to make
as many houses as they want. Each house will have the
same layout and properties and can accommodate it's own
family.

Here the blueprint can be considered as Class and each


house as the Object created from the class.

10
CLASSES
Circle(class)

centre(field)
radius(field)

circumference()(method)
area()(method)

 The basic syntax for a class definition:

class ClassName
{
[fields declaration
[methods declaration]
}
11
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

class keyword is used to declare a class in java.


public keyword is an access modifier which represents visibility. It means it is
visible to all.
static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to
create an object to invoke the static method. The main method is executed by
the JVM, so it doesn't require to create an object to invoke the main method. So
it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is
the object of PrintStream class, println() is the method of PrintStream class. We
will learn about the internal working of System.out.println statement later. 13
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.

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.

A local variable cannot be defined with "static" keyword.

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:

boolean data type


byte data type
char data type
short data type
int data type
long data type
float data type
double data type

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)

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

incrementing/decrementing a value by one


negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
20
System.out.println(++x);//12
Java Arithmetic Operators
Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example


class OperatorExample{
public static void main(String args[]){
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
}}
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
System.out.println(10<<2);//10*2^2=10*4=40
Java Right Shift Operator
The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.

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

A class with only data fields has no significance. Objects


created by such a class have no purpose.
Methods are declared inside the body of the class but
after the declaration of data fields.
The general form of a method declaration is:

retunType MethodName (parameter-list)


{
Method-body;
}

24
ADDING METHODS
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


Adding Methods to Class
Circle
double circumference() {
return 2*3.14*r;
} Method body
public double area() {
return 3.14 * r * r;
}
}
25
OBJECTS

Any real world entity which can have some


characteristics or which can perform some work is
called as Object.

Objects can be a physical or logical entity like a


pen or a College Management System

26
TCS Internal
OBJECTS

Objects can be identified by picking relevant


nouns in the scenario

Objects have-
1. State
2. Behavior
3. Identity- java uniquely identifies all objects

27
OBJECTS

There are three steps when creating an object from a class:

1. Declaration: A variable declaration with a variable name


with an object type.

2. Instantiation: The 'new' key word is used to create the


object.

3. Initialization: The 'new' keyword is followed by a call to a


constructor. This call initializes the new object.

28
Constructors

In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.

Rules for creating Java constructor


There are two rules defined for the constructor.

Constructor name must be the same as its class name


A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

Default constructor (no-arg constructor)


Parameterized constructor

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");

//calling method to display the values of object 30


s1.id;
OBJECTS
 By declaring the Circle class, we have created a new
data type – Circle.
 We can define variables (objects) of that type :
Circle circle1;
Circle circle2;

circle1 circle2

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


31
CREATING OBJECT OF CLASS

Objects are created dynamically using the new keyword.


circle1 and circle2 refer to Circle objects

circle1 = new Circle() ; circle2 = new Circle() ;

32
ACCESSING OBJECT DATA
Similar to C syntax for accessing data defined in a
structure.

ObjectName.VariableName
ObjectName.MethodName(parameter-
list)

Circle circle1 = new Circle();

circle1.x = 2.0 // initialize center and radius


circle1.y = 2.0
circle1.r = 1.0

33
ACCESSING METHODS IN CLASS

Using Object Methods:

sent ‘message’ to circle1

Circle circle1 = new Circle();

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.

There are two ways to overload the method in java

By changing number of arguments


By changing the data type

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

this is a reference variable that refers to the


current object- the object whose method or
constructor is being called.

If there is ambiguity between instance


variable and parameter variable, this keyword
can be used to resolve it.

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);
}

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly
used in the event handling.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
//main
39
s1.p();
6) this keyword can be used to return current class instance
return_type method_name(){
return this;
}

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

Static variable - When a variable is declared as


static, only one instance of a static variable is
created no matter how many objects are created.

Static method- Normally, when you need to invoke


a method you simply create an object, but with the
use of static we do not need to create an object.
This is the reason why main method is always
Static.

Static block – static block is invoked before the


main method

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.

static{System.out.println("static block is invoked");}

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.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.

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:

/A Java class which has only getter methods.


public class Student{
//private data member
private String college="AKG";
//getter method for college
Read-Only
public String getCollege(){
class
return college;
}
}
Write-Only class
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
} 46
CONSTRUCTOR
Every class has a constructor.
If we do not explicitly write a constructor for a class the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor
will be invoked.
A constructor should have the same name as the class.
A class can have more than one constructor.

public Circle(double x, double y,


double r) {
super();
this.x = x;
this.y = y;
this.r = r;}

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

Create a constructor which takes all parameters in the


sequence in the mentioned above question. The constructor
should set the value of attributes as parameter values inside
the constructor.

Create a MAIN Method to test the constructors mentioned


above.

52
ASSIGNMENT
QUE – 3: Static Members

Create a class Account with below attributes:

number - int
acType - String
balance - double
noOfAccountHolders - int
numberCounter - int which is a static field and initialize to 0

Make all the attributes private. Create corresponding getters


and setters.
Create a constructor which takes all parameters except the
static member and the attribute number in the above
sequence.

53
ASSIGNMENT

The constructor should set the value of attributes as


parameter values inside the constructor. Increment the value
of the static member by 1 inside the constructor and assign to
the attribute number.

Test from the main method by creating 5 objects of the


Account class and print the numberCounter value after
creation of each object.

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.

Conditional logic is involved when different operations are


to be performed based on whether a condition is true or
not.
Conditional expressions consists of conditions that results in
a boolean value and performs actions based on the boolean
result.

There are three types of decision making statements in


Java. They are:
56
TCS Internal
IF STATEMENT
if –This statement is the most basic of all control flow
statements. “if” statement has a certain condition
expression. It executes a certain section of code only if that
particular condition is true. If the condition is false, control
jumps to the end of the if statement.

public class IfExample {


public static void main(String[] args) {
Customer c1 = new
Customer(102,"Amit",31);//invoking
Customer constructor
Customer c2 = new Customer(102,"Rohan",91);
if(c1.getAge()<c2.getAge())
System.out.print(c1.getName()+" is
younger");
} }
OUTPUT:
Amit is younger
57
TCS Internal
IF STATEMENT

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.

public class IfElseExample {


public static void main(String[] args) {

Customer c1 = new Customer(102,"Amit",31);


Customer c2 = new Customer(102,"Rohan",11);
if(c1.getAge()<c2.getAge())
System.out.print(c1.getName()+" is
younger");
else
System.out.println(c2.getName()+ " is
younger");
} }

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.

A conditional operator starts with a boolean operation,


followed by two possible values for the variable to the left of
the assignment (=) operator.

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

QUE – 1: Conditional operations


Create a package “com”.
Create class GradeDemo with main method.
Write a static method findGrade which will take percentage as
input and return grade based on below criteria:
Grade A : Percent >= 80
Grade B : Percent >=60 and < 80
Grade C: Percent >=40 and < 60
Grade D: Percent >=30 and < 40
Grade E : Percent < 30
For any invalid input, this method will return Grade O

65
ARRAYS AND ITERATIONS

66
TCS Internal
CONTENT

 Data Types

 Loops

 Array

67
TCS Internal
DATA TYPES

 Data types represent the different values to be stored


in the variable. It defined by the values it can take and
the operations that can be performed on it.

 There are two types of data types:

Primitive and Non -primitive.

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:

– byte // byte a = 100 , byte b = -50


– short // short s = 10000, short r = -20000
– int // int a = 100000, int b = -200000
– float // float f1 = 234.5f
– long // long a = 100000L, long b = -200000L
– boolean // boolean one = true
– char // char letterA ='A'
– double // double d1 = 123.4
70
NON-PRIMITIVE DATA TYPES
 Non-primitive data types are not predefined and are created
by the programmer.
– Arrays
– Structure
– Union
– Linked List
– Stack
– Queue

71
LOOPS

 Loops are used for automatically repeating similar


task many number of times.
 Loops in java:

• 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:

public class Loops {


public static void main(String[] args) {
int i=1;
while(i<=5){
System.out.print(i);
i++;
}
} }
OUTPUT:
12345

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:

public class Loops {


public static void main(String[] args) {
int i=5;
do{
System.out.print(i);
i++;
}while(i<5);
} }
OUTPUT:
5
74
FOR LOOP
For loops execute a sequence of statements multiple
times and abbreviates the code that manages the loop
variable.
The syntax of a for loop is:

public class Loops {

public static void main(String[] args) {


for(int i=1;i<=5;i++){
System.out.print(i);
}
}
}

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:

public class Loops {


public static void main(String[] args) {
int arr[]={2,9,4,5,7};
for(int i:arr){

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:

• It is capable of storing many elements at a


time.

• It allows random accessing of elements i.e.


any element of the array can be randomly
accessed using indexes.

79
DISADVANTAGES OF ARRAY
 Disadvantages of Arrays:

• Predetermining the size of the array is a must.

• There is a chance of memory wastage or


shortage.

• To delete one element in the array, we need


to traverse throughout the array.

80
ASSIGNMENT
QUE – 1: Array

Create a class Customer with below attributes:

int - id
String - name
String - dob
double - salary
String - email
int – age

Make all the attributes private. Create corresponding getters


and setters.
Create a constructor which takes all parameters in the above
sequence. The constructor should set the value of attributes to
parameter values inside the constructor.
Create a class CustomerDemo with main method
81
ASSIGNMENT

Create the below static method searchCustomerById in the


CustomerDemo class.

searchCustomerById(Customer[] objArray)

This method will take array of Customer objects and id as


input and returns the position of the id if found or -1 if not
found.

Create an array of 5 Customer objects in the main method

Call the above static method from the main method

82
ASSIGNMENT
QUE – 2: Array

Create a class Item with below attributes:

int - id
String - name
double - price
int – quantity

Make all the attributes private. Create corresponding getters


and setters.

Create a constructor which takes all parameters in the above


sequence. The constructor should set the value of attributes to
parameter values inside the constructor.
Create a class ItemDemo with main method

83
ASSIGNMENT

Create the below static method searchItemByName in the


ItemDemo class.

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.

Create an array of 5 Item objects in the main method

Call the above static method from the main method

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.

Inheritance provided mechanism that allowed a class to


inherit property of another class.

When a Class extends another class it inherits all non-


private members including fields and methods

Inheritance in Java can be best understood in terms of


Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.

extends keyword IS used to describe inheritance in


Java.
88
TCS Internal
INHERITANCE

89
TCS Internal
TYPES OF INHERITANCE

Single Level Inheritance

Multi- Level Inheritance

Multiple Inheritance

Hierarchical Inheritance

Hybrid Inheritance

90
SINGLE INHERITANCE
1. Single Inheritance :

In this inheritance, a derived class is created from a


single base class.

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.

Java does not support multiple inheritance.


– In multiple inheritance there is a chance of multiple
properties of multiple objects with the same name being
available to the sub class object. This leads to ambiguity.

100
MULTIPLE INHERITANCE
Multiple Inheritance problem

Class A
play(){...}

Class B Class C
play(){...} play(){...}
So Java provides
INTERFACE for it

Extend one class, implement ‘n’ interfaces Class D


play();
Which
play() ?

class Cat extends Feline implements Pet{…}


class Dog extends Canine implements Pet{…}

101
TCS Internal
ADVANTAGE OF INHERITANCE

1.Inheritance-It can make application code more


flexible to change because classes that inherit form a
common superclass can be used interchangeably.

2.Reusability-Facility to use public methods of base


class without rewriting the same.

3.Extensibilty-Extending the base class logic as per


business logic of the derived class.

102
DISADVANATAGE OF INHERITANCE

1.It increase’s time/effort to take the program to jump


through all the levels of overloaded classes.

2.Main Disadvantage of Using inheritance is that the


two classes(base and inherited class) get tightly
coupled.

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

Also called compile time polymorphism

Class can have more than one methods with


same name but different number or
sequence or type of arguments.

Type of the object is determined at compile


time(by the compiler). Known as static binding.

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{}

Parent object=new Child(); //upcasting

108
TCS Internal
METHOD OVERRIDING

109
TCS Internal
STATIC vs DYNAMIC POLYMORPHISM

Static Polymorphism Dynamic Polymorphism

Call is resolved at compile time. Call is resolved at runtime.

Achieved by method overloading. Achieved by method overriding.

Fast execution because known early at Slow execution as compared to early


compile time. binding because it is known at runtime.

110
Less flexible as all things execute at More flexible as all things execute at run
TCS Internal
ASSIGNMENT

QUE – 1: Inheritance

Create a class Item with below attributes:

int - id
String - name
double - price
int – quantity

Create a constructor which takes all parameters in the above


sequence. The constructor should set the value of attributes to
parameter values inside the constructor.

111
ASSIGNMENT
Create a child class Vehicle for the above class with below
attributes:

int - number
String - name
double – price

Create a constructor which takes all parameters of the parent


as well as child class in the above sequence.

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.

Create a class ItemDemo with a main method. Create objects


of the Parent and Child Class using the constructor.

112
ASSIGNMENT
QUE – 2: Polymorphism

Create a class Student with below attributes:


int - id
String - name
double - marks
int – age

Make all the attributes private. Create corresponding getters


and setters.

Create a constructor which takes all parameters in the above


sequence. The constructor should set the value of attributes to
parameter values inside the constructor.

113
ASSIGNMENT

Create a method add(double marks) - adds given input value


to marks attribute

Create a method add(double marks,int age)- adds given input


value to marks,age attributes respectively.

The return type of the above methods should be void.

Create a main method and test the above methods.

114
EXTRA ASSIGNMENTS
TOPIC: Classes and Objects

Create a class Item with below attributes:


id - int
name - String
price - double
quantity – int

Make all the attributes private. Create corresponding getters


and setters.
Create a constructor which takes all parameters in the above
sequence. The constructor should set the value of attributes
as parameter values inside the constructor.
Create a class Demo with main method. Declare item object in
main method using constructor.
Print item details(id, name, price and quantity) using the
getter methods.
115
EXTRA ASSIGNMENTS
TOPIC: Conditional Operations

Create class Customer with below attributes:

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.

Thus, a customer who charges Rs. 400 a year receives


Rs.1.00, which is 0.25 * 1/100
* 400, and one who charges Rs1, 400 a year receives Rs. 5.75,
which is 1.25 = 0.25 *
1/100 * 500 for the first Rs. 500 and 0.50 *1/100 * 900 = 4.50
for the next Rs. 900.
117
EXTRA ASSIGNMENTS

Create another class as CreditCardDemo which will have main


method. Within main

method, create object of CreditCardCompany. Create 5


customer objects with relevant

data. Call the method to return payback amount for each


customer and display the same.

Ensure class attributes are private and other methods are


public.

118
EXTRA ASSIGNMENTS

TOPIC: Arrays and Iterations

Create a class Account with below attributes:

int - number
String - acType
double - balance
int - noOfAccountHolders

Make all the attributes private. Create corresponding getters


and setters.

Create a constructor which takes all parameters in the above


sequence. The constructor should set the value of attributes to
parameter values inside the constructor.

119
EXTRA ASSIGNMENTS

Create a class AccountDemo with main method

Create the below static method sortAccountByNumber in the


AccountDemo class.

sortAccountByNumber(Account[] objArray)

The method will sort the array based on number and return
the sorted array.

Create an array of 5 Account objects in the main method

Call the above static method from the main method

120
EXTRA ASSIGNMENTS
TOPIC: Inheritance and Polymorphism

Create a class Item with below attributes:


int - id
String - name
double - price
int – quantity
Create a constructor which takes all parameters in the above
sequence. The constructor should set the value of attributes to
parameter values inside the constructor.

Create a child class Vehicle for the above class with below
attributes:
int - number
String - name
double - price

121
EXTRA ASSIGNMENTS

Create a constructor which takes all parameters of the parent as


well as child class in the above sequence.
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.
Override the toString method in the parent class which will return
the name and the value of each attribute of the parent class.
Override the toString method in the child class which will call the
parent toString method using super keyword and also return the
name and the value of each attribute of the child class.
Create a class ItemDemo with a main method. Create objects of
the Parent and Child Class and test the toString method
Create a child object referenced by the parent class and call the
toString method.

122
Thank You

Copyright © 2013 TATA Consultancy Services Limited


123
TCS Internal

You might also like