SlideShare a Scribd company logo
BIT211
CHAPTER 2
Java Language Fundamentals
Bachelors of Science in Applied Information Technology
© ISBAT UNIVERSITY – 2020. 3/27/2020
Objectives
 Interpret the Java Program
 Understand the basics of Java Language
 Identify the Data Types
 Understand arrays
 Identify the Operators
 Format output using Escape Sequence
© ISBAT UNIVERSITY – 2020. 3/27/2020
A Sample Java program
// This is a simple program called First.java
class First
{
public static void main (String [] args)
{
System.out.println ("My first program in Java ");
}
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Analyzing the Java Program
 The symbol // stands for commented line.
 The line class First declares a new class called First.
 public static void main (String [] args)
 This is the main method from where the program begins its execution.
 System.out.println (“My first program in
java”);
 This line displays the string My first program in java on the screen.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Compiling and executing the Java
program
The java compiler creates a file called 'First.class' that contains the
byte codes
To actually run the program, a java interpreter called java is required to
execute the code.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Passing Command Line Arguments
class CommLineArg
{
public static void main (String [] pargs)
{
System.out.println("These are the arguments
passed to the main method.");
System.out.println(pargs [0]);
System.out.println(pargs [1]);
System.out.println(pargs [2]);
}
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Passing Command Line Arguments
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Basics of the Java Language
 Classes & Methods
 Data types
 Variables
 Operators
 Control structures
© ISBAT UNIVERSITY – 2020. 3/27/2020
Classes in Java
 Class declaration Syntax
class Classname
{
var_datatype variablename;
:
met_datatype methodname(parameter_list)
:
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Sample class
© ISBAT UNIVERSITY – 2020. 3/27/2020
Data Types
 byte
 char
 boolean
 short
 int
 long
 float
 double
 Array
 Class
 Interface
© ISBAT UNIVERSITY – 2020. 3/27/2020
Type Casting
 In type casting, a data type is
converted into another data type.
 Example
float c = 34.89675f;
int b = (int)c + 10;
© ISBAT UNIVERSITY – 2020. 3/27/2020
Automatic type and Casting
 There are two type of data conversion: automatic
type conversion and casting.
 When one type of data is assigned to a variable
of another type then automatic type conversion
takes place provided it meets the conditions
specified:
 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.
© ISBAT UNIVERSITY – 2020. 3/27/2020
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 then the whole
expression is promoted to float.
 If one operand is double then the whole
expression is promoted to double.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Variables
 Three components of a variable declaration
are:
 Data type
 Name
 Initial value to be assigned (optional)
 Syntax
datatype identifier [=value][,
identifier[=value]...];
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
Output
class DynVar
{
public static void main(String [] args)
{
double len = 5.0, wide = 7.0;
double num = Math.sqrt(len * len + wide * wide);
System.out.println("Value of num after dynamic initialization
is " + num);
}
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
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 what objects are visible to other
parts of the program.
 It also determines the life of an object.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class ScopeVar
{
public static void main(String [] args)
{
int num = 10;
if ( num == 10)
{
// num is available in inner scope
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);
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Array Declarations
 Three ways to declare an array are:
 datatype identifier [ ];
 datatype identifier [ ] = new datatype[size];
 datatype identifier [ ] =
{value1,value2,….valueN};
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example – One Dimensional Array
class ArrDemo
{
public static void main(String [] arg)
{
double nums[] = {10.1, 11.3, 12.5,13.7, 14.9};
System.out.println(" The value at location 3 is : " +
nums[3]);
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example – Multi Dimensional Array
class MultiArrayDemo
{
public static void main ( String [] arg)
{
int multi[][] = new int [4][];
multi[0] = new int[1];
multi[1] = new int[2];
multi[2] = new int[3];
multi[3] = new int[4];
int num = 0;
for (int count = 0; count < 4; count++)
{
for (int ctr = 0; ctr < count+1; ctr++)
{
multi[count][ctr] = num;
num++;
}
}
for (int count = 0; count < 4; count++)
{
for (int ctr = 0; ctr < count+1; ctr++)
{
System.out.print(multi[count][ctr] + " ");
System.out.println();
}
}
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Operators
 Arithmetic Operators
 Bitwise Operators
 Relational Operators
 Logical Operators
 Conditional Operators
 Assignment operators
© ISBAT UNIVERSITY – 2020. 3/27/2020
Arithmetic Operators
 Operands of the arithmetic operators must be of
numeric type.
 Boolean operands cannot be used, but character
operands are allowed.
 These operators are used in mathematical
expressions.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class ArithmeticOp
{
public static void main ( String [] arg)
{
int num = 5, num1 = 12, num2 = 20, result;
result = num + num1;
System.out.println("Sum of num and num1 is : (num + num1) " + result);
result = num % num1;
System.out.println("Modulus of num and num1 is : (num % num1) " + result);
result *= num2;
System.out.println("Product of result and num2 is : (result *= num2) " + result);
System.out.println("Value of num before the operation is : " + num);
num ++;
System.out.println("Value of num after ++ operation is : " + num);
double num3 = 25.75, num4 = 14.25, res;
res = num3 - num4;
System.out.println("num3 – num4 is : " +res);
res -= 2.50;
System.out.println("res -= 2.50 " + res);
System.out.println("Value of res before -- operation is : "+ res);
res--;
System.out.println("Value of res after -- operation is : " + res);
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Bitwise Operators
 A bitwise operator allows manipulation of
individual bits in an integral primitive data type.
 These operators act upon the individual bits of
their operands.
 Bitwise operators perform Boolean algebra on
the corresponding bits in the two arguments to
produce the result.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Relational Operators
 Relational operators test the relation between
two operands.
 The result of an expression in which relational
operators are used, is boolean (either true or
false).
 Relational operators are used in control
structures.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class RelOp
{
public static void main(String [] args)
{
float num = 10.0F;
double num1 = 10.0;
if (num == num1)
System.out.println ("num is equal to num1");
else
System.out.println ("num is not equal to num1");
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Logical Operators
 Logical operators work with boolean operands.
 Some operators are
 &
 |
 ^
 !
© ISBAT UNIVERSITY – 2020. 3/27/2020
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.
 The code below checks whether a commuter’s age is
greater than 65 and print the message.
CommuterCategory = (CommuterAge >
65)? “Senior Citizen” : “Regular”;
© ISBAT UNIVERSITY – 2020. 3/27/2020
Assignment Operators
 The assignment operator is a single equal sign, =,
and assigns a value to a variable.
 Assigning values to more than one variable can be
done at a time.
 In other words, it allows us to create a chain of
assignments.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Operator Precedence
 Parentheses: ( ) and [ ]
 Unary Operators: +, -, ++, --, ~, !
 Arithmetic and Shift operators: *, /, %, +, -, >>, <<
 Relational Operators: >, >=, <, <=, ==, !=
 Logical and Bitwise Operators: &, ^, |, &&, ||,
 Conditional and Assignment Operators: ?=, =, *=, /=, +=,
-=
 Parentheses are used to change the order in which an
expression is evaluated. Any part of an expression
enclosed in parentheses is evaluated first.
© ISBAT UNIVERSITY – 2020. 3/27/2020
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.
 System.out.println (“Happy tBirthday”);
 Output: Happy Birthday
© ISBAT UNIVERSITY – 2020. 3/27/2020
Control Flow
 All application development environments provide a
decision making process called control flow statements that
direct the application execution.
 Flow control enables a developer to create an application
that can examine the existing conditions, and decide a
suitable course of action.
 Loops or iteration 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.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Control Flow Structures in Java
 Decision-making
 if-else statement
 switch-case statement
 Loops
 while loop
 do-while loop
 for loop
© ISBAT UNIVERSITY – 2020. 3/27/2020
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 format of an if-else statement is very simple and is given
below:
if (condition)
{
action1;
}
else
{
action2;
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class CheckNum
{
public static void main(String [] args)
{
int num = 10;
if (num % 2 == 0)
System.out.println(num + " is an even number");
else
System.out.println(num + " is an odd number");
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
switch – case statement
 The switch – case statement can be used in place of
if-else-if statement.
 It is used in situations where the expression being
evaluated results in multiple values.
 The use of the switch-case statement leads to
simpler code, and better performance.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class SwitchDemo
{
public static void main(String[] args)
{
int day = 4;
String str;
switch (day)
{
case 0:
str = "Sunday";
break;
case 1:
str = "Monday";
break;
case 2:
str = "Tuesday";
break;
case 3:
str = "Wednesday";
break;
case 4:
str = "Thursday";
break;
case 5:
str = "Friday";
break;
case 6:
str = "Saturday";
break;
default:
str = "Invalid day";
}
System.out.println(str);
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
while Loop
 while loops are used for situations when a loop has to be
executed as long as certain condition is True.
 The number of times a loop is to be executed is not pre-
determined, but depends on the condition.
 The syntax is:
while (condition)
{
action statements;
.
.
.}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class FactDemo
{
public static void main(String [] args)
{
int num = 5, fact = 1;
while (num >= 1)
{
fact *= num;
num--;
}
System.out.println("The factorial of 5 is : " + fact);
}
}
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
do – while Loop
 The do-while loop executes certain statements till the
specified condition is True.
 These loops are similar to the while loops, except that a
do-while loop executes at least once, even if the specified
condition is False. The syntax is:
do
{
action statements;
.
.
} while (condition);
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class DoWhileDemo
{
public static void main(String [] args)
{
int count = 1, sum = 0;
do
{
sum += count;
count++;
}while (count <= 100);
System.out.println("The sum of first 100 numbers
is : " + sum);
}
}
The sum of first 100 numbers is : 5050
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
for Loop
 All loops have some common features: a counter variable that is initialized
before the loop begins, a condition that tests the counter variable and a
statement that modifies the value of the counter variable.
 The for loop provides a compact format for incorporating these features.
Syntax:
for (initialization statements; condition; increment / decrement statements)
{
action statements;
.
.
}
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class ForDemo
{
public static void main(String [] args)
{
int count = 1, sum = 0;
for (count = 1; count <= 10; count += 2)
{
sum += count;
}
System.out.println("The sum of first 5 odd numbers is
: " + sum);
}
}
The sum of first 5 odd numbers is : 25
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Jump Statements
 Three jump statements are:
 break
 continue
 return
 The three uses of break statements are:
 It terminates a statement sequence in a switch
statement.
 It can be used to exit a loop.
 It is another form of goto.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Example
class BrDemoAppl
{
public static void main(String [] args)
{
for (int count = 1; count <= 100; count++)
{
if (count == 10)
break;
System.out.println("The value of num is : " + count);
}
System.out.println("The loop is over");
}
}
The value of num is : 1
The value of num is : 2
The value of num is : 3
The value of num is : 4
The value of num is : 5
The value of num is : 6
The value of num is : 7
The value of num is : 8
The value of num is : 9
The loop is over
Output
© ISBAT UNIVERSITY – 2020. 3/27/2020
Summary
 A Java program consists of a set of classes. A program may contain
comments. The compiler ignores this commented lines.
 The Java program must have a main() method from where it begins its
execution.
 Classes define a template for units that store data and code related to an
entity.
 Variables defined in a class are called the instance variables.
 There are two types of casting:widening and narrowing casting.
 Variables are basic unit of storage.
 Each variable has a scope and lifetime.
 Arrays are used to store several items of same data type in consecutive
memory locations.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Summary Contd…
 Java provides different types of operators. They include:
 Arithmetic
 Bitwise
 Relational
 Logical
 Conditional
 Assignment
 Java supports the following programming constructs:
 if-else
 switch
 for
 while
 do-while
 The three jump statements-break,continue and return helps to transfer
control to another part of the program.
© ISBAT UNIVERSITY – 2020. 3/27/2020
Thank you
49

More Related Content

Similar to BIT211_2.pdf

Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
Mahmoud Ouf
 
Final report mobile shop
Final report   mobile shopFinal report   mobile shop
Final report mobile shop
Viditsingh22
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignment
PVS-Studio
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
amitbhachne
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
FALLEE31188
 
SystemVerilog-20041201165354.ppt
SystemVerilog-20041201165354.pptSystemVerilog-20041201165354.ppt
SystemVerilog-20041201165354.ppt
ravi446393
 
17515
1751517515
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
doopagamer
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
Docent Education
 
Aspdot
AspdotAspdot
Verilog presentation final
Verilog presentation finalVerilog presentation final
Verilog presentation final
Ankur Gupta
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
karymadelaneyrenne19
 
IRJET- Switch Case Statements in C
IRJET-  	  Switch Case Statements in CIRJET-  	  Switch Case Statements in C
IRJET- Switch Case Statements in C
IRJET Journal
 
AMAZON STOCK PRICE PREDICTION BY USING SMLT
AMAZON STOCK PRICE PREDICTION BY USING SMLTAMAZON STOCK PRICE PREDICTION BY USING SMLT
AMAZON STOCK PRICE PREDICTION BY USING SMLT
IRJET Journal
 
C programming language
C programming languageC programming language
C programming language
Abin Rimal
 
IRJET- Matrix Multiplication using Strassen’s Method
IRJET-  	  Matrix Multiplication using Strassen’s MethodIRJET-  	  Matrix Multiplication using Strassen’s Method
IRJET- Matrix Multiplication using Strassen’s Method
IRJET Journal
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculations
William Olivier
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
Mahmoud Ouf
 
02.adt
02.adt02.adt

Similar to BIT211_2.pdf (20)

Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Final report mobile shop
Final report   mobile shopFinal report   mobile shop
Final report mobile shop
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignment
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
SystemVerilog-20041201165354.ppt
SystemVerilog-20041201165354.pptSystemVerilog-20041201165354.ppt
SystemVerilog-20041201165354.ppt
 
17515
1751517515
17515
 
OOP Using Java Ch2 all about oop .pptx
OOP Using Java Ch2  all about oop  .pptxOOP Using Java Ch2  all about oop  .pptx
OOP Using Java Ch2 all about oop .pptx
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Aspdot
AspdotAspdot
Aspdot
 
Verilog presentation final
Verilog presentation finalVerilog presentation final
Verilog presentation final
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
IRJET- Switch Case Statements in C
IRJET-  	  Switch Case Statements in CIRJET-  	  Switch Case Statements in C
IRJET- Switch Case Statements in C
 
AMAZON STOCK PRICE PREDICTION BY USING SMLT
AMAZON STOCK PRICE PREDICTION BY USING SMLTAMAZON STOCK PRICE PREDICTION BY USING SMLT
AMAZON STOCK PRICE PREDICTION BY USING SMLT
 
C programming language
C programming languageC programming language
C programming language
 
IRJET- Matrix Multiplication using Strassen’s Method
IRJET-  	  Matrix Multiplication using Strassen’s MethodIRJET-  	  Matrix Multiplication using Strassen’s Method
IRJET- Matrix Multiplication using Strassen’s Method
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculations
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 
02.adt
02.adt02.adt
02.adt
 

Recently uploaded

DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 

BIT211_2.pdf

  • 1. BIT211 CHAPTER 2 Java Language Fundamentals Bachelors of Science in Applied Information Technology
  • 2. © ISBAT UNIVERSITY – 2020. 3/27/2020 Objectives  Interpret the Java Program  Understand the basics of Java Language  Identify the Data Types  Understand arrays  Identify the Operators  Format output using Escape Sequence
  • 3. © ISBAT UNIVERSITY – 2020. 3/27/2020 A Sample Java program // This is a simple program called First.java class First { public static void main (String [] args) { System.out.println ("My first program in Java "); } }
  • 4. © ISBAT UNIVERSITY – 2020. 3/27/2020 Analyzing the Java Program  The symbol // stands for commented line.  The line class First declares a new class called First.  public static void main (String [] args)  This is the main method from where the program begins its execution.  System.out.println (“My first program in java”);  This line displays the string My first program in java on the screen.
  • 5. © ISBAT UNIVERSITY – 2020. 3/27/2020 Compiling and executing the Java program The java compiler creates a file called 'First.class' that contains the byte codes To actually run the program, a java interpreter called java is required to execute the code.
  • 6. © ISBAT UNIVERSITY – 2020. 3/27/2020 Passing Command Line Arguments class CommLineArg { public static void main (String [] pargs) { System.out.println("These are the arguments passed to the main method."); System.out.println(pargs [0]); System.out.println(pargs [1]); System.out.println(pargs [2]); } }
  • 7. © ISBAT UNIVERSITY – 2020. 3/27/2020 Passing Command Line Arguments Output
  • 8. © ISBAT UNIVERSITY – 2020. 3/27/2020 Basics of the Java Language  Classes & Methods  Data types  Variables  Operators  Control structures
  • 9. © ISBAT UNIVERSITY – 2020. 3/27/2020 Classes in Java  Class declaration Syntax class Classname { var_datatype variablename; : met_datatype methodname(parameter_list) : }
  • 10. © ISBAT UNIVERSITY – 2020. 3/27/2020 Sample class
  • 11. © ISBAT UNIVERSITY – 2020. 3/27/2020 Data Types  byte  char  boolean  short  int  long  float  double  Array  Class  Interface
  • 12. © ISBAT UNIVERSITY – 2020. 3/27/2020 Type Casting  In type casting, a data type is converted into another data type.  Example float c = 34.89675f; int b = (int)c + 10;
  • 13. © ISBAT UNIVERSITY – 2020. 3/27/2020 Automatic type and Casting  There are two type of data conversion: automatic type conversion and casting.  When one type of data is assigned to a variable of another type then automatic type conversion takes place provided it meets the conditions specified:  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.
  • 14. © ISBAT UNIVERSITY – 2020. 3/27/2020 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 then the whole expression is promoted to float.  If one operand is double then the whole expression is promoted to double.
  • 15. © ISBAT UNIVERSITY – 2020. 3/27/2020 Variables  Three components of a variable declaration are:  Data type  Name  Initial value to be assigned (optional)  Syntax datatype identifier [=value][, identifier[=value]...];
  • 16. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example Output class DynVar { public static void main(String [] args) { double len = 5.0, wide = 7.0; double num = Math.sqrt(len * len + wide * wide); System.out.println("Value of num after dynamic initialization is " + num); } }
  • 17. © ISBAT UNIVERSITY – 2020. 3/27/2020 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 what objects are visible to other parts of the program.  It also determines the life of an object.
  • 18. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class ScopeVar { public static void main(String [] args) { int num = 10; if ( num == 10) { // num is available in inner scope 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); } } Output
  • 19. © ISBAT UNIVERSITY – 2020. 3/27/2020 Array Declarations  Three ways to declare an array are:  datatype identifier [ ];  datatype identifier [ ] = new datatype[size];  datatype identifier [ ] = {value1,value2,….valueN};
  • 20. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example – One Dimensional Array class ArrDemo { public static void main(String [] arg) { double nums[] = {10.1, 11.3, 12.5,13.7, 14.9}; System.out.println(" The value at location 3 is : " + nums[3]); } } Output
  • 21. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example – Multi Dimensional Array class MultiArrayDemo { public static void main ( String [] arg) { int multi[][] = new int [4][]; multi[0] = new int[1]; multi[1] = new int[2]; multi[2] = new int[3]; multi[3] = new int[4]; int num = 0; for (int count = 0; count < 4; count++) { for (int ctr = 0; ctr < count+1; ctr++) { multi[count][ctr] = num; num++; } } for (int count = 0; count < 4; count++) { for (int ctr = 0; ctr < count+1; ctr++) { System.out.print(multi[count][ctr] + " "); System.out.println(); } } } } Output
  • 22. © ISBAT UNIVERSITY – 2020. 3/27/2020 Operators  Arithmetic Operators  Bitwise Operators  Relational Operators  Logical Operators  Conditional Operators  Assignment operators
  • 23. © ISBAT UNIVERSITY – 2020. 3/27/2020 Arithmetic Operators  Operands of the arithmetic operators must be of numeric type.  Boolean operands cannot be used, but character operands are allowed.  These operators are used in mathematical expressions.
  • 24. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class ArithmeticOp { public static void main ( String [] arg) { int num = 5, num1 = 12, num2 = 20, result; result = num + num1; System.out.println("Sum of num and num1 is : (num + num1) " + result); result = num % num1; System.out.println("Modulus of num and num1 is : (num % num1) " + result); result *= num2; System.out.println("Product of result and num2 is : (result *= num2) " + result); System.out.println("Value of num before the operation is : " + num); num ++; System.out.println("Value of num after ++ operation is : " + num); double num3 = 25.75, num4 = 14.25, res; res = num3 - num4; System.out.println("num3 – num4 is : " +res); res -= 2.50; System.out.println("res -= 2.50 " + res); System.out.println("Value of res before -- operation is : "+ res); res--; System.out.println("Value of res after -- operation is : " + res); } } Output
  • 25. © ISBAT UNIVERSITY – 2020. 3/27/2020 Bitwise Operators  A bitwise operator allows manipulation of individual bits in an integral primitive data type.  These operators act upon the individual bits of their operands.  Bitwise operators perform Boolean algebra on the corresponding bits in the two arguments to produce the result.
  • 26. © ISBAT UNIVERSITY – 2020. 3/27/2020 Relational Operators  Relational operators test the relation between two operands.  The result of an expression in which relational operators are used, is boolean (either true or false).  Relational operators are used in control structures.
  • 27. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class RelOp { public static void main(String [] args) { float num = 10.0F; double num1 = 10.0; if (num == num1) System.out.println ("num is equal to num1"); else System.out.println ("num is not equal to num1"); } } Output
  • 28. © ISBAT UNIVERSITY – 2020. 3/27/2020 Logical Operators  Logical operators work with boolean operands.  Some operators are  &  |  ^  !
  • 29. © ISBAT UNIVERSITY – 2020. 3/27/2020 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.  The code below checks whether a commuter’s age is greater than 65 and print the message. CommuterCategory = (CommuterAge > 65)? “Senior Citizen” : “Regular”;
  • 30. © ISBAT UNIVERSITY – 2020. 3/27/2020 Assignment Operators  The assignment operator is a single equal sign, =, and assigns a value to a variable.  Assigning values to more than one variable can be done at a time.  In other words, it allows us to create a chain of assignments.
  • 31. © ISBAT UNIVERSITY – 2020. 3/27/2020 Operator Precedence  Parentheses: ( ) and [ ]  Unary Operators: +, -, ++, --, ~, !  Arithmetic and Shift operators: *, /, %, +, -, >>, <<  Relational Operators: >, >=, <, <=, ==, !=  Logical and Bitwise Operators: &, ^, |, &&, ||,  Conditional and Assignment Operators: ?=, =, *=, /=, +=, -=  Parentheses are used to change the order in which an expression is evaluated. Any part of an expression enclosed in parentheses is evaluated first.
  • 32. © ISBAT UNIVERSITY – 2020. 3/27/2020 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.  System.out.println (“Happy tBirthday”);  Output: Happy Birthday
  • 33. © ISBAT UNIVERSITY – 2020. 3/27/2020 Control Flow  All application development environments provide a decision making process called control flow statements that direct the application execution.  Flow control enables a developer to create an application that can examine the existing conditions, and decide a suitable course of action.  Loops or iteration 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.
  • 34. © ISBAT UNIVERSITY – 2020. 3/27/2020 Control Flow Structures in Java  Decision-making  if-else statement  switch-case statement  Loops  while loop  do-while loop  for loop
  • 35. © ISBAT UNIVERSITY – 2020. 3/27/2020 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 format of an if-else statement is very simple and is given below: if (condition) { action1; } else { action2; }
  • 36. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class CheckNum { public static void main(String [] args) { int num = 10; if (num % 2 == 0) System.out.println(num + " is an even number"); else System.out.println(num + " is an odd number"); } } Output
  • 37. © ISBAT UNIVERSITY – 2020. 3/27/2020 switch – case statement  The switch – case statement can be used in place of if-else-if statement.  It is used in situations where the expression being evaluated results in multiple values.  The use of the switch-case statement leads to simpler code, and better performance.
  • 38. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class SwitchDemo { public static void main(String[] args) { int day = 4; String str; switch (day) { case 0: str = "Sunday"; break; case 1: str = "Monday"; break; case 2: str = "Tuesday"; break; case 3: str = "Wednesday"; break; case 4: str = "Thursday"; break; case 5: str = "Friday"; break; case 6: str = "Saturday"; break; default: str = "Invalid day"; } System.out.println(str); } } Output
  • 39. © ISBAT UNIVERSITY – 2020. 3/27/2020 while Loop  while loops are used for situations when a loop has to be executed as long as certain condition is True.  The number of times a loop is to be executed is not pre- determined, but depends on the condition.  The syntax is: while (condition) { action statements; . . .}
  • 40. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class FactDemo { public static void main(String [] args) { int num = 5, fact = 1; while (num >= 1) { fact *= num; num--; } System.out.println("The factorial of 5 is : " + fact); } } Output
  • 41. © ISBAT UNIVERSITY – 2020. 3/27/2020 do – while Loop  The do-while loop executes certain statements till the specified condition is True.  These loops are similar to the while loops, except that a do-while loop executes at least once, even if the specified condition is False. The syntax is: do { action statements; . . } while (condition);
  • 42. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class DoWhileDemo { public static void main(String [] args) { int count = 1, sum = 0; do { sum += count; count++; }while (count <= 100); System.out.println("The sum of first 100 numbers is : " + sum); } } The sum of first 100 numbers is : 5050 Output
  • 43. © ISBAT UNIVERSITY – 2020. 3/27/2020 for Loop  All loops have some common features: a counter variable that is initialized before the loop begins, a condition that tests the counter variable and a statement that modifies the value of the counter variable.  The for loop provides a compact format for incorporating these features. Syntax: for (initialization statements; condition; increment / decrement statements) { action statements; . . }
  • 44. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class ForDemo { public static void main(String [] args) { int count = 1, sum = 0; for (count = 1; count <= 10; count += 2) { sum += count; } System.out.println("The sum of first 5 odd numbers is : " + sum); } } The sum of first 5 odd numbers is : 25 Output
  • 45. © ISBAT UNIVERSITY – 2020. 3/27/2020 Jump Statements  Three jump statements are:  break  continue  return  The three uses of break statements are:  It terminates a statement sequence in a switch statement.  It can be used to exit a loop.  It is another form of goto.
  • 46. © ISBAT UNIVERSITY – 2020. 3/27/2020 Example class BrDemoAppl { public static void main(String [] args) { for (int count = 1; count <= 100; count++) { if (count == 10) break; System.out.println("The value of num is : " + count); } System.out.println("The loop is over"); } } The value of num is : 1 The value of num is : 2 The value of num is : 3 The value of num is : 4 The value of num is : 5 The value of num is : 6 The value of num is : 7 The value of num is : 8 The value of num is : 9 The loop is over Output
  • 47. © ISBAT UNIVERSITY – 2020. 3/27/2020 Summary  A Java program consists of a set of classes. A program may contain comments. The compiler ignores this commented lines.  The Java program must have a main() method from where it begins its execution.  Classes define a template for units that store data and code related to an entity.  Variables defined in a class are called the instance variables.  There are two types of casting:widening and narrowing casting.  Variables are basic unit of storage.  Each variable has a scope and lifetime.  Arrays are used to store several items of same data type in consecutive memory locations.
  • 48. © ISBAT UNIVERSITY – 2020. 3/27/2020 Summary Contd…  Java provides different types of operators. They include:  Arithmetic  Bitwise  Relational  Logical  Conditional  Assignment  Java supports the following programming constructs:  if-else  switch  for  while  do-while  The three jump statements-break,continue and return helps to transfer control to another part of the program.
  • 49. © ISBAT UNIVERSITY – 2020. 3/27/2020 Thank you 49