SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Chapter 2: Basic Elements
of Java
Chapter Objectives
• Become familiar with the basic components of a Java program,
including methods, special symbols, and identifiers.
• Explore primitive data types.
• Discover how to use arithmetic operators.
• Examine how a program evaluates arithmetic expressions.
• Explore how mixed expressions are evaluated.
2
Chapter Objectives
• Learn about type casting.
• Become familiar with the String type.
• Learn what an assignment statement is and what it does.
• Discover how to input data into memory by using input
statements.
• Become familiar with the use of increment and
decrement operators.
3
Chapter Objectives
• Examine ways to output results using output statements.
• Learn how to import packages and why they are
necessary.
• Discover how to create a Java application program.
• Explore how to properly structure a program, including
using comments to document a program.
4
Introduction
• Computer program: A sequence of statements designed
to accomplish a task.
• Programming:The process of planning and creating a
program.
5
The Basics of a Java Program
• Java program: A collection of classes.
• There is a main method in every Java application
program.
• Token:The smallest individual unit of a program.
6
Special Symbols
7
Word Symbols
• int
• float
• double
• char
• void
• public
• static
• throws
• return
8
Java Identifiers
• Names of things.
• Consists of:
• Letters
• Digits
• The underscore character (_)
• The dollar sign ($)
• Must begin with a letter, underscore, or the dollar sign.
9
Illegal Identifiers
10
DataTypes
A set of values together with a set of operations.
11
Primitive DataTypes
12
Primitive DataTypes
• Floating-point data types:
• Float: Precision = 6 or 7
• Double: Precision = 15
• Boolean:
• True
• False
13
Integral DataTypes
14
Values and Memory Allocation for
Integral DataTypes
15
Arithmetic Operators and Operator
Precedence
• Five arithmetic operators:
• + addition
• - subtraction
• * multiplication
• / division
• % mod (modulus)
• Unary operator: An operator that has one operand.
• Binary operator: An operator that has two operands.
16
Order of Precedence
* / % (same precedence)
+ - (same precedence)
• Operators in 1 have a higher precedence than
operators in 2.
• When operators have the same level of precedence,
operations are performed from left to right.
17
Expressions
• Integral expressions
• Floating-point or decimal expressions
• Mixed expressions
18
Integral Expressions
• All operands are integers.
• Examples:
2 + 3 * 5
3 + x – y / 7
x + 2 * (y – z) + 18
19
Floating-Point Expressions
• All operands are floating-point numbers.
• Examples:
12.8 * 17.5 – 34.50
x * 10.5 + y - 16.2
20
Mixed Expressions
• Operands of different types.
• Examples:
2 + 3.5
6 / 4 + 3.9
• Integer operands yield an integer result; floating-point
numbers yield floating-point results.
• If both types of operands are present, the result is a floating-
point number.
• Precedence rules are followed.
21
Type Conversion (Casting)
• Used to avoid implicit type coercion.
• Syntax:
(dataTypeName) expression
• Expression evaluated first, then type converted to:
dataTypeName
• Examples:
(int)(7.9 + 6.7) = 14
(int)(7.9) + (int)(6.7) = 13
22
The class String
• Used to manipulate strings.
• String:
• Sequence of zero or more characters.
• Enclosed in double quotation marks.
• Null or empty strings have no characters.
• Numeric strings consist of integers or decimal numbers.
• Length is the number of characters in a string.
23
Input
Named constant
• Cannot be changed during program execution.
• Declared by using the reserved word final.
• Initialized when it is declared.
Example 2-11
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
24
Input
Variable (name, value, data type, size)
• Content may change during program execution.
• Must be declared before it can be used.
• May not be automatically initialized.
• If new value is assigned, old one is destroyed.
• Value can only be changed by an assignment statement or an
input (read) statement.
Example 2-12
double amountDue;
int counter;
char ch;
int x, y;
25
Input
The Assignment Statement
variable = expression;
Example 2-13
int i, j;
double sale;
char first;
String str;
i = 4;
j = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day."; 26
Input
• Standard input stream object is System.in.
• Input numeric data to program.
• Separate by blanks, lines, or tabs.
• To read data:
1. Create an input stream object of the class Scanner.
2. Use the methods such as next, nextLine, nextInt, and
nextDouble.
27
Input
static Scanner console = new Scanner(System.in);
Example 2-16
static Scanner console = new Scanner(System.in);
int feet;
int inches;
Suppose the input is
23 7
feet = console.nextInt(); //Line 1
inches = console.nextInt(); //Line 2
28
Increment and
Decrement Operators
• ++ increments the value of its operand by 1.
• -- decrements the value of its operand by 1.
• Syntax:
Pre-increment: ++variable
Post-increment: variable++
Pre-decrement: --variable
Post-decrement: variable--
29
Strings and the Operator +
• Operator + can be used to concatenate two strings, or a
string and a numeric value or character.
Example 2-20
String str;
int num1, num2;
num1 = 12;
num2 = 26;
str = "The sum = " + num1 + num2;
After this statement executes, the string assigned to str is:
"The sum = 1226"; 30
Strings and the Operator +
• Example 2-20
String str;
int num1, num2;
num1 = 12;
num2 = 26;
str = "The sum = " + num1 + num2;
After this statement executes, the string assigned to str is:
"The sum = 1226";
• Consider the following statement:
str = "The sum = " + (num1 + num2);
• In this statement, because of the parentheses, you first evaluate
num1 + num2. Because num1 and num2 are both int variables,
num1 + num2 = 12 + 26 = 38. After this statement
executes, the string assigned to str is:
"The sum = 38";
31
Output
• Standard output object is System.out.
• Methods:
print
println
• Syntax:
System.out.print(stringExp);
System.out.println(stringExp);
System.out.println();
32
Commonly Used
Escape Sequences
33
Packages, Classes, Methods, and
the import Statement
• Package: A collection of related classes.
• Class: Consists of methods.
• Method: Designed to accomplish a specific task.
34
import Statement
• Used to import the components of a package into a program.
• Reserved word.
• import java.io.*;
Imports the (components of the) package java.io
into the program.
• Primitive data types and the class String:
• Part of the Java language.
• Don’t need to be imported.
35
Creating a Java
Application Program
• Syntax of a class:
• Syntax of the main method:
36
Programming Style and Form
• Know common syntax errors and rules.
• Use blanks appropriately.
• Use a semicolon as a statement terminator.
• Important to have well-documented code.
• Good practice to follow traditional rules for naming identifiers.
37
More on Assignment Statements
variable = variable * (expression);
is equivalent to:
variable *= expression;
Similarly,
variable = variable + (expression);
is equivalent to:
variable += expression;
38
Programming Examples
• Convert Length program:
• Input: Length in feet and inches.
• Output: Equivalent length in centimeters.
• Make Change program:
• Input: Change in cents.
• Output: Equivalent change in half-dollars, quarters, dimes, nickels,
and pennies.
39
Chapter Summary
• Basic elements of a Java program include:
• The main method
• Reserved words
• Special symbols
• Identifiers
• Data types
• Expressions
• Input
• Output
• Statements
Java Programming: From Problem Analysis to Program Design, Second Edition 40
Chapter Summary
• To create a Java application, it is important to understand:
• Syntax rules.
• Semantic rules.
• How to manipulate strings and numbers.
• How to declare variables and named constants.
• How to receive input and display output.
• Good programming style and form.
Java Programming: From Problem Analysis to Program Design, Second Edition 41

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Software Engineering
Introduction to Software EngineeringIntroduction to Software Engineering
Introduction to Software EngineeringSaqib Raza
 
