SlideShare uma empresa Scribd logo
1 de 18
JAVA BASICS

  VARIABLES
Objectives
1. Understand how to use variables

2. Recognise the different datatypes

1. Use a range of arithmetic operators

2. Learn how to call a subroutine

3. Learn how to round a number

4. Become more confident writing your original
   JAVA programs
Using Variables
           1. What will the output be for this code?   The answer is: 17


public class AddingExample
{                                                             Before you can use them in your code
   public static void main(String[] args)                     you must declare your variables. This
   {                                                          includes writing two things:
      int num1; // declaring the variables
      int num2;                                               The DATATYPE of the variable (e.g int)
      int result;                                             The IDENTIFIER (name) of the variable


        num1 = 10; // assigning values to the variables                       Once declared you
        num2 = 7;                                                             can then just use the
        result = num1 + num2;                                                 identifier to change
                                                                              the value or use it in
        System.out.println(“The answer is: ” + result);                       calculation etc
    }
}
Using variables
When you declare a variable the computer:                           MEMORY
  • Allocates some memory large enough to hold the data             num1
  • Assigns that memory block the identifier you entered
                                                                    result


                                                                    num2




When you assign a value with the = sign                             MEMORY
   • The value is stored in the memory location for that variable   num1     10
                                                                    result   17


                                                                    num2     7
Datatypes
             There are several datatypes you can use
 Data type                 Description                   Example          Storage required

                Stores a collection of characters                        Varies depending
String                                                 “Computer”
                (numbers, text etc.)                                      on no. of chars
                A single character (text, number,
char                                                    „6‟, „F‟, etc           1 byte
                symbol etc)

int             A whole number                               5                 2 bytes

double          A decimal number                             2.5               4 bytes

boolean         Stores either TRUE or FALSE                 TRUE                1 byte


      String greeting = “Hello";              The first two lines of code to the left declare
                                              a variable AND then assign a value to them.
      boolean passed = false;
                                              The last example would have a value
      double percentageScore;                 assigned later in the program
Creating text variables
1. What is the name of the class?
                                      public class StringVariables
 StringVariables
                                      {
2. What are the names of the             public static void main(String[] args)
variables?                               {
 greeting, name                                String greeting = “Hello";
                                               System.out.println( greeting );
3. What is the data type for these
variables                                      String name = “Computing Students";
 String (which means text)                     System.out.println( name );
                                         }
4. What will the output be for this   }
code?
 Hello                                When this program is run:
 Computing Students
                                        • A variable called „greeting‟ is made and the value
                                          Hello is assigned to it on the same line.
                                        • The value assigned to greeting is printed out
                                        • This is repeated for a new variable called „name‟
More complex text variables
  1. What will the output be for this code?   Hi, my name is Billy



   public class MoreMessages                           When used like this
   {                                                   the ‘=‘ is called the
                                                      assignment operator
      public static void main(String[] args)
      {
            String myName = “Billy";
            System.out.println("Hi, my name is " + myName);
      }
   }


                                          The ‘+’ symbol is used to join
                                             pieces of text together
Numerical Variables
        1. What will the output be for this code?   The answer is: 17

public class AddingExample
{
   public static void main(String[] args)
   {
      int num1; // declaring the variables
      int num2;
      int result;

          num1 = 10; // assigning values to the variables
          num2 = 7;
          result = num1 + num2;

          System.out.println(“The answer is: ” + result);
    }
}
Ex 2.1 – Simple Arithmetic
Aim: Create a simple program that adds two numbers


Description
Write a program called Arithmetic1.java that calculates the sum
3.5 + 3.75.

                                                   HINT
                                                   Think about the correct
                                                   datatypes.

                                                   Look at the previous slide
                                                   for some guidance.




Difficulty rating

                               Skills: Use of variables, arithmetic & datatypes
Arithmetic Operations
    Operation         Symbol               Meaning                   Examples

Addition                +                                            13 + 2 = 15

Subtraction             -                                            13 – 5 = 8

Multiplication          *                                            6 * 6 = 36

                                                                     13 / 5 = 2.6
                               The result can be a decimal
Ordinary Division       /                                            15 / 3 = 5.0
                               number
                                                                     2 / 9 = 0.222

                                                                     13 DIV 5 = 2
                               the result is just the integer part
Quotient (division)    DIV                                           15 DIV 3 = 5
                               of the actual answer
                                                                     2 DIV 9 = 0

                                                                     13 DIV 5 = 3
