0% found this document useful (0 votes)
20 views

Lecture

The document discusses Java fundamentals including parts of a Java program, variables and data types, input/output, and operators. It covers the structure of a Java class, variables and literals, primitive data types like integer, float, boolean and char. Escape sequences, identifiers, naming conventions and Unicode encoding are also explained.

Uploaded by

warriord876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lecture

The document discusses Java fundamentals including parts of a Java program, variables and data types, input/output, and operators. It covers the structure of a Java class, variables and literals, primitive data types like integer, float, boolean and char. Escape sequences, identifiers, naming conventions and Unicode encoding are also explained.

Uploaded by

warriord876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

ICT102

Introduction to Programming

Lecture 2– Java Fundamentals: I/O, Data Types and Operators

CRICOS 03171A
Focus for this week

01 Parts of Java Program, Variables and Literals,


Primitive Data Types,

02 Arithmetic Operators and Combined Assignment


Operators, I/O
2-3

Parts of a Java Program


• A Java source code file contains one or more Java classes.

• If more than one class is in a source code file, only one of them may be public.

• The public class and the filename of the source code file must match.
ex: A class named Simple must be in a file named Simple.java
• Each Java class can be separated into parts.
2-4

Analyzing The Example


This is a Java comment. It is
// This is a simple Java program.
ignored by the compiler.

public class Simple This is the class header


for the class Simple
{
public static void main(String [] args)
{
System.out.println("Programming is great fun!");
}
}
This is the Java Statement that
is executed when the program runs.
2-5

Practice activity
Download and install IDE using the instructions
Code and Run the above example program
2-6

Console Output
• The previous example uses the line:
System.out.println("Programming is great fun!");
• This line uses the System class from the standard Java library.

• The System class contains methods and objects that perform system level tasks.

• The out object, a member of the System class, contains the methods print and
println.
2-7

Console Output
• The print statement works very similarly to the
println statement.
• However, the print statement does not put a
newline character at the end of the output.
• The lines:
System.out.print("These lines will be");
System.out.print("printed on");
System.out.println("the same line.");

Will output:
These lines will beprinted onthe same line.
Notice the odd spacing? Why are some words written
together?
2-8

Java Escape Sequences


\n newline Advances the cursor to the next line for subsequent printing

\t tab Causes the cursor to skip over to the next tab stop

\b backspace Causes the cursor to back up, or move left, one position

Causes the cursor to go to the beginning of the current line, not


\r carriage return
the next line

\\ backslash Causes a backslash to be printed

\’ single quote Causes a single quotation mark to be printed

\” double quote Causes a double quotation mark to be printed


2-9

Practice Question
• Write the code that would result in the following
output:
These are our top seller:

Computer games

Coffee

Asprin

My name is “Qasir”

• With escape sequences, complex text output can


be achieved.
2-10

Variables and Literals


• A variable is a named storage location in the computer’s memory.

• A literal is a value that is written into the code of a program.

• Programmers determine the number and type of variables a program will need.

This line is called The following line is known


a variable declaration. as an assignment statement.
int value; value = 5;

This is a string literal. It will be printed as is.

System.out.print("The value is ");


System.out.println(value);
The integer 5 will
be printed out here.
Notice no quote marks?
2-11

The + Operator
• The + operator can be used in two
ways.
– as a concatenation operator
– as an addition operator
• If either side of the + operator is a
string, the result will be a string.
System.out.println("Hello " + "World");
System.out.println("The value is: " + 5);
System.out.println("The value is: " + value);
System.out.println("The value is: " + ‘/n’ + 5);
2-12

Java Reserved Keywords


abstract double instanceof static
assert else int strictfp
boolean enum interface super
break extends long switch
byte false native synchronized
case for new this
catch final null throw
char finally package throws
class float private transient
const goto protected true
continue if public try
default implements return void
do import short volatile
while
2-13

Identifiers
• Identifiers are programmer-defined names for:
– classes
– variables
– methods
• Identifiers may not be any of the Java reserved keywords.
2-14

Identifiers
• Identifiers must follow certain rules:
– An identifier may only contain:
 letters a–z or A–Z,
 the digits 0–9,
 underscores (_), or
 the dollar sign ($)

– The first character may not be a digit.

– Identifiers are case sensitive.


 itemsOrdered is not the same as itemsordered.

– Identifiers cannot include spaces.


2-15

Variable Names
• Variable names should be descriptive.

• Descriptive names allow the code to be more readable; therefore, the code is more
maintainable.

• Which of the following is more descriptive?


double tr = 0.0725;
double salesTaxRate = 0.0725;

• Java programs should be self-documenting.

• Java Naming Conventions

• http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
2-16

Primitive Data Types


• Primitive data types are built into the Java language
and are not derived from classes.
• There are 8 Java primitive data types.
– byte – float
– short – double
– int – boolean
– long – char
2-17

