SlideShare a Scribd company logo
Aptech Software Ltd.
Session 2
Java Language Fundamentals
A Simple Approach – Core Java / Session 2/ 2 of 30
Aptech Software Ltd.
Review
 Java was introduced by Sun Microsystems in 1995.
 Java is object-oriented and a cross platform language.
 Java bytecodes are machine language instructions understood by
the Java Virtual Machine (JVM) and usually generated as a result of
compiling Java language source code.
 A "Just-In-Time" (JIT) Java compiler produces native code from
Java byte code instructions during program execution.
 Applets are Java programs that run through a Java enabled web
browser.The Java Development Kit (JDK) contains the software and
tools needed to compile, debug and execute applets and
applications written in the Java language. It’s basically a set of
command-line tools.
 Java program can be run using command-line arguments.
The data type of these arguments is String.
A Simple Approach – Core Java / Session 2/ 3 of 30
Aptech Software Ltd.
Objectives
Explain the basics of Java Language
Identify the Data Types
Understand arrays
Identify Operators
Format output using Escape Sequence
Use Control Flow Statements
A Simple Approach – Core Java / Session 2/ 4 of 30
Aptech Software Ltd.
Basics of the Java Language
Data types Variables Operators Control Flow Statements
Java Blocks
A variable is a named memory location.
Data types determine the type of data to be stored in memory.
An operator is a symbol that operates on one or more arguments to
produce a result.
Programs are executed in sequential order. Control flow statements allow
variations in this sequential order.
A Simple Approach – Core Java / Session 2/ 5 of 30
Aptech Software Ltd.
Data Types
 byte
 char
 boolean
 short
 int
 long
 float
 double
 Array
 Class
 Interface
Primitive Data Types Reference Data Types
A Simple Approach – Core Java / Session 2/ 6 of 30
Aptech Software Ltd.
Variables
Three components of a variable
declaration are:
 Data type
 Name
 Initial value to be assigned (optional)
Syntax:
datatype identifier [=value][,
identifier[=value]...];
A Simple Approach – Core Java / Session 2/ 7 of 30
Aptech Software Ltd.
class VariableTest {
public static void main(String [] args) {
double a = 1.0;
int b = 3;
System.out.println("Value of double variable is: "+a);
System.out.println("Value of integer variable is: "+b);
}
}
Variable declaration and
initialization
Example
Note: Always initialize your variables when you define
them. If you don’t know what value a variable should have
when you define it, initialize it to zero.
float f;
A Simple Approach – Core Java / Session 2/ 8 of 30
Aptech Software Ltd.
Scope and Lifetime of Variables
Variables can be declared inside a block.
The block begins with an opening curly brace
and ends with a closing curly brace.
A block defines a scope.
A new scope is created every time a new block
is created.
Scope specifies which variables are visible to
other parts of the program.
It also determines the life of the variables.
A Simple Approach – Core Java / Session 2/ 9 of 30
Aptech Software Ltd.
class ScopeVariable {
public static void main(String[] args) {
/* num is available in inner scope */
int num = 2;
/* Testing variable num */
if (num == 2) {
int num1 = num * num;
System.out.println("Value of num and num1 are "
+ num + " " + num1);
}
/* num1 = 10; ERROR ! num1 is not known */
System.out.println("Value of num is " + num);
}
}
Example
//num1 = 10; ERROR ! num1 is not known
 Check the scope of the variables.
 ERROR!!! If variable is accessed outside its scope.
A Simple Approach – Core Java / Session 2/ 10 of 30
Aptech Software Ltd.
Type Casting
Type Casting causes the program to treat a
variable of one type as though it contains data
of another type.
Example:
float c = 34.89675f;
int b = (int) c + 10; // Convert c to an integer
A Simple Approach – Core Java / Session 2/ 11 of 30
Aptech Software Ltd.
Types of Data Conversion
Automatic Type Conversion Casting
When one type of data is assigned
to a variable of another type,
automatic type conversion takes
place provided it meets the
following conditions:
The two types are compatible.
The destination type is larger
than the source type.
Casting is used for explicit type
conversion. It loses information
above the magnitude of the
value being converted.
A Simple Approach – Core Java / Session 2/ 12 of 30
Aptech Software Ltd.
Example
 Declare and initialize the variables
 Add the variables and assign the