Remainder                      The result is the remainder of the
                       MOD                                           15 DIV 3 = 0
(division)                     calculation
                                                                     2 DIV 9 = 2
Ex 2.2 – Multiple Arithmetic
Aim: Create a program that performs a range of arithmetic calculations


Description
Write a program called Arithmetic2.java that takes 2 variables
with the values 15 and 5 and produces the following output:

Output
                                                    HINT
                                                    You will need 3 variables
                                                    (that you can reuse for
                                                    each calculation)

                                                    1.   num1
                                                    2.   num
                                                    3.   answer


Difficulty rating

                                Skills: Use of variables &arithmetic statements
Ex 2.3 – Kelly Koms Telephone bill
Aim: Create a program that works out a person’s phone bill


Description
Write a program that breaks down and works out the total of a persons
phone bill. It should show them the output below:

Output
                             Use the data:
                             352 texts at 8p        116 mins at 12p

                              HINT
                              It is best to have 3 separate variables for the different
                              totals.

                              Look at slide 7 for how to output Strings and variables
                              (Use “n” to space out your output)


Difficulty rating

                                 Skills: Use of arithmetic & concatenating Strings
Ex 2.4 – BMI
Aim: Create a program that works out a person’s BMI


Description
Write a program called SimpleBMI.java that works out the BMI of
someone who is 1.80m and 70kg.

The calculation is: BMI = weight / ( height 2 )

Output




On the next slide we will look at how to round up the value to two decimal places. Don‟t
worry about this until you have completed this program



Difficulty rating

                                       Skills: Use of variables &arithmetic statements
Rounding Numbers

                                                        This is where the subroutine „round‟ is
                                                        being called by using it‟s name. In
                                                        brackets it has the value to be rounded
                                                        (bmi) and the number of decimal places
                                                        to round it to (2)




The code circled in green is a subroutine called ‘round’ that rounds a value to a set number of
decimal places. This subroutine requires two pieces of data (parameters) before it will work.
                                 double d – The value to be rounded,
                                 int decimalPlace – the number of decimal places to round to.
                                It will ‘return’ a value that has been rounded up

Remember a subroutine won‟t do anything unless it is „called‟ inside the main subroutine. (line 13)
More on calling subroutines
                                       You can see the code to
                                       the left has 3 subroutines.
                                       Starting on lines 9, 18 & 27.

                                       There is only 1 line of code
                                       in the main subroutine.


                                       Calling a subroutine

                                       When we 'call a subroutine
                                       we use it‟s IDENTIFIER (it‟s
                                       name). As seen on line 29

                                       When       the    code   is
                                       executed it will go to the
                                       main method. When it gets
                                       to line 29 the computer will
                                       execute lines 9 – 16.

                                       As subtractingSubRoutine
                                       is NOT CALLED anywhere it
           (remember this is the       will NOT GET EXECUTED.
           ONLY subroutine that
           automatically executes
           when the program is run).
Ex 2.5 – Exam mark
Aim: Create a program that works out a students % score for different 3
tests
Description
Write a program called Test.java that works out the % score of 3 different
tests.

Output
                                  Use the data:
                                  Test 1: 10.5/20      Test 2: 17/20     Test 3: 77/98

                                   HINT
                                   Do the first test and try to run and compile it. Then
                                   do the other tests.

                                   Notice there is something different between the
                                   first test score and the last 2.


Difficulty rating

                                 Skills: Use of arithmetic, datatypes & rounding
Some important things to note
When writing code it is good to break up a larger programs into
small subroutines as this makes it easier to write, debug and
understand.
(For now most of your programs are small enough be written
directly in the main subroutine).