Incremental model
Incremental modelIncremental model
Incremental modelHpibmx
 
Language and Processors for Requirements Specification
Language and Processors for Requirements SpecificationLanguage and Processors for Requirements Specification
Language and Processors for Requirements Specificationkirupasuchi1996
 
Chapter 1 2 - some size factors
Chapter 1   2 - some size factorsChapter 1   2 - some size factors
Chapter 1 2 - some size factorsNancyBeaulah_R
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming Kamal Acharya
 
Fundamental design concepts
Fundamental design conceptsFundamental design concepts
Fundamental design conceptssrijavel
 
Phased life cycle model
Phased life cycle modelPhased life cycle model
Phased life cycle modelStephennancy
 
Software project estimation
Software project estimationSoftware project estimation
Software project estimationinayat khan
 
Services provided by os
Services provided by osServices provided by os
Services provided by osSumant Diwakar
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer Ashim Lamichhane
 
Software requirements specification
Software requirements specificationSoftware requirements specification
Software requirements specificationlavanya marichamy
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 

Was ist angesagt? (20)

Introduction to Software Engineering
Introduction to Software EngineeringIntroduction to Software Engineering
Introduction to Software Engineering
 
Incremental model
Incremental modelIncremental model
Incremental model
 
Design notation
Design notationDesign notation
Design notation
 