Numeric Data Types


byte 1 byte Integers in the range
-128 to +127

short 2 bytes Integers in the range of


-32,768 to +32,767

int 4 bytes Integers in the range of


-2,147,483,648 to +2,147,483,647

long 8 bytes Integers in the range of


-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

float 4 bytes Floating-point numbers in the range of


±3.410-38 to ±3.41038, with 7 digits of accuracy

double 8 bytes Floating-point numbers in the range of


±1.710-308 to ±1.710308, with 15 digits of accuracy
2-18

Practice Question
• Why does below code give an error

– float number;
– number = 23.5; // Error!

• How to fix this error?

• Java is a strongly-typed language.


2-19

The boolean Data Type


• The Java boolean data type can have two possible values.
– true
– false

• The value of a boolean variable may only be copied into a boolean variable.

See example: TrueFalse.java


2-20

The char Data Type


• The Java char data type provides access to
single characters.
• char literals are enclosed in single quote marks.
– ‘a’, ‘Z’, ‘\n’, ‘1’
• Don’t confuse char literals with string literals.
– char literals are enclosed in single quotes.
– String literals are enclosed in double quotes.
2-21

Unicode
• Internally, characters are stored as numbers.
• This number to Text conversion is done using
Unicode
• The Unicode character set can consist of
65536 (216) individual characters.
• ASCII was 256
2-22

Unicode
The binary numbers
A represent these
decimal values.
B

00 65 00 66

0000000001000001 0000000001000011

https://unicodetable.archive.thomasorlita.com/
2-23

Practice Question
• What is the error in below code
public static void main(String [] args)
{
int month, days;

System.out.println("Month " + month + " has " +


days + " Days.");
}

Variable declaration and Initialization


2-24

Arithmetic Operators
• Java has five (5) arithmetic operators.

Operator Meaning Type Example

+ Addition Binary total = cost + tax;

- Subtraction Binary cost = total – tax;

* Multiplication Binary tax = cost * rate;

/ Division Binary salePrice = original / 2;

% Modulus Binary remainder = value % 5;


2-25

Operator Precedence
• Mathematical expressions can be very complex.

• There is a set order in which arithmetic operations will be carried out.

Operator Associativity Example Result


Higher -
Priority Right to left x = -4 + 3; -1
(unary negation)
* / % Left to right x = -4 + 4 % 3 * 13 + 2; 11
Lower
Priority + - Left to right x = 6 + 3 – 4 + 6 * 3; 23
2-26

Grouping with Parenthesis


• When parenthesis are used in an expression, the
inner most parenthesis are processed first.
• If two sets of parenthesis are at the same level,
they are processed left to right.

• x = ((4*5) / (5-2) ) – 25; // result = -19

1 2

4
2-27

Combined Assignment Operators


Operator Example Equivalent Value of variable after operation

+= x += 5; x = x + 5; The old value of x plus 5.

-= y -= 2; y = y – 2; The old value of y minus 2

*= z *= 10; z = z * 10; The old value of z times 10

/= a /= b; a = a / b; The old value of a divided by b.

The remainder of the division of


%= c %= 3; c = c % 3;
the old value of c divided by 3.
2-28

Commenting Code
• Java provides three methods for commenting code.

Comment
Style Description
Single line comment. Anything after the // on the line will be
//
ignored by the compiler.
Block comment. Everything beginning with /* and ending with
/* … */ the first */ will be ignored by the compiler. This comment type
cannot be nested.
Javadoc comment. This is a special version of the previous block
comment that allows comments to be documented by the javadoc
/** … */ utility program. Everything beginning with the /** and ending
with the first */ will be ignored by the compiler. This comment
type cannot be nested.
2-29

Indentation
• Programs should use proper indentation.
• Each block of code should be indented a few spaces from
its surrounding block.
• Two to four spaces are sufficient.
• Tab characters should be avoided.
– Tabs can vary in size between applications and devices.
– Most programming text editors allow the user to replace the tab
with spaces.
2-30

The Scanner Class


• To read input from the keyboard we can use the
Scanner class.
• The Scanner class is defined in java.util, so
we will use the following statement at the top of
our programs:

import java.util.Scanner;
2-31

The Scanner Class


• Scanner objects work with System.in

• To create a Scanner object:


Scanner keyboard = new Scanner (System.in);
• Get the age as an int

• int age = scanner.nextInt();


• Scanner class methods are:

• nextDouble, nextFloat, nextBoolean etc.


• See example: Payroll.java
2-32

Practice Questions
List the variables, literals and what would be the screen output?
Public class BigLittle {
Public static void main (String[] args)
{ int little;
int big;
little = 2;
big = 2000;
System.out.println (“The little number is ” + little);
System.out.println (“The big number is ” + big);
}
}

- Which of the following are illegal names for identifiers and why?
- x
- 99bottles
- July 97
- R&D

You might also like