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)

More Related Content

PPTX
02 data types in java
PPSX
Data types, Variables, Expressions & Arithmetic Operators in java
PPT
Java basic
PPT
Chapter 8 - Exceptions and Assertions Edit summary
PPTX
L2 datatypes and variables
PPTX
Introduction to Java
PPT
Introduction to-programming
PPT
Basic elements of java
02 data types in java
Data types, Variables, Expressions & Arithmetic Operators in java
Java basic
Chapter 8 - Exceptions and Assertions Edit summary
L2 datatypes and variables
Introduction to Java
Introduction to-programming
Basic elements of java

What's hot (20)

PPT
PPT
Java tutorial for Beginners and Entry Level
PPT
Java: Objects and Object References
PDF
Object Oriented Programming in PHP
PPTX
Classes, objects in JAVA
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPT
Core java concepts
PPTX
Pi j3.2 polymorphism
PDF
Built in classes in java
PPT
Chapter 7 - Defining Your Own Classes - Part II
PPTX
Java basics and java variables
PPT
Chapter 2 - Getting Started with Java
PPT
Java Notes
PDF
Chapter 01 Introduction to Java by Tushar B Kute
PPT
M C6java3
PPT
Core java concepts
PDF
Learn Java Part 2
PPTX
Core java complete ppt(note)
PPT
Chapter 4 - Defining Your Own Classes - Part I
PPTX
Chapter 05 classes and objects
Java tutorial for Beginners and Entry Level
Java: Objects and Object References
Object Oriented Programming in PHP
Classes, objects in JAVA
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Core java concepts
Pi j3.2 polymorphism
Built in classes in java
Chapter 7 - Defining Your Own Classes - Part II
Java basics and java variables
Chapter 2 - Getting Started with Java
Java Notes
Chapter 01 Introduction to Java by Tushar B Kute
M C6java3
Core java concepts
Learn Java Part 2
Core java complete ppt(note)
Chapter 4 - Defining Your Own Classes - Part I
Chapter 05 classes and objects
Ad

Similar to Java basics variables (20)

PPT
C++ basics
PDF
vb.net.pdf
PPTX
Python Guide.pptx
PPTX
5. using variables, data, expressions and constants
PPT
M C6java2
PDF
Programming in Java: Storing Data
PPTX
Input output
PPT
02 Primitive data types and variables
PDF
Lecture # 1 introduction revision - 1
DOCX
UNIT-II VISUAL BASIC.NET | BCA
PPT
Variables 9 cm604.7
PPT
presentation of java fundamental
PDF
pythonQuick.pdf
PDF
python notes.pdf
PDF
python 34💭.pdf
PPTX
Java generics final
PPTX
made it easy: python quick reference for beginners
PPTX
Chapter1.pptx
PDF
Chapter 2 basic element of programming
PPT
Comp102 lec 4
C++ basics
vb.net.pdf
Python Guide.pptx
5. using variables, data, expressions and constants
M C6java2
Programming in Java: Storing Data
Input output
02 Primitive data types and variables
Lecture # 1 introduction revision - 1
UNIT-II VISUAL BASIC.NET | BCA
Variables 9 cm604.7
presentation of java fundamental
pythonQuick.pdf
python notes.pdf
python 34💭.pdf
Java generics final
made it easy: python quick reference for beginners
Chapter1.pptx
Chapter 2 basic element of programming
Comp102 lec 4
Ad

Recently uploaded (20)

PPTX
Single Visit Endodontics.pptx treatment in one visit
PDF
FAMILY PLANNING (preventative and social medicine pdf)
PPTX
Juvenile delinquency-Crim Research day 3x
PDF
HSE and their team are going through the hazards of the issues with learning ...
PDF
Physical pharmaceutics two in b pharmacy
PDF
[Medicalstudyzone.com] 1. AIIMS NOV EMBER 2015 SOLVED PAPER.pdf
PPTX
MALARIA - educational ppt for students..
PDF
IS1343_2012...........................pdf
PPTX
climate change of delhi impacts on climate and there effects
PDF
V02-Session-4-Leadership-Through-Assessment-MLB.pdf
PDF
GIÁO ÁN TIẾNG ANH 7 GLOBAL SUCCESS (CẢ NĂM) THEO CÔNG VĂN 5512 (2 CỘT) NĂM HỌ...
PDF
HSE 2022-2023.pdf الصحه والسلامه هندسه نفط
PDF
Developing speaking skill_learning_mater.pdf
PDF
Teacher's Day Quiz 2025
PPTX
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
PDF
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
PDF
Design and Evaluation of a Inonotus obliquus-AgNP-Maltodextrin Delivery Syste...
PDF
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
PPTX
Entrepreneurship Management and Finance - Module 1 - PPT
PDF
The 10 Most Inspiring Education Leaders to Follow in 2025.pdf
Single Visit Endodontics.pptx treatment in one visit
FAMILY PLANNING (preventative and social medicine pdf)
Juvenile delinquency-Crim Research day 3x
HSE and their team are going through the hazards of the issues with learning ...
Physical pharmaceutics two in b pharmacy
[Medicalstudyzone.com] 1. AIIMS NOV EMBER 2015 SOLVED PAPER.pdf
MALARIA - educational ppt for students..
IS1343_2012...........................pdf
climate change of delhi impacts on climate and there effects
V02-Session-4-Leadership-Through-Assessment-MLB.pdf
GIÁO ÁN TIẾNG ANH 7 GLOBAL SUCCESS (CẢ NĂM) THEO CÔNG VĂN 5512 (2 CỘT) NĂM HỌ...
HSE 2022-2023.pdf الصحه والسلامه هندسه نفط
Developing speaking skill_learning_mater.pdf
Teacher's Day Quiz 2025
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
Design and Evaluation of a Inonotus obliquus-AgNP-Maltodextrin Delivery Syste...
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
Entrepreneurship Management and Finance - Module 1 - PPT
The 10 Most Inspiring Education Leaders to Follow in 2025.pdf

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)