Language and Processors for Requirements Specification
Language and Processors for Requirements SpecificationLanguage and Processors for Requirements Specification
Language and Processors for Requirements Specification
 
Chapter 1 2 - some size factors
Chapter 1   2 - some size factorsChapter 1   2 - some size factors
Chapter 1 2 - some size factors
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
unit testing and debugging
unit testing and debuggingunit testing and debugging
unit testing and debugging
 
Fundamental design concepts
Fundamental design conceptsFundamental design concepts
Fundamental design concepts
 
Rad model
Rad modelRad model
Rad model
 
software engineering
software engineeringsoftware engineering
software engineering
 
Phased life cycle model
Phased life cycle modelPhased life cycle model
Phased life cycle model
 
Software project estimation
Software project estimationSoftware project estimation
Software project estimation
 
Batch operating system
Batch operating system Batch operating system
Batch operating system
 
Services provided by os
Services provided by osServices provided by os
Services provided by os
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 
Software requirements specification
Software requirements specificationSoftware requirements specification
Software requirements specification
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 

Andere mochten auch

C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDDavid Ware
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement Ahmad Idrees
 
Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEDominic Storey
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessmanAhmad Idrees
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing Ahmad Idrees
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer SystemAhmad Idrees
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for BloggersAhmad Idrees
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of businessAhmad Idrees
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing Ahmad Idrees
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer VisionBrian Thorne
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages Ahmad Idrees
 

Andere mochten auch (20)

C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement
 
Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSE
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
 

Ähnlich wie Basic elements of java

Ähnlich wie Basic elements of java (20)

C++ ch2
C++ ch2C++ ch2
C++ ch2
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
 
Java chapter 2
Java chapter 2Java chapter 2
Java chapter 2
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
 
c-programming
c-programmingc-programming
c-programming
 
Basic Elements of C++
Basic Elements of C++Basic Elements of C++
Basic Elements of C++
 
Data structure Unit-I Part A
Data structure Unit-I Part AData structure Unit-I Part A
Data structure Unit-I Part A
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
Unit 1 psp
Unit 1 pspUnit 1 psp
Unit 1 psp
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
Object oriented programming 8 basics of c++ programming
Object oriented programming 8 basics of c++ programmingObject oriented programming 8 basics of c++ programming
Object oriented programming 8 basics of c++ programming
 
C Building Blocks
C Building Blocks C Building Blocks
C Building Blocks
 
Class 2 variables, classes methods...
Class 2   variables, classes methods...Class 2   variables, classes methods...
Class 2 variables, classes methods...
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 