value to the variable of different
data type without explicit type
casting.
 No ERROR!!!
long sum;
int first = 20,
second = 30;
sum = first + second;
Demonstration: Additional Example 2
Automatic Type Casting Casting
 Declare the variables
 The variables will hold the
values which are passed
during runtime.
 Add the variable after type
casting.
int first, second, sum;
first = Integer.parseInt(args[0]);
second = Integer.parseInt(args[1]);
sum = first + second;
Demonstration: Additional Example 1
A Simple Approach – Core Java / Session 2/ 13 of 30
Aptech Software Ltd.
Type Promotion Rules
All byte and short values are promoted to int
type.
If one operand is long, the whole expression is
promoted to long.
If one operand is float, the whole expression is
promoted to float.
If one operand is double, the whole expression
is promoted to double.
A Simple Approach – Core Java / Session 2/ 14 of 30
Aptech Software Ltd.
Arrays 1-2
 An array is a data structure that stores data of same data
type in consecutive memory locations.
 Three ways to declare an array are:
datatype identifier [ ];
datatype identifier [ ] = new datatype[size];
datatype identifier [ ] = {value1,value2,….valueN};
 Array can have more than one dimension
A Simple Approach – Core Java / Session 2/ 15 of 30
Aptech Software Ltd.
Arrays 2-2
 It consists of a single
column of data of the
same type.
 An array is declared
by specifying its name
and size.
One Dimensional Array Multi Dimensional Array
 Multi Dimensional arrays are
arrays of arrays.
 To declare a Multi Dimensional
array, additional index has to
be specified by using another
set of square brackets.
A Simple Approach – Core Java / Session 2/ 16 of 30
Aptech Software Ltd.
Example
 Array Declaration
 Accessing the array elements
 Using the length property