Before using variables you must declare them first. This involves
supplying the datatype and it‟s identifier.
Some important things to note
When working out an arithmetic calculation and storing as a
double at least one of the variables involved in the calculation
has to be stored as a double (even if it is in fact just an integer.

int num1 = 3;                         This would NOT work as
Int num2 = 5;                         neither of the variables being
double result = num1 / num2           divided are stored as doubles




int num1 = 3;                         This would work as num2 is
                                      stored as a double (even
double num2 = 5;                      though 5 is an integer we still
double result = num1 / num2           have to store it as a double)

Mais conteúdo relacionado

Mais procurados

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 

Mais procurados (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Java Notes
Java NotesJava Notes
Java Notes
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
M C6java3
M C6java3M C6java3
M C6java3
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 

Semelhante a Java basics variables

5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constantsCtOlaf
 
Programming in Java: Storing Data
Programming in Java: Storing DataProgramming in Java: Storing Data
Programming in Java: Storing DataMartin Chapman
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variablesmaznabili
 
Lecture # 1 introduction revision - 1
Lecture # 1   introduction  revision - 1Lecture # 1   introduction  revision - 1
Lecture # 1 introduction revision - 1SajeelSahil
 
UNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCAUNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCARaj vardhan
 
Variables 9 cm604.7
Variables 9 cm604.7Variables 9 cm604.7
Variables 9 cm604.7myrajendra
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamentalGanesh Chittalwar
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming Zul Aiman
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and VariablesTommy Vercety
 

Semelhante a Java basics variables (20)

C++ basics
C++ basicsC++ basics
C++ basics
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
Python Guide.pptx
Python Guide.pptxPython Guide.pptx
Python Guide.pptx
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
M C6java2
M C6java2M C6java2
M C6java2
 
Programming in Java: Storing Data
Programming in Java: Storing DataProgramming in Java: Storing Data
Programming in Java: Storing Data
 
Input output
Input outputInput output
Input output
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
Lecture # 1 introduction revision - 1
Lecture # 1   introduction  revision - 1Lecture # 1   introduction  revision - 1
Lecture # 1 introduction revision - 1
 
UNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCAUNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCA
 
Variables 9 cm604.7
Variables 9 cm604.7Variables 9 cm604.7
Variables 9 cm604.7
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
Comp102 lec 4
Comp102   lec 4Comp102   lec 4
Comp102 lec 4
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 

Último

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 

Último (20)

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 

Java basics variables

  • 1. JAVA BASICS VARIABLES
  • 2. Objectives 1. Understand how to use variables 2. Recognise the different datatypes 1. Use a range of arithmetic operators 2. Learn how to call a subroutine 3. Learn how to round a number 4. Become more confident writing your original JAVA programs
  • 3. Using Variables 1. What will the output be for this code? The answer is: 17 public class AddingExample { Before you can use them in your code public static void main(String[] args) you must declare your variables. This { includes writing two things: int num1; // declaring the variables int num2; The DATATYPE of the variable (e.g int) int result; The IDENTIFIER (name) of the variable num1 = 10; // assigning values to the variables Once declared you num2 = 7; can then just use the result = num1 + num2; identifier to change the value or use it in System.out.println(“The answer is: ” + result); calculation etc } }
  • 4. Using variables When you declare a variable the computer: MEMORY • Allocates some memory large enough to hold the data num1 • Assigns that memory block the identifier you entered result num2 When you assign a value with the = sign MEMORY • The value is stored in the memory location for that variable num1 10 result 17 num2 7
  • 5. Datatypes There are several datatypes you can use Data type Description Example Storage required Stores a collection of characters Varies depending String “Computer” (numbers, text etc.) on no. of chars A single character (text, number, char „6‟, „F‟, etc 1 byte symbol etc) int A whole number 5 2 bytes double A decimal number 2.5 4 bytes boolean Stores either TRUE or FALSE TRUE 1 byte String greeting = “Hello"; The first two lines of code to the left declare a variable AND then assign a value to them. boolean passed = false; The last example would have a value double percentageScore; assigned later in the program
  • 6. Creating text variables 1. What is the name of the class? public class StringVariables StringVariables { 2. What are the names of the public static void main(String[] args) variables? { greeting, name String greeting = “Hello"; System.out.println( greeting ); 3. What is the data type for these variables String name = “Computing Students"; String (which means text) System.out.println( name ); } 4. What will the output be for this } code? Hello When this program is run: Computing Students • A variable called „greeting‟ is made and the value Hello is assigned to it on the same line. • The value assigned to greeting is printed out • This is repeated for a new variable called „name‟
  • 7. More complex text variables 1. What will the output be for this code? Hi, my name is Billy public class MoreMessages When used like this { the ‘=‘ is called the assignment operator public static void main(String[] args) { String myName = “Billy"; System.out.println("Hi, my name is " + myName); } } The ‘+’ symbol is used to join pieces of text together
  • 8. Numerical Variables 1. What will the output be for this code? The answer is: 17 public class AddingExample { public static void main(String[] args) { int num1; // declaring the variables int num2; int result; num1 = 10; // assigning values to the variables num2 = 7; result = num1 + num2; System.out.println(“The answer is: ” + result); } }
  • 9. Ex 2.1 – Simple Arithmetic Aim: Create a simple program that adds two numbers Description Write a program called Arithmetic1.java that calculates the sum 3.5 + 3.75. HINT Think about the correct datatypes. Look at the previous slide for some guidance. Difficulty rating Skills: Use of variables, arithmetic & datatypes
  • 10. Arithmetic Operations Operation Symbol Meaning Examples Addition + 13 + 2 = 15 Subtraction - 13 – 5 = 8 Multiplication * 6 * 6 = 36 13 / 5 = 2.6 The result can be a decimal Ordinary Division / 15 / 3 = 5.0 number 2 / 9 = 0.222 13 DIV 5 = 2 the result is just the integer part Quotient (division) DIV 15 DIV 3 = 5 of the actual answer 2 DIV 9 = 0 13 DIV 5 = 3 Remainder The result is the remainder of the MOD 15 DIV 3 = 0 (division) calculation 2 DIV 9 = 2
  • 11. Ex 2.2 – Multiple Arithmetic Aim: Create a program that performs a range of arithmetic calculations Description Write a program called Arithmetic2.java that takes 2 variables with the values 15 and 5 and produces the following output: Output HINT You will need 3 variables (that you can reuse for each calculation) 1. num1 2. num 3. answer Difficulty rating Skills: Use of variables &arithmetic statements
  • 12. Ex 2.3 – Kelly Koms Telephone bill Aim: Create a program that works out a person’s phone bill Description Write a program that breaks down and works out the total of a persons phone bill. It should show them the output below: Output Use the data: 352 texts at 8p 116 mins at 12p HINT It is best to have 3 separate variables for the different totals. Look at slide 7 for how to output Strings and variables (Use “n” to space out your output) Difficulty rating Skills: Use of arithmetic & concatenating Strings
  • 13. Ex 2.4 – BMI Aim: Create a program that works out a person’s BMI Description Write a program called SimpleBMI.java that works out the BMI of someone who is 1.80m and 70kg. The calculation is: BMI = weight / ( height 2 ) Output On the next slide we will look at how to round up the value to two decimal places. Don‟t worry about this until you have completed this program Difficulty rating Skills: Use of variables &arithmetic statements
  • 14. Rounding Numbers This is where the subroutine „round‟ is being called by using it‟s name. In brackets it has the value to be rounded (bmi) and the number of decimal places to round it to (2) The code circled in green is a subroutine called ‘round’ that rounds a value to a set number of decimal places. This subroutine requires two pieces of data (parameters) before it will work. double d – The value to be rounded, int decimalPlace – the number of decimal places to round to. It will ‘return’ a value that has been rounded up Remember a subroutine won‟t do anything unless it is „called‟ inside the main subroutine. (line 13)
  • 15. More on calling subroutines You can see the code to the left has 3 subroutines. Starting on lines 9, 18 & 27. There is only 1 line of code in the main subroutine. Calling a subroutine When we 'call a subroutine we use it‟s IDENTIFIER (it‟s name). As seen on line 29 When the code is executed it will go to the main method. When it gets to line 29 the computer will execute lines 9 – 16. As subtractingSubRoutine is NOT CALLED anywhere it (remember this is the will NOT GET EXECUTED. ONLY subroutine that automatically executes when the program is run).
  • 16. Ex 2.5 – Exam mark Aim: Create a program that works out a students % score for different 3 tests Description Write a program called Test.java that works out the % score of 3 different tests. Output Use the data: Test 1: 10.5/20 Test 2: 17/20 Test 3: 77/98 HINT Do the first test and try to run and compile it. Then do the other tests. Notice there is something different between the first test score and the last 2. Difficulty rating Skills: Use of arithmetic, datatypes & rounding
  • 17. Some important things to note When writing code it is good to break up a larger programs into small subroutines as this makes it easier to write, debug and understand. (For now most of your programs are small enough be written directly in the main subroutine). Before using variables you must declare them first. This involves supplying the datatype and it‟s identifier.
  • 18. Some important things to note When working out an arithmetic calculation and storing as a double at least one of the variables involved in the calculation has to be stored as a double (even if it is in fact just an integer. int num1 = 3; This would NOT work as Int num2 = 5; neither of the variables being double result = num1 / num2 divided are stored as doubles int num1 = 3; This would work as num2 is stored as a double (even double num2 = 5; though 5 is an integer we still double result = num1 / num2 have to store it as a double)