Mehr von Ahmad Idrees

Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer Ahmad Idrees
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's Ahmad Idrees
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information Ahmad Idrees
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle Ahmad Idrees
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures Ahmad Idrees
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutAhmad Idrees
 

Mehr von Ahmad Idrees (8)

Control structures i
Control structures i Control structures i
Control structures i
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
What is business
What is businessWhat is business
What is business
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know about
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Kürzlich hochgeladen (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

Basic elements of java

  • 1. Chapter 2: Basic Elements of Java
  • 2. Chapter Objectives • Become familiar with the basic components of a Java program, including methods, special symbols, and identifiers. • Explore primitive data types. • Discover how to use arithmetic operators. • Examine how a program evaluates arithmetic expressions. • Explore how mixed expressions are evaluated. 2
  • 3. Chapter Objectives • Learn about type casting. • Become familiar with the String type. • Learn what an assignment statement is and what it does. • Discover how to input data into memory by using input statements. • Become familiar with the use of increment and decrement operators. 3
  • 4. Chapter Objectives • Examine ways to output results using output statements. • Learn how to import packages and why they are necessary. • Discover how to create a Java application program. • Explore how to properly structure a program, including using comments to document a program. 4
  • 5. Introduction • Computer program: A sequence of statements designed to accomplish a task. • Programming:The process of planning and creating a program. 5
  • 6. The Basics of a Java Program • Java program: A collection of classes. • There is a main method in every Java application program. • Token:The smallest individual unit of a program. 6
  • 8. Word Symbols • int • float • double • char • void • public • static • throws • return 8
  • 9. Java Identifiers • Names of things. • Consists of: • Letters • Digits • The underscore character (_) • The dollar sign ($) • Must begin with a letter, underscore, or the dollar sign. 9
  • 11. DataTypes A set of values together with a set of operations. 11
  • 13. Primitive DataTypes • Floating-point data types: • Float: Precision = 6 or 7 • Double: Precision = 15 • Boolean: • True • False 13
  • 15. Values and Memory Allocation for Integral DataTypes 15
  • 16. Arithmetic Operators and Operator Precedence • Five arithmetic operators: • + addition • - subtraction • * multiplication • / division • % mod (modulus) • Unary operator: An operator that has one operand. • Binary operator: An operator that has two operands. 16
  • 17. Order of Precedence * / % (same precedence) + - (same precedence) • Operators in 1 have a higher precedence than operators in 2. • When operators have the same level of precedence, operations are performed from left to right. 17
  • 18. Expressions • Integral expressions • Floating-point or decimal expressions • Mixed expressions 18
  • 19. Integral Expressions • All operands are integers. • Examples: 2 + 3 * 5 3 + x – y / 7 x + 2 * (y – z) + 18 19
  • 20. Floating-Point Expressions • All operands are floating-point numbers. • Examples: 12.8 * 17.5 – 34.50 x * 10.5 + y - 16.2 20
  • 21. Mixed Expressions • Operands of different types. • Examples: 2 + 3.5 6 / 4 + 3.9 • Integer operands yield an integer result; floating-point numbers yield floating-point results. • If both types of operands are present, the result is a floating- point number. • Precedence rules are followed. 21
  • 22. Type Conversion (Casting) • Used to avoid implicit type coercion. • Syntax: (dataTypeName) expression • Expression evaluated first, then type converted to: dataTypeName • Examples: (int)(7.9 + 6.7) = 14 (int)(7.9) + (int)(6.7) = 13 22
  • 23. The class String • Used to manipulate strings. • String: • Sequence of zero or more characters. • Enclosed in double quotation marks. • Null or empty strings have no characters. • Numeric strings consist of integers or decimal numbers. • Length is the number of characters in a string. 23
  • 24. Input Named constant • Cannot be changed during program execution. • Declared by using the reserved word final. • Initialized when it is declared. Example 2-11 final double CENTIMETERS_PER_INCH = 2.54; final int NO_OF_STUDENTS = 20; final char BLANK = ' '; final double PAY_RATE = 15.75; 24
  • 25. Input Variable (name, value, data type, size) • Content may change during program execution. • Must be declared before it can be used. • May not be automatically initialized. • If new value is assigned, old one is destroyed. • Value can only be changed by an assignment statement or an input (read) statement. Example 2-12 double amountDue; int counter; char ch; int x, y; 25
  • 26. Input The Assignment Statement variable = expression; Example 2-13 int i, j; double sale; char first; String str; i = 4; j = 4 * 5 - 11; sale = 0.02 * 1000; first = 'D'; str = "It is a sunny day."; 26
  • 27. Input • Standard input stream object is System.in. • Input numeric data to program. • Separate by blanks, lines, or tabs. • To read data: 1. Create an input stream object of the class Scanner. 2. Use the methods such as next, nextLine, nextInt, and nextDouble. 27
  • 28. Input static Scanner console = new Scanner(System.in); Example 2-16 static Scanner console = new Scanner(System.in); int feet; int inches; Suppose the input is 23 7 feet = console.nextInt(); //Line 1 inches = console.nextInt(); //Line 2 28
  • 29. Increment and Decrement Operators • ++ increments the value of its operand by 1. • -- decrements the value of its operand by 1. • Syntax: Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-- 29
  • 30. Strings and the Operator + • Operator + can be used to concatenate two strings, or a string and a numeric value or character. Example 2-20 String str; int num1, num2; num1 = 12; num2 = 26; str = "The sum = " + num1 + num2; After this statement executes, the string assigned to str is: "The sum = 1226"; 30
  • 31. Strings and the Operator + • Example 2-20 String str; int num1, num2; num1 = 12; num2 = 26; str = "The sum = " + num1 + num2; After this statement executes, the string assigned to str is: "The sum = 1226"; • Consider the following statement: str = "The sum = " + (num1 + num2); • In this statement, because of the parentheses, you first evaluate num1 + num2. Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38. After this statement executes, the string assigned to str is: "The sum = 38"; 31
  • 32. Output • Standard output object is System.out. • Methods: print println • Syntax: System.out.print(stringExp); System.out.println(stringExp); System.out.println(); 32
  • 34. Packages, Classes, Methods, and the import Statement • Package: A collection of related classes. • Class: Consists of methods. • Method: Designed to accomplish a specific task. 34
  • 35. import Statement • Used to import the components of a package into a program. • Reserved word. • import java.io.*; Imports the (components of the) package java.io into the program. • Primitive data types and the class String: • Part of the Java language. • Don’t need to be imported. 35
  • 36. Creating a Java Application Program • Syntax of a class: • Syntax of the main method: 36
  • 37. Programming Style and Form • Know common syntax errors and rules. • Use blanks appropriately. • Use a semicolon as a statement terminator. • Important to have well-documented code. • Good practice to follow traditional rules for naming identifiers. 37
  • 38. More on Assignment Statements variable = variable * (expression); is equivalent to: variable *= expression; Similarly, variable = variable + (expression); is equivalent to: variable += expression; 38
  • 39. Programming Examples • Convert Length program: • Input: Length in feet and inches. • Output: Equivalent length in centimeters. • Make Change program: • Input: Change in cents. • Output: Equivalent change in half-dollars, quarters, dimes, nickels, and pennies. 39
  • 40. Chapter Summary • Basic elements of a Java program include: • The main method • Reserved words • Special symbols • Identifiers • Data types • Expressions • Input • Output • Statements Java Programming: From Problem Analysis to Program Design, Second Edition 40
  • 41. Chapter Summary • To create a Java application, it is important to understand: • Syntax rules. • Semantic rules. • How to manipulate strings and numbers. • How to declare variables and named constants. • How to receive input and display output. • Good programming style and form. Java Programming: From Problem Analysis to Program Design, Second Edition 41