Demonstration: Example 3 and Additional Example 3
/* Array Initialization */
double[] nums = {2, 0, 1};
/* Printing array element */
System.out.println("The value at location 3
is :" + nums[2]);
int[] numbers = {8, 18, 5, 2, 1, 10};
System.out.println("Total number of
elements in an array is: "+ numbers.length);
System.out.println("First element in an
array is: " + numbers[0]);
System.out.println("Last element in an
array is: “ + numbers[numbers.length - 1]);
A Simple Approach – Core Java / Session 2/ 17 of 30
Aptech Software Ltd.
Operators
Operators Description Examples
Arithmetic
Operators Arithmetic Operators use numeric operands. These
operators are mainly used for mathematical calculations.
+, - * % etc
Relational
Operators
Relational Operators test the relation between two operands.
The result of an expression where relational operators are
used is boolean.
==, >=, <= etc
Logical
Operators
Logical Operators work with boolean operands. &, |, ^ etc
Conditional
Operators
The Conditional Operator is unique, because it is a ternary
or triadic operator that has three operands to the expression.
It can replace certain types of if-then-else statements.
!=, =, *=, /=, +=, -=
Assignment
Operators
The Assignment Operator is a single equal sign, =, and
assigns a value to a variable.
=
A Simple Approach – Core Java / Session 2/ 18 of 30
Aptech Software Ltd.
Examples
Code Snippet:
int a= 5, b= 12,d=10,c;
c=a+b; Addition
c=a%b; Modulus
d++; Increment
d--; Decrement
Value of c and d:
c=17  After adding
c=2  This is remainder of a/b
d=11  After incrementing
d=10  After decreasing the value
Code Snippet:
boolean i=true, j=false;
boolean or=i|j, and=i&j;
!i;
!j;
Value of or and and:
or=true  Using logical or
and=false  Using logical and
i=false  Using logical unary not
j=true  Using logical unary not
Arithmetic Operators Logical Operators
A Simple Approach – Core Java / Session 2/ 19 of 30
Aptech Software Ltd.
Operator Precedence
 Expressions that are written will generally consist of several
operators. The rules of precedence decide the order in which
each operator is evaluated in any given expression.
Order Operator
1. Parentheses like ( ) and [ ]
2. Unary Operators like +, -, ++, --, ~, !
3. Arithmetic and Shift operators like *, /, %, +, -, >>, <<
4. Relational Operators like >, >=, <, <=, ==, !=
5. Logical Operators like &, ^, |, &&, ||
6. Conditional and Assignment Operators like ?=, =, *=, /=,
+=, -=
A Simple Approach – Core Java / Session 2/ 20 of 30
Aptech Software Ltd.
Formatting output with Escape Sequences
 Whenever an output is to be displayed on the screen, it needs to be
formatted.
 The formatting can be done with the help of escape sequences that
Java provides.
Example:
System.out.println (“Happy tBirthday”);
Output:
Happy Birthday
A Simple Approach – Core Java / Session 2/ 21 of 30
Aptech Software Ltd.
Control Flow Statements
 All application development environments provide a
decision making process called control flow statements
that direct the application execution.
 Control flow enables a developer to create an
application that can examine the existing conditions,
and decide a suitable course of action.
 Loops or iterations are an important programming
construct that can be used to repeatedly execute a set
of actions.
 Jump statements allow the program to execute in a non-
linear fashion.
A Simple Approach – Core Java / Session 2/ 22 of 30
Aptech Software Ltd.
Types of Control Flow Statements
Decision-making
if-else statement
switch-case statement
Loops
while loop
do-while loop
for loop
A Simple Approach – Core Java / Session 2/ 23 of 30
Aptech Software Ltd.
if-else statement
 The if-else statement tests the result of a condition,
and performs appropriate actions based on the result.
 It can be used to route program execution through two
different paths.
 The syntax of if-else statement is::
if (condition)
{
action1;
}
else
{
action2;
}
A Simple Approach – Core Java / Session 2/ 24 of 30
Aptech Software Ltd.
switch – case statement
 The switch – case statement can be used as an alternative for if-else-if
statement.
 It is used in situations where an expression is evaluated multiple values.
 The use of the switch-case statement results in better performance.
 The syntax of switch-case is:
switch (expression) {
case 1:
action1 statements;
break;
case 2':
action2statements;
break;
….
case N ':
actionN statements;
break;
default:
default statements; }
A Simple Approach – Core Java / Session 2/ 25 of 30
Aptech Software Ltd.
Loops 3-1
while
The while loop executes a statement or set of statements as long as the
condition specified evaluates to true.
Syntax
int count = 0;
while (count < 10) {
System.out.println(count);
count++;
}
Example
while (test)
{
// statement
}
Executed
Condition = True
A Simple Approach – Core Java / Session 2/ 26 of 30
Aptech Software Ltd.
Loops 3-2
do-while
The do-while loops execute certain statements till the specified condition is
true. This loop ensures that the loop body is executed at least once.
Syntax
do {
System.out.println(count);
count++;
} while (count < 10)
Example
do {
//statement
}while (test)
Executed
Condition = True
A Simple Approach – Core Java / Session 2/ 27 of 30
Aptech Software Ltd.
Loops 3-3
for
The for loop is primarily used for executing a statement or block of statements a
predetermined number of times.
Syntax
For(count = 0; count
<10; count++) {
System.out.println(coun
t);
}
Example
for(initialization;test;
increment){
action statements;
}
Condition = True
Executed
A Simple Approach – Core Java / Session 2/ 28 of 30
Aptech Software Ltd.
Jump Statements 2-1
 Two jump statements are:
break
continue
break statement: It is used to terminate the block.
continue statement: Sometimes the programmer might
want to continue a loop, but stop processing the
remainder of the code in its body for a particular iteration.
The continue statement can be used for such an action.
A Simple Approach – Core Java / Session 2/ 29 of 30
Aptech Software Ltd.
Jump Statements 2-2
 Introduce break keyword in the loop.
 Avoid Unnecessary execution.
 Terminate the loop.
Demonstration: Additional Example 5
int number = 41;
int is_prime = 1;
for(int i = 2; i * i <= number; i++) {
if((number%i)==0){
is_prime = 0;
break;
}
}
if(is_prime==1) {
System.out.println("It is a prime number");
}
else {
System.out.println("Not a prime number");
}
}
A Simple Approach – Core Java / Session 2/ 30 of 30
Aptech Software Ltd.
Summary
 Java has built-in data types, known as primitive data types.
 Variables are basic units of storage.
 Casting is a facility of converting a data type to another data type.
 Arrays are used to store several items of same data type in consecutive
memory locations.
 Java provides different types of operators. They include:
 Arithmetic
 Relational
 Logical
 Conditional
 Assignment
 Java supports the following programming constructs for the control
statements:
 if - else
 switch
 for
 while
 do - while
 The two jump statements, break and continue, help to transfer control to
another part of the program.

More Related Content

Similar to In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. (20)

PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPT
Java Basics
Brandon Black
 
PPT
java tutorial 2
Tushar Desarda
 
PPT
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
PPTX
CAP615-Unit1.pptx
SatyajeetGaur3
 
PPTX
Object oriented programming2 Week 2.pptx
MirHazarKhan1
 
PPTX
PCSTt11 overview of java
Archana Gopinath
 
PPTX
java Basic Programming Needs
Raja Sekhar
 
PPTX
Core Java introduction | Basics | free course
Kernel Training
 
PPTX
Identifiers, keywords and types
Daman Toor
 
PPTX
Java chapter 2
Abdii Rashid
 
PPTX
Learning Java 2 - Variables, Data Types and Operators
MinhNguyen1493
 
PPT
Unit I Advanced Java Programming Course
parveen837153
 
PPT
object oriented programming java lectures
MSohaib24
 
PPTX
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
PPSX
DITEC - Programming with Java
Rasan Samarasinghe
 
PPT
Ap Power Point Chpt2
dplunkett
 
PPT
Ch02 primitive-data-definite-loops
James Brotsos
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Java Basics
Brandon Black
 
java tutorial 2
Tushar Desarda
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
CAP615-Unit1.pptx
SatyajeetGaur3
 
Object oriented programming2 Week 2.pptx
MirHazarKhan1
 
PCSTt11 overview of java
Archana Gopinath
 
java Basic Programming Needs
Raja Sekhar
 
Core Java introduction | Basics | free course
Kernel Training
 
Identifiers, keywords and types
Daman Toor
 
Java chapter 2
Abdii Rashid
 
Learning Java 2 - Variables, Data Types and Operators
MinhNguyen1493
 
Unit I Advanced Java Programming Course
parveen837153
 
object oriented programming java lectures
MSohaib24
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
DITEC - Programming with Java
Rasan Samarasinghe
 
Ap Power Point Chpt2
dplunkett
 
Ch02 primitive-data-definite-loops
James Brotsos
 

More from Indu32 (12)

PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
PDF
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
Indu32
 
PPTX
Introduction to MySQL commands mysql presentation 22.pptx
Indu32
 
PDF
unit8_jdbc.pdf mysql and java jdbc connection
Indu32
 
PPTX
css front end development , designing web page
Indu32
 
PPTX
CSS presentation for beginners where they can understand easily
Indu32
 
PPTX
html webpage development different tags used
Indu32
 
PPTX
design patter related ppt and presentation
Indu32
 
PPTX
Web development ppt used to design web applocation
Indu32
 
PPTX
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
PPT
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
Indu32
 
PPT
java basic ppt introduction, The Java language is known for its robustness, s...
Indu32
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
Indu32
 
Introduction to MySQL commands mysql presentation 22.pptx
Indu32
 
unit8_jdbc.pdf mysql and java jdbc connection
Indu32
 
css front end development , designing web page
Indu32
 
CSS presentation for beginners where they can understand easily
Indu32
 
html webpage development different tags used
Indu32
 
design patter related ppt and presentation
Indu32
 
Web development ppt used to design web applocation
Indu32
 
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
Indu32
 
java basic ppt introduction, The Java language is known for its robustness, s...
Indu32
 
Ad

Recently uploaded (20)

PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Controller Request and Response in Odoo18
Celine George
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Ad

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.

  • 1. Aptech Software Ltd. Session 2 Java Language Fundamentals
  • 2. A Simple Approach – Core Java / Session 2/ 2 of 30 Aptech Software Ltd. Review  Java was introduced by Sun Microsystems in 1995.  Java is object-oriented and a cross platform language.  Java bytecodes are machine language instructions understood by the Java Virtual Machine (JVM) and usually generated as a result of compiling Java language source code.  A "Just-In-Time" (JIT) Java compiler produces native code from Java byte code instructions during program execution.  Applets are Java programs that run through a Java enabled web browser.The Java Development Kit (JDK) contains the software and tools needed to compile, debug and execute applets and applications written in the Java language. It’s basically a set of command-line tools.  Java program can be run using command-line arguments. The data type of these arguments is String.
  • 3. A Simple Approach – Core Java / Session 2/ 3 of 30 Aptech Software Ltd. Objectives Explain the basics of Java Language Identify the Data Types Understand arrays Identify Operators Format output using Escape Sequence Use Control Flow Statements
  • 4. A Simple Approach – Core Java / Session 2/ 4 of 30 Aptech Software Ltd. Basics of the Java Language Data types Variables Operators Control Flow Statements Java Blocks A variable is a named memory location. Data types determine the type of data to be stored in memory. An operator is a symbol that operates on one or more arguments to produce a result. Programs are executed in sequential order. Control flow statements allow variations in this sequential order.
  • 5. A Simple Approach – Core Java / Session 2/ 5 of 30 Aptech Software Ltd. Data Types  byte  char  boolean  short  int  long  float  double  Array  Class  Interface Primitive Data Types Reference Data Types
  • 6. A Simple Approach – Core Java / Session 2/ 6 of 30 Aptech Software Ltd. Variables Three components of a variable declaration are:  Data type  Name  Initial value to be assigned (optional) Syntax: datatype identifier [=value][, identifier[=value]...];
  • 7. A Simple Approach – Core Java / Session 2/ 7 of 30 Aptech Software Ltd. class VariableTest { public static void main(String [] args) { double a = 1.0; int b = 3; System.out.println("Value of double variable is: "+a); System.out.println("Value of integer variable is: "+b); } } Variable declaration and initialization Example Note: Always initialize your variables when you define them. If you don’t know what value a variable should have when you define it, initialize it to zero. float f;
  • 8. A Simple Approach – Core Java / Session 2/ 8 of 30 Aptech Software Ltd. Scope and Lifetime of Variables Variables can be declared inside a block. The block begins with an opening curly brace and ends with a closing curly brace. A block defines a scope. A new scope is created every time a new block is created. Scope specifies which variables are visible to other parts of the program. It also determines the life of the variables.
  • 9. A Simple Approach – Core Java / Session 2/ 9 of 30 Aptech Software Ltd. class ScopeVariable { public static void main(String[] args) { /* num is available in inner scope */ int num = 2; /* Testing variable num */ if (num == 2) { int num1 = num * num; System.out.println("Value of num and num1 are " + num + " " + num1); } /* num1 = 10; ERROR ! num1 is not known */ System.out.println("Value of num is " + num); } } Example //num1 = 10; ERROR ! num1 is not known  Check the scope of the variables.  ERROR!!! If variable is accessed outside its scope.
  • 10. A Simple Approach – Core Java / Session 2/ 10 of 30 Aptech Software Ltd. Type Casting Type Casting causes the program to treat a variable of one type as though it contains data of another type. Example: float c = 34.89675f; int b = (int) c + 10; // Convert c to an integer
  • 11. A Simple Approach – Core Java / Session 2/ 11 of 30 Aptech Software Ltd. Types of Data Conversion Automatic Type Conversion Casting When one type of data is assigned to a variable of another type, automatic type conversion takes place provided it meets the following conditions: The two types are compatible. The destination type is larger than the source type. Casting is used for explicit type conversion. It loses information above the magnitude of the value being converted.
  • 12. A Simple Approach – Core Java / Session 2/ 12 of 30 Aptech Software Ltd. Example  Declare and initialize the variables  Add the variables and assign the value to the variable of different data type without explicit type casting.  No ERROR!!! long sum; int first = 20, second = 30; sum = first + second; Demonstration: Additional Example 2 Automatic Type Casting Casting  Declare the variables  The variables will hold the values which are passed during runtime.  Add the variable after type casting. int first, second, sum; first = Integer.parseInt(args[0]); second = Integer.parseInt(args[1]); sum = first + second; Demonstration: Additional Example 1
  • 13. A Simple Approach – Core Java / Session 2/ 13 of 30 Aptech Software Ltd. Type Promotion Rules All byte and short values are promoted to int type. If one operand is long, the whole expression is promoted to long. If one operand is float, the whole expression is promoted to float. If one operand is double, the whole expression is promoted to double.
  • 14. A Simple Approach – Core Java / Session 2/ 14 of 30 Aptech Software Ltd. Arrays 1-2  An array is a data structure that stores data of same data type in consecutive memory locations.  Three ways to declare an array are: datatype identifier [ ]; datatype identifier [ ] = new datatype[size]; datatype identifier [ ] = {value1,value2,….valueN};  Array can have more than one dimension
  • 15. A Simple Approach – Core Java / Session 2/ 15 of 30 Aptech Software Ltd. Arrays 2-2  It consists of a single column of data of the same type.  An array is declared by specifying its name and size. One Dimensional Array Multi Dimensional Array  Multi Dimensional arrays are arrays of arrays.  To declare a Multi Dimensional array, additional index has to be specified by using another set of square brackets.
  • 16. A Simple Approach – Core Java / Session 2/ 16 of 30 Aptech Software Ltd. Example  Array Declaration  Accessing the array elements  Using the length property Demonstration: Example 3 and Additional Example 3 /* Array Initialization */ double[] nums = {2, 0, 1}; /* Printing array element */ System.out.println("The value at location 3 is :" + nums[2]); int[] numbers = {8, 18, 5, 2, 1, 10}; System.out.println("Total number of elements in an array is: "+ numbers.length); System.out.println("First element in an array is: " + numbers[0]); System.out.println("Last element in an array is: “ + numbers[numbers.length - 1]);
  • 17. A Simple Approach – Core Java / Session 2/ 17 of 30 Aptech Software Ltd. Operators Operators Description Examples Arithmetic Operators Arithmetic Operators use numeric operands. These operators are mainly used for mathematical calculations. +, - * % etc Relational Operators Relational Operators test the relation between two operands. The result of an expression where relational operators are used is boolean. ==, >=, <= etc Logical Operators Logical Operators work with boolean operands. &, |, ^ etc Conditional Operators The Conditional Operator is unique, because it is a ternary or triadic operator that has three operands to the expression. It can replace certain types of if-then-else statements. !=, =, *=, /=, +=, -= Assignment Operators The Assignment Operator is a single equal sign, =, and assigns a value to a variable. =
  • 18. A Simple Approach – Core Java / Session 2/ 18 of 30 Aptech Software Ltd. Examples Code Snippet: int a= 5, b= 12,d=10,c; c=a+b; Addition c=a%b; Modulus d++; Increment d--; Decrement Value of c and d: c=17 After adding c=2 This is remainder of a/b d=11 After incrementing d=10 After decreasing the value Code Snippet: boolean i=true, j=false; boolean or=i|j, and=i&j; !i; !j; Value of or and and: or=true Using logical or and=false Using logical and i=false Using logical unary not j=true Using logical unary not Arithmetic Operators Logical Operators
  • 19. A Simple Approach – Core Java / Session 2/ 19 of 30 Aptech Software Ltd. Operator Precedence  Expressions that are written will generally consist of several operators. The rules of precedence decide the order in which each operator is evaluated in any given expression. Order Operator 1. Parentheses like ( ) and [ ] 2. Unary Operators like +, -, ++, --, ~, ! 3. Arithmetic and Shift operators like *, /, %, +, -, >>, << 4. Relational Operators like >, >=, <, <=, ==, != 5. Logical Operators like &, ^, |, &&, || 6. Conditional and Assignment Operators like ?=, =, *=, /=, +=, -=
  • 20. A Simple Approach – Core Java / Session 2/ 20 of 30 Aptech Software Ltd. Formatting output with Escape Sequences  Whenever an output is to be displayed on the screen, it needs to be formatted.  The formatting can be done with the help of escape sequences that Java provides. Example: System.out.println (“Happy tBirthday”); Output: Happy Birthday
  • 21. A Simple Approach – Core Java / Session 2/ 21 of 30 Aptech Software Ltd. Control Flow Statements  All application development environments provide a decision making process called control flow statements that direct the application execution.  Control flow enables a developer to create an application that can examine the existing conditions, and decide a suitable course of action.  Loops or iterations are an important programming construct that can be used to repeatedly execute a set of actions.  Jump statements allow the program to execute in a non- linear fashion.
  • 22. A Simple Approach – Core Java / Session 2/ 22 of 30 Aptech Software Ltd. Types of Control Flow Statements Decision-making if-else statement switch-case statement Loops while loop do-while loop for loop
  • 23. A Simple Approach – Core Java / Session 2/ 23 of 30 Aptech Software Ltd. if-else statement  The if-else statement tests the result of a condition, and performs appropriate actions based on the result.  It can be used to route program execution through two different paths.  The syntax of if-else statement is:: if (condition) { action1; } else { action2; }
  • 24. A Simple Approach – Core Java / Session 2/ 24 of 30 Aptech Software Ltd. switch – case statement  The switch – case statement can be used as an alternative for if-else-if statement.  It is used in situations where an expression is evaluated multiple values.  The use of the switch-case statement results in better performance.  The syntax of switch-case is: switch (expression) { case 1: action1 statements; break; case 2': action2statements; break; …. case N ': actionN statements; break; default: default statements; }
  • 25. A Simple Approach – Core Java / Session 2/ 25 of 30 Aptech Software Ltd. Loops 3-1 while The while loop executes a statement or set of statements as long as the condition specified evaluates to true. Syntax int count = 0; while (count < 10) { System.out.println(count); count++; } Example while (test) { // statement } Executed Condition = True
  • 26. A Simple Approach – Core Java / Session 2/ 26 of 30 Aptech Software Ltd. Loops 3-2 do-while The do-while loops execute certain statements till the specified condition is true. This loop ensures that the loop body is executed at least once. Syntax do { System.out.println(count); count++; } while (count < 10) Example do { //statement }while (test) Executed Condition = True
  • 27. A Simple Approach – Core Java / Session 2/ 27 of 30 Aptech Software Ltd. Loops 3-3 for The for loop is primarily used for executing a statement or block of statements a predetermined number of times. Syntax For(count = 0; count <10; count++) { System.out.println(coun t); } Example for(initialization;test; increment){ action statements; } Condition = True Executed
  • 28. A Simple Approach – Core Java / Session 2/ 28 of 30 Aptech Software Ltd. Jump Statements 2-1  Two jump statements are: break continue break statement: It is used to terminate the block. continue statement: Sometimes the programmer might want to continue a loop, but stop processing the remainder of the code in its body for a particular iteration. The continue statement can be used for such an action.
  • 29. A Simple Approach – Core Java / Session 2/ 29 of 30 Aptech Software Ltd. Jump Statements 2-2  Introduce break keyword in the loop.  Avoid Unnecessary execution.  Terminate the loop. Demonstration: Additional Example 5 int number = 41; int is_prime = 1; for(int i = 2; i * i <= number; i++) { if((number%i)==0){ is_prime = 0; break; } } if(is_prime==1) { System.out.println("It is a prime number"); } else { System.out.println("Not a prime number"); } }
  • 30. A Simple Approach – Core Java / Session 2/ 30 of 30 Aptech Software Ltd. Summary  Java has built-in data types, known as primitive data types.  Variables are basic units of storage.  Casting is a facility of converting a data type to another data type.  Arrays are used to store several items of same data type in consecutive memory locations.  Java provides different types of operators. They include:  Arithmetic  Relational  Logical  Conditional  Assignment  Java supports the following programming constructs for the control statements:  if - else  switch  for  while  do - while  The two jump statements, break and continue, help to transfer control to another part of the program.