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

Java Day-1 2

Uploaded by

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

Java Day-1 2

Uploaded by

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

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 Microsystems 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
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

7
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.

8
CLASSES

Circle(class)

centre(field)
radius(field)

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

⚫ The basic syntax for a class definition:


class ClassName
{
[fields declaration
[methods declaration]
}
9
ADDING FIELDS

▪ Add fields

Classes
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle

The fields (data) are also called the instance variables.


⚫ Here x,y and r are the instance variables

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

11
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
public double circumference() {
return 2*3.14*r;
} Method body
public double area() {
return 3.14 * r * r;
}
}
12
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

13
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

14
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.
15
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)


16
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() ;

17
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

18
ACCESSING METHODS IN CLASS

Using Object Methods:

sent ‘message’ to circle1

Circle circle1 = new Circle();

double area;
circle1.r = 1.0;
area = circle1.area();

19
USING CLASS

class MyMain
{
public static void main(String args[])
{
Circle circle1; // creating reference
circle1 = 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+"
Circumference ="+circumf);
}
}

20
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

21
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.

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

23
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. 24
ACCESS MODIFIER
The scope of access modifiers in java

25
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;
} 26
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.
27
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.

28
ASSIGNMENT
QUE – 3: Static Members

Create a class Account with below attributes:

number - int
acType - String
balance - doubnoOfAccountHoldersle
- 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.

29
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.

30
CONDITIONAL OPERATIONS

31
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:
32
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
33
TCS Internal
IF STATEMENT

34
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
35
TCS Internal
IF-ELSE STATEMENT

36
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
37
TCS Internal
SWITCH STATEMENT

38
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.

39
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

40
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

41
ARRAYS AND ITERATIONS

42
TCS Internal
CONTENT

▪ Data Types

▪ Loops

▪ Array

43
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.

44
DATA TYPES

45
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
46
NON-PRIMITIVE DATA TYPES
▪ Non-primitive data types are not predefined and are created
by the programmer.
– Arrays
– Structure
– Union
– Linked List
– Stack
– Queue

47
LOOPS

▪ Loops are used for automatically repeating similar


task many number of times.
▪ Loops in java:
• While
• Do-While
• For
• Enhanced for

48
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

49
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
50
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
51
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);
}
} }
OUTPUT:
29457
52
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;
53
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 54
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.

55
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.

56
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
57
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

58
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

59
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

60
Thank You

Copyright © 2013 TATA Consultancy Services Limited


61
TCS Internal

You might also like