You will learn:
- Variables
- Data types
- Comments
- Interacting with user input
- Operations
- Casting
- Math Class
The code below calculate the area and the circumference of a circle and output it to the user.
System.out.println(3.142 * 7 * 7);
System.out.println(2 * 3.142 * 7);
OUTPUT
153.958
43.988
But the output are vague to the user, labeling them can give user clear understanding of each output.
System.out.println("Area of a circle with radius 7 is: " + 3.142 * 7 * 7);
System.out.println("Circumference of a circle with radius 7 is: " + 2 * 3.142 * 7);
Texts must be written in between double quotation mark and you can perform addition operation on two or more texts or texts and numbers to join them together.
OUTPUT
Area of a circle with radius 7 is: 153.958
Circumference of a circle with radius 7 is: 43.988
Can you tell what the code below does?
System.out.println(4 * 3);
Your Guess might be:
It multiple 4 by 3, YES
however, the code calculate the area of a rectangle with length 4 and width 3.
You missed it because there is no readability in the code.
To add readability to the code we introduce VARIABLES
Considering the code below, can you easily tell what it does?
int length = 4;
int width = 3;
int areaOfRectangle = length * width;
System.out.println(areaOfRectangle);
The Java keyword int
before the variable name is primitive data type
Java is statically typed language, you must declared the data types of every variable. Once a variable is declared to be of a certain data type, it cannot hold values of other data types.
Three data types we will be using most are:
int
=> It holds integer values e.g
int age = 16;
double
=> It holds decimal point values e.g
double PI = 3.142;
String
=> It holds sequence of characters (text) e.g
String name = "Fabala";
Values of String data types are en-quoted in double quotation mark. Only addition(+) operation can be perform on String and are called concatenation.
String firstName = "Halifa";
String lastName = "Sallah";
String fullName = firstName + " " + lastName;
Note: Spaces are characters and empty String is just ""
, double quotation mark with nothing inside.
Exercise
Write a program that calculate and output both the Area and Circumference
of a circle with radius 3.5
, take PI = 3.142
Solution
solution will be available later!
It turns out that Variables
does much more than adding readability to our code.
By just declaring PI
variable only once, you can reuse it in evaluating area and circumference of multiple circles and if there's need for changes in PI
, you only need to do that in PI
variable.
Code below calculate the area of three circles, A, B and C with radius 3.5, 7, and 4.5 respectively taking PI as 3.14159265358979
double PI = 3.14159265358979;
//circle A
double radiusA = 3.5;
double areaOfCircleA = PI * radiusA * radiusA;
System.out.println("Area of circle A: " + areaOfCircleA);
//circle B
double radiusB = 7;
double areaOfCircleB = PI * radiusB * radiusB;
System.out.println("Area of circle B: " + areaOfCircleB);
//circle C
double radiusC = 4.5;
double areaOfCircleC = PI * radiusC * radiusC;
System.out.println("Area of circle C: " + areaOfCircleC);
I deliberately add //circle A
, //circle B
, //circle C
in the code above. Those are COMMENTS and are use to add additional readability to code. COMMENTS are commonly use to explain what the code does and because COMMENTS are ignored by the compiler (are not executed), people also use it to comment codes that they do not want to execute.
// single line comments
/* this is a
multi line
comments
*/
I want to demonstrate VARIABLES in actions in one more instance before we actually define what they are.
Interacting with users
Let's write a program that takes in two integer numbers from the user and output their sum to the screen.
There are few ways to read input from the user in java and the two most commonly use are BufferedReader class and Scanner class
but for now we are going to use Scanner class.
To use Scanner class
, we need to import it on top of our own class.
import java.util.Scanner;
We import Scanner class from Java.util
package.
More on import and packages later in the course. Our focus is on variables. Feel free to retype the exact codes seen below.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int firstNumber = scan.nextInt();
System.out.print("Enter another integer number: ");
int secondNumber = scan.nextInt();
int sum = firstNumber + secondNumber;
System.out.println("Sum of " + firstNumber + " and " + secondNumber + " is " + sum);
//it's a good practice to close scanner object when done
scan.close();
Exercise
Write a program that reads an integer from the user and squared it.
SOLUTION
Exercise
Using Scanner class, read two numbers from the user and perform four basic arithmetic operations on them. Your codes should be readable using variables and user should clearly understand each output.
Can you try to do the same exercise without using VARIABLES. Good luck!
We have now seen VARIABLES in action.
VARIABLES is related to variables we have seen in Mathematics, Economics and English.
In Mathematics, we solve for x and in programming we use x to map to our values in memory (think of x being descriptive and holding our value that a stored in the memory (heap) )
In English and Economics, Variables are something that are subject to changes or can assume any set of values and in programming variable too can change from mapping one value to another value.
for example, in the code below variable name was mapping to Fred and it was now reassigned to map to Fabala
String name = "Fred";
name = "Fabala";
System.out.println("Name: " + name);
Equal to sign (=
) is an assignment operator. We use it to assign values to variable names.
It is worth knowing that you do not have to assign value (Initial value) to a variable at the time of declaration.
You can declare variable and assign value to it later in your code. The code below try to demonstrate the use case
double heigh; // declaring variable
System.out.println("measuring...");
heigh = 13.7; // assigning value
System.out.println("Heigh: " + heigh);
Note in Scanner class we have more methods than nextInt();
Other commonly used methods are:
next()
, to read word from the user
nextLine()
to read the whole line
nextDouble() or nextFloat
to read the decimal (floating point numbers)
nextShort()
, nextLong()
, nextBoolean()
and much more. We will explore more of them as we need them.
Exercise
Write a program that ask user his/her name and great him/her like "Hello " + name!
Don't forget you will need
next()
method from the Scanner class
Note
- Variable names should be descriptive and meaningful
- Variable must only start with letters or underscores and can contain any character.
- Reserve keywords cannot be use as variable name
- By convention all java variable name should start with small letter with all subsequent words capitalized. e.g
firstName
- By convention all constant variables are written in UPPER CASE e.g
double PI = 3.142;
and to enforce the constant nature of the variable, you can usefinal
keyword in java. e.gfinal double PI = 3.142;
The code below had wrongly assigned wrong values to the wrong variable. firstName should contain the first name value, "Fabala" and lastName should contain the last name value "Dibbasey*. Our task is to correct the order of the values aka swap so that firstName and lastName will now hold their right values "Fabala" and "Dibbasey" respectively.
String firstName = "Dibbasey";
String lastName = "Fabala";
Try it out before looking at the solution.
String firstName = "Dibbasey";
String lastName = "Fabala";
System.out.println("Before swapping... " );
System.out.println("first name: " + firstName + "\nlast name: " + lastName);
String temp;
temp = firstName;
firstName = lastName;
lastName = temp;
System.out.println("After swapping");
System.out.println("first name: " + firstName + "\nlast name: " + lastName);
Exercise
Read two double number from the user and swap them.
Data types
Primitive and non primitive are the two data types in Java.
Primitive data types
Non primitive data types
- Strings
- Arrays
- Classes
- Interfaces
- Objects
more on Non primitive data types and it's differences from primitive data type later in the course. Also, We'll learn how to create our own data types on top of java built in data types later in the course.
Exercises
Simple interest
Write a Java program that read principal, time and rate from the user and calculate simple interest from the given input.
Quadratic equation
Quadratic equation
Using java program, read a, b and c from the user and solve quadratic equation from the input.
use Math.sqrt(a), where a is any double number && Math.pow(a, b), where a is the base and b is the exponent.
Time conversion
Write java program that convert days ranging from 1 to 360 to seconds. Access the day from the user!
Quotient && Remainder
Quotient, integer part of the division
.
Remainder, left over integer part of the division
.
Write a program that ask user two input numbers, the first number being the numerator and second input being the denominator, perform division on the two numbers and output to the user both Quotient and Remainder
of the division.
Arithmetic Operations
+
Addition Operator
-
Subtraction Operator
*
Multiplication Operator
/
Division Operator
%
Remainder Operator
Shorthand Operations
for int a = 5;
&& int b = 4;
a += b
==> a = a + b; // 9
a -= b
==> a = a - b; // 1
a *= b
==> a = a * b; // 20
a /= b
==> a = a / b; // 1 (Quotient division!)
a %= b
==> a = a % b; // 1
In java 3/2 (Quotient division) is not the same as 3/2.0 (floating point division). For floating (decimal) point division, at least either numerator or denominator value must be double data type. e.g 7/2.0 or 7.0/2 or 7.0/2.0
Increment and Decrement Shorthand Operation
a++
==> a += 1; ==> a = a + 1;
a--
==> a -= 1; ==> a = a - 1;
Casting
Remember we said that once a data type is declared to be of one data type cannot hold the value of different data type.
With casting we can match the value of one data type to another data type. for example,
int width = (int) 3.35;
System.out.println(width);
Explicit casting is when we have to do the conversion manually like the code above.
Implicit casting is when casting occurred automatically as in the code below.
double height = 7;
System.out.println(height);
Implicit casting happen when converting smaller data type to larger data type as it's demonstrated in flow chart below
Byte -> Short -> Char -> Int -> Long -> Float -> Double
and Explicit casting follow the reversed of the flow chart.
Math class
Math.sqrt(a);
, return the square root of a given double number a
Math.abs(a);
, return absolute number of a given double number a.
Math.round(a);
round up or round down to the nearest whole number
Math.floor(a);
always round down
Math.ceil(a);
always round up
Math.min(a, b);
return the minimum number
To see more Math functions in most IDE or Editor type Math.
ctrl + space
or consult documentation.
Exercises
Average score
Ask UTG student his/her scores from four different exams, calculate and output the average score to the student, round your answer to two decimal places.
Sum of minMax
Read three numbers from the user, calculate and output to the screen the sum of the minimum and the maximum numbers to the user.
input
5
7
2
output
minMax sum = 9
Explanation
minimum number is 2 and maximum number is 7; 2 + 7 = 9
Congratulations you've successfully completed Java Basic Concept. Looking forward to seeing you in Condition and Loop.
Don't forget to connect with me on twitter and linkedin
Top comments (0)