Data Types: JAVA For Beginners

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

JAVA for Beginners

Predicted Output:

P Q PANDQ PORQ PXORQ NOTP

true true true true false fals

true false false true true fals

false true false true true true

false false false false false true

Data Types
The following is a list of Java’s primitive data types:

Data Type Description


int Integer – 32bit ranging from -2,147,483,648 to 2,147,483,648
byte 8-bit integer ranging from -128 to 127
short 16-bit integer ranging from -32,768 to 32,768
long 64-bit integer from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,808

float Single-precision floating point, 32-bit


double Double-precision floating point, 64-bit

char Character , 16-bit unsigned ranging from 0 to 65,536 (Unicode)

boolean Can be true or false only

The ‘String’ type has not been left out by mistake. It is not a primitive data type, but strings (a
sequence of characters) in Java are treated as Objects.

class Example8 {

public static void main(String args[]) {

int var; // this declares an int variable

double x; // this declares a floating-point variable

var = 10; // assign var the value 10

x = 10.0; // assign x the value 10.0

System.out.println("Original value of var: " + var);

System.out.println("Original value of x: " + x);

System.out.println(); // print a blank line

Riccardo Flask 13 | P a g e
JAVA for Beginners

// now, divide both by 4

var = var / 4;

x = x / 4;

System.out.println("var after division: " + var);

System.out.println("x after division: " + x);

Predicted output:

Original value of var: 10

Original value of x: 10.0

var after division: 2

x after division: 2.5

One here has to note the difference in precision of the different data types. The following example
uses the character data type. Characters in Java are encoded using Unicode giving a 16-bit range, or
a total of 65,537 different codes.

class Example9 {

public static void main(String args[]) {

char ch;

ch = 'X';

System.out.println("ch contains " + ch);

ch++; // increment ch

System.out.println("ch is now " + ch);

ch = 90; // give ch the value Z

System.out.println("ch is now " + ch);

Riccardo Flask 14 | P a g e
JAVA for Beginners

Predicted Output:

ch is now X
ch is now Y
ch is now Z

The character ‘X’ is encoded as the number , hence when we increment ‘ch’, we get character
number , or ‘Y’.

The Boolean data type can be either TRUE or FALSE. It can be useful when controlling flow of a
program by assigning the Boolean data type to variables which function as flags. Thus program flow
would depend on the condition of these variables at the particular instance. Remember that the
output of a condition is always Boolean.

class Example10 {

public static void main(String args[]) {

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

Predicted output:

b is false
b is true
This is executed
10 > 9 is true

Riccardo Flask 15 | P a g e
JAVA for Beginners

Introducing Control Statements


These statements will be dealt with in more detail further on in this booklet. For now we will learn
about the if and the for loop.

class Example11 {

public static void main(String args[]) {

int a,b,c;

a = 2;

b = 3;

c = a - b;

if (c >= 0) System.out.println("c is a positive number");

if (c < 0) System.out.println("c is a negative number");

System.out.println();

c = b - a;

if (c >= 0) System.out.println("c is a positive number");

if (c < 0) System.out.println("c is a negative number");

Predicted output:

c is a negative number
c is a positive number

The ‘if’ statement evaluates a condition and if the result is true, then the following statement/s are
executed, else they are just skipped (refer to program output). The line System.out.println() simply
inserts a blank line. Conditions use the following comparison operators:

Operator Description
< Smaller than
> Greater than
<= Smaller or equal to, (a<=3) : if a is 2 or 3, then result of comparison is TRUE
>= Greater or equal to, (a>=3) : if a is 3 or 4, then result of comparison is TRUE
== Equal to
!= Not equal

Riccardo Flask 16 | P a g e
JAVA for Beginners

The for loop is an example of an iterative code, i.e. this statement will cause the program to repeat a
particular set of code for a particular number of times. In the following example we will be using a
counter which starts at 0 and ends when it is smaller than 5, i.e. 4. Therefore the code following the
for loop will iterate for 5 times.

class Example12 {

public static void main(String args[]) {

int count;

for(count = 0; count < 5; count = count+1)

System.out.println("This is count: " + count);

System.out.println("Done!");

Predicted Output:

This is count: 0

This is count: 1

This is count: 2

This is count: 3

This is count: 4

Done!

Instead of count = count+1, this increments the counter, we can use count++

The following table shows all the available shortcut operators:

Operator Description Example Description


++ Increment a++ a = a + 1 (adds one from a)
-- Decrement a-- a = a – 1 (subtract one from a)
+= Add and assign a+=2 a=a+2
-= Subtract and assign a-=2 a=a–2
*= Multiply and assign a*=3 a=a*3
/= Divide and assign a/=4 a=a/4
%= Modulus and assign a%=5 a = a mod 5

Riccardo Flask 17 | P a g e
JAVA for Beginners

Blocks of Code
Whenever we write an IF statement or a loop, if there is more than one statement of code which has
to be executed, this has to be enclosed in braces, i.e. ‘, …. ’

class Example13 {

public static void main(String args[]) {

double i, j, d;

i = 5;

j = 10;

if(i != 0) {

System.out.println("i does not equal zero");

d = j / i; Block of
Code
System.out.print("j / i is " + d);

System.out.println();

Predicted Output:

i does not equal to zero

j/i is 2

Test your skills Example14


Write a program which can be used to display a conversion table, e.g. Euros to Malta Liri, or Metres
to Kilometres.

Hints:

One variable is required


You need a loop

The Euro Converter has been provided for you for guidance. Note loop starts at 1 and finishes at 100
(<101). In this case since the conversion rate does not change we did not use a variable, but assigned
it directly in the print statement.

class EuroConv {

Riccardo Flask 18 | P a g e
JAVA for Beginners

public static void main (String args []){

double eu;

System.out.println("Euro conversion table:");

System.out.println();

for (eu=1;eu<101;eu++)

System.out.println(eu+" Euro is euqivalent to Lm


"+(eu*0.43));

The Math Class


In order to perform certain mathematical operations like square root (sqrt), or power (pow); Java
has a built in class containing a number of methods as well as static constants, e.g.
Pi = 3.141592653589793 and E = 2.718281828459045. All the methods involving angles use radians
and return a double (excluding the Math.round()).

class Example15 {

public static void main(String args[]) {

double x, y, z;

x = 3;

y = 4;

z = Math.sqrt(x*x + y*y);

System.out.println("Hypotenuse is " +z);

Predicted Output:

Hypotenuse is 5.0

Please note that whenever a method is called, a particular nomenclature is used where we first
specify the class that the particular method belongs to, e.g. Math.round( ); where Math is the class
name and round is the method name. If a particular method accepts parameters, these are placed in
brackets, e.g. Math.max(2.8, 12.9) – in this case it would return 12.9 as being the larger number. A

Riccardo Flask 19 | P a g e
JAVA for Beginners

useful method is the Math.random( ) which would return a random number ranging between 0.0
and 1.0.

Scope and Lifetime of Variables


The following simple programs, illustrate how to avoid programming errors by taking care where to
initialize variables depending on the scope.

class Example16 {

public static void main(String args[]) {

int x; // known to all code within main

x = 10;

if(x == 10) { // start new scope

int y = 20; // known only to this block

// x and y both known here.

System.out.println("x and y: " + x + " " + y);

x = y * 2;

// y = 100; // Error! y not known here

// x is still known here.

System.out.println("x is " + x);

Predicted Output:

x and y: 10 20
x is 40

If we had to remove the comment marks from the line, y = 100; we would get an error during
compilation as y is not known since it only exists within the block of code following the ‘if’
statement.

The next program shows that y is initialized each time the code belonging to the looping sequence is
executed; therefore y is reset to -1 each time and then set to 100. This operation is repeated for
three (3) times.

Riccardo Flask 20 | P a g e
JAVA for Beginners

class Example17 {

public static void main(String args[]) {

int x;

for(x = 0; x < 3; x++) {

int y = -1; // y is initialized each time block is


entered

System.out.println("y is: " + y); // this always


prints -1

y = 100;

System.out.println("y is now: " + y);

Predicted Output:

y is: -1
y is now: 100

y is: -1
y is now: 100

y is: -1
y is now: 100

Type Casting and Conversions


Casting is the term used when a value is converted from one data type to another, except for
Boolean data types which cannot be converted to any other type. Usually conversion occurs to a
data type which has a larger range or else there could be loss of precision.

class Example18 { //long to double automatic conversion

public static void main(String args[]) {

long L;

double D;

L = 100123285L;

D = L; // L = D is impossible

Riccardo Flask 21 | P a g e
JAVA for Beginners

System.out.println("L and D: " + L + " " + D);

Predicted Output:

L and D: 100123285 1.00123285E8

The general formula used in casting is as follows: (target type) expression, where target type could
be int, float, or short, e.g. (int) (x/y)

class Example19 { //CastDemo

public static void main(String args[]) {

double x, y;

byte b;

int i;

char ch;

x = 10.0;

y = 3.0;

i = (int) (x / y); // cast double to int

System.out.println("Integer outcome of x / y: " + i);

i = 100;

b = (byte) i;

System.out.println("Value of b: " + b);

i = 257;

b = (byte) i;

System.out.println("Value of b: " + b);

b = 88; // ASCII code for X

ch = (char) b;

System.out.println("ch: " + ch);

Riccardo Flask 22 | P a g e
JAVA for Beginners

Predicted Output:

Integer outcome of x / y: 3

Value of b: 100

Value of b: 1

ch: X

In the above program, x and y are doubles and so we have loss of precision when converting to
integer. We have no loss when converting the integer 100 to byte, but when trying to convert 257 to
byte we have loss of precision as 257 exceeds the size which can hold byte. Finally we have casting
from byte to char.

class Example20 {

public static void main(String args[]) {

byte b;

int i;

b = 10;

i = b * b; // OK, no cast needed

b = 10;

b = (byte) (b * b); // cast needed!! as cannot assing int


to byte

System.out.println("i and b: " + i + " " + b);

Predicted Output:

i and b: 100 100

The above program illustrates the difference between automatic conversion and casting. When we
are assigning a byte to integer, i = b * b, the conversion is automatic. When performing an arithmetic
operation the byte type are promoted to integer automatically, but if we want the result as byte, we
have to cast it back to byte. This explains why there is the statement: b = (byte) (b * b). Casting has
to be applied also if adding variables of type char, as result would else be integer.

Riccardo Flask 23 | P a g e
JAVA for Beginners

Console Input
Most students at this point would be wondering how to enter data while a program is executing.
This would definitely make programs more interesting as it adds an element of interactivity at run-
time. This is not that straight forward in Java, since Java was not designed to handle console input.
The following are the three most commonly used methods to cater for input:

Using the Keyboard Class


One can create a class, which would contain methods to cater for input of the various data types.
Another option is to search the internet for the Keyboard Class. This class is easily found as it is used
in beginners Java courses. This class is usually found in compiled version, i.e. keyboard.class. This file
has to be put in the project folder or else placed directly in the Java JDK. The following is the source
code for the Keyboard class just in case it is not available online!

import java.io.*;

import java.util.*;

public class Keyboard {

//************* Error Handling Section

private static boolean printErrors = true;

private static int errorCount = 0;

// Returns the current error count.

public static int getErrorCount(){

return errorCount;
}

// Resets the current error count to zero.

public static void resetErrorCount (int count){

errorCount = 0;

// Returns a boolean indicating whether input errors are

// currently printed to standard output.

public static boolean getPrintErrors(){

return printErrors;

Riccardo Flask 24 | P a g e

You might also like