0% found this document useful (0 votes)
77 views42 pages

Lect 3

The document provides an introduction to basic programming language elements in Java, focusing on fundamental concepts such as comments, classes, the main method, variables, and data types. It outlines the structure of a simple Java program, the rules for variable declaration and initialization, and discusses primitive data types and literals. Additionally, it emphasizes the importance of meaningful variable names and the concept of constant variables.

Uploaded by

wmy308.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views42 pages

Lect 3

The document provides an introduction to basic programming language elements in Java, focusing on fundamental concepts such as comments, classes, the main method, variables, and data types. It outlines the structure of a simple Java program, the rules for variable declaration and initialization, and discusses primitive data types and literals. Additionally, it emphasizes the importance of meaningful variable names and the concept of constant variables.

Uploaded by

wmy308.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

COMP1022P Introduction to Computing with Java

Topic 2: Basic Programming Language Elements


Dr. Desmond Tsoi

Department of Computer Science & Engineering


The Hong Kong University of Science and Technology
Hong Kong SAR, China

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 1 / 42


Part I

Java Fundamentals

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 2 / 42


My First Java Program (Re-visit)
In the last lecture, you were asked
to type in the following simple Java
program into an editor, then
compile and run it
Now it’s time to understand what
it does!

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 3 / 42


Comments
Adding comments to program increases its readability
Comments are not treated as computer instructions, i.e., it is only for
human to read, not for computers
In Java, there are three ways to add comments
Syntax
1. All the lines between /* and */ are treated as comments
/* Multiple line comment
Comment line 1
...
Comment line n
*/
2. The line after // is treated as comment
// Single line comment
3. The text between /** */ is used to generate a web page, which describes
the instance variables and methods (Details of instance variables and
methods will be discussed later)
/** javadoc comment */
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 4 / 42
Class
A Java program should have at least one class (can be more than
one) and exactly one main method. If no main() method, the program
will not run!
Syntax
<access modifier> class <class name>
{
// Instance variables
// ...
// Methods
// ...
}
where <access modifier> is a Java keyword to
control the access to the class, <class name> is
the name of the class Just use the keyword public
Note: The name of the class should be the same as the access modifier for all
as the name of the file where this class is defined your programs right now

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 5 / 42


Writing a Simple Java Program
1. Define a class with the class
keyword and give a meaningful
name, then save it to disk
I The name of the file should
be exactly the same as the
class name!
2. Define a main method in the
class with signature
public static void main(String[] args)
as the starting point of the
program
I Just memorize this line of
code at the moment, we will
explain it in details later!
3. Put statement(s) / code within
the curly braces of main to
instruct a computer to perform
some tasks!
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 6 / 42
What Can You Do In the Main Method?
As mentioned, once you have
defined the main method (or any
method), you can start instructing
computer to do ”something”!
Here, ”something” includes:
1. Typical statements:
F Variable declaration,
assignments, method calls
2. Selective / Branching
statement(s), i.e. statement(s) for
selecting which statements to
execute We are going to cover all these
F if..else, switch one by one in this course!
3. Looping / Iterative statement(s),
i.e. statement(s) for repeatedly
executing of code
F for, while, do..while

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 7 / 42


Part II

Basic Elements of Java Programming

Pick the right one for the job: Java!

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 8 / 42


Variables, Primitive Data Types & Literals
Pre-defined values or data entered by a user (via keyboard / mouse)
are typically kept track of or memorized by computer programs in
main memory
Computer programs do this through the use of program elements
called ”variables”
By declaring variables in a program, data in different types could be
stored in computer’s memory
Before talking about how to declare variables, we will first introduce
I 8 primitive data types
I 4 primitive literal types
supported by Java

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 9 / 42


8 Primitive Data Types

Integer types
I byte (1 byte, range: -128 to +127)
I short (2 bytes, range: -32,768 to +32,767)
I int (4 bytes, range: -2,147,483,648 to +2,147,483,647)
I long (8 bytes, range: -9,223,372,036,854,775,908 to
+9,223,372,036,854,775,907)
Floating-point types
I float (4 bytes, range: −3.4 × 1038 to 3.4 × 1038 )
(6 - 7 significant decimal digits)
I double (8 bytes, range: −1.7 × 10308 to 1.7 × 10308 )
(14 - 15 significant decimal digits)

Floating point types are more general than integer types

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 10 / 42


8 Primitive Data Types (Cont’d)
Character type
I char (2 bytes, unsigned, Unicode)
F An English letter (’a’, ..., ’z’, ’A, ..., ’Z’)
F An English punctuation mark (’ !’, ’ ?’, etc.)
F A decimal digit (’0’, ..., ’9’)
F A symbol such as a space
F etc.
Boolean type
I boolean (true or false)
These are all the primitive data types in Java. Everything else is non-primitive
data type

Questions
1. Is String a primitive data type in Java?
No, since it is not one of the 8 primitive data types introduced.
2. Is Integer a primitive data type in Java?
No. Once again, it is not one of the 8 primitive data types introduced.
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 11 / 42
4 Primitive Literal Types
Literals are values associated with data types used in the program
In Java, there are 4 primitive literal types
1. Integer literals (associated with types: byte, short, int, long)
F 42, -3, 18, 20493, 0
2. Floating point literals (associated with types: float, double)
F 7.35, -19.83423, 42.0
3. Character literals (associated with types: char)
F ‘a’, ‘X’, ‘!’, ‘#’, ‘@’
4. Boolean literals (associated with type: boolean)
F true, false

The default data type of floating point literals is double, but the suffix F
(or f) can be appended to designate the data type of a floating literal as
float

Character is enclosed by single quotes ‘ ’

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 12 / 42


Character Literals
A character is stored as 16-bit unsigned
integer using Unicode encoding scheme,
which supports the display of text in
different language, such as
I Chinese 忍
I Korean 안녕하세요
Unicode includes the ASCII (American
Standard Code of Information
Interchange) code
I ASCII has a total of 128 characters,
each character is enclosed with a pair
of single quotes, e.g. ‘A’
I Each character in the Unicode has a

corresponding numeric value, e.g. ‘A’


has a value of 65 in decimal
representation
List of Unicode
https://en.wikipedia.org/wiki/List_of_Unicode_characters
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 13 / 42
Variable Declaration and Initialization
As mentioned, data in different types can be
stored in computer’s memory
A variable is a memory location with a name
and a type that stores a value
(You may think of a variable as a box with a
name that can hold a single data value)
Syntax
<type> <var name>;
<type> <var name> = <initial value>;
<type> <var name1>, <var name2>, ...;
<type> <var name1> = <initial value1>, <var name2> = <initial value2>, ...;
where <type> is the type of data that your variable would like to store, <var name> or <var
nameN> is the name of variable in program, which refers to the location in memory, <initial
value> or <initial valueN> is the initially assigned value to the variable
(We call this initialization!)

During compilation, a memory location of suitable size is assigned for each


declared variable, e.g. 8 bits are assigned for a variable in byte type
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 14 / 42
Rules for Choosing Variable Name

Java imposes the following rules for the choice of variable name
1. Must start with a letter, an underscore ( )
or a dollar sign ($) character
2. The other characters can only be letters,
digits, underscore ( ), and dollar sign ($)
3. Cannot contain a space, or any other
characters such as a dot (.), an asterisk (*),
a question mark (?) or an “at” sign (@)
4. Does not have any length unit
5. Furthermore, some of the words are
prohibited to be used as variable name, we
call these words ”reserved words”

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 15 / 42


List of Reserved Words
A variable name cannot be any of the keywords in Java, since
keywords have special meanings to Java compiler
Reserved Java keywords
abstract assert boolean break byte
case catch char class const *
continue default do double else
enum extends final finally float
for goto * if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while
Reserved Java literals
true false null
Special Identifier
var
* Keywords that are not currently used in Java
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 16 / 42
Variable Name Examples

Examples of valid variable name:


I Area, Length, a, A, sevenAnd1,
my program, desmond, GoOd, bAd,
$value, amount$
Examples of invalid variable name:
I my-program (Hyphen is not allowed)
I Java.com (Dot sign is not allowed)
I 7and1 (Variable name cannot
start with digit)
I good or bad (Space is not allowed)
I c?0 (? is not allowed)
I A/C (/ is not allowed)

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 17 / 42


Example: Variable Declaration and Initialization

// Filename: VariableDeclarationInitDemo1.java
/* An example demonstrating how to declare and initialize
variables to store data of different primitive type */
public class VariableDeclarationInitDemo1 {
public static void main(String[] args) {
int myVar1 = 10;
int myVar2;
int myVar3, myVar4, myVar5;
int myVar6 = 1, myVar7 = 3, myVar8 = 5;
System.out.println(myVar1);
} Screen output:
} 10

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 18 / 42


Example: Variable Declaration and Initialization
// Filename: VariableDeclarationInitDemo2.java
/* An example demonstrating the use of un-initialized
variables can cause error */
public class VariableDeclarationInitDemo2 {
public static void main(String[] args) {
int myVar1 = 10;
int myVar2; // Variable is not initialized
int myVar3, myVar4, myVar5;
int myVar6 = 1, myVar7 = 3, myVar8 = 5;
System.out.println(myVar1);
System.out.println(myVar2); // Error!
// Print content of uninitialized variable myVar2
// is an error. Java compiler requires initialization
// of local variables before use!
}
}
Error message: VariableDeclarationInitDemo2.java:11:
variable myVar2 might not have been initialized
System.out.println(myVar2);
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 19 / 42
Example: Variable Declaration and Initialization
// Filename: VariableDeclarationInitDemo3.java
/* An example demonstrating how to declare and initialize
variables to store data of different primitive type */
public class VariableDeclarationInitDemo3 {
public static void main(String[] args) {
float myVar1 = 2.7125f; // A letter f is at the end. Why?
double myVar2 = 5.8602921052123;
char myVar3 = 'a', myVar4 = '@', myVar5 = '#';
boolean myVar6 = true, myVar7 = false;
System.out.println(myVar1);
Screen output:
System.out.println(myVar2);
2.7125
System.out.println(myVar3);
5.8602921052123
System.out.println(myVar4);
a
System.out.println(myVar5);
@
System.out.println(myVar6);
#
System.out.println(myVar7);
true
}
false
}

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 20 / 42


Final Notes about Variable Declaration
You cannot use the same name for two variables
I If do so, error will occur (already defined error)
Although “ ” and “$” are valid characters to begin a variable name,
you are not recommend to do so. Instead you are suggested to begin
a variable name with a letter
As Java is a case-sensitive language, it treats variables differ in
meaning based on differing use of uppercase and lowercase letters
I For example, variable names ”myVar” and ”MyVar” are treated as two
different variables
Meaningful variable names make program more readable
I For example, tax is certainly better than t

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 21 / 42


Constant Variable
Sometimes we would prefer to declare a
variable with value that cannot be altered
once the initial value is assigned
I Example: PI is always equal to 3.14159,
which is a fact and should not be changed
in any case
A variable that cannot be altered is called
”constant variable”
Syntax
final <type> <CONSTANT VARIABLE NAME> = <value>;
where <type> is the type of data that your variable would like to store,
<CONSTANT VARIABLE NAME> is the name of constant variable in program,
<value> is the final value

During compilation, the value of the constant will be substituted whenever


the name of the constant appears in the program
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 22 / 42
Constant Variable Declaration

// Filename: ConstantDeclarationDemo.java
/* An example demonstrating how to declare constant
variables to store the value of pi */
public class ConstantDeclarationDemo {
public static void main(String[] args) {
final double PI = 3.14159;
// For this statement, Java will first convert
// PI from double to String and then perform
// string concatenation
// + is a string concatenation operator
System.out.println("The value of PI is " + PI);
}
} Screen output:
The value of PI is 3.14159
Using constant variable improves the readability of the program and makes
programs easier to be modified

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 23 / 42


Recap: Java Convention & Good Programming Style
Using meaningful names
Class names
I The first letter of each word in the class name should be capitalized
(e.g. WelcomeStudents)
Variable names
I Lowercase letters should be used for variables with single word
I If the name consists of several words, we then use lowercase for the
first letter of the first word, and use capital letter for the first letter of
subsequent words (e.g. myVar)
Constant variable names
I Uppercase letters should be used for symbolic constants (e.g. PI), and
underscores should be used to separate between words (e.g.
MAX LIMIT)

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 24 / 42


Part III

Basic Java Input and Output

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 25 / 42


Basic Java Input and Output (I/O)

Two very basic elements in a Java program are:


1. Displaying data on monitor’s screen (Output)
2. Getting user’s input from keyboard (Input)
Through Java I/O, user and computer interact with each other

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 26 / 42


Display Data on Monitor’s Screen
Java provides two methods to display data
on monitor’s screen (specifically is the
command window)
1. System.out.print()
2. System.out.println()

System.out is a standard output object, i.e., an


object with methods that output data to screen

Syntax
System.out.print(<data> [ +<data> ]);
System.out.println(<data> [ +<data> ]);
System.out.println();
where <data> is the type of data that you would like to display, <data> can be
in types: byte, short, int, long, float, double, char, boolean, String, etc. [...] may
be repeated zero or more times, but must be separated by +

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 27 / 42


Output Data on Screen

// Filename: OutputDataDemo1.java
/* An example showing how to output data on screen */
public class OutputDataDemo1 {
public static void main(String[] args) {
int val = 9;
System.out.println(val);
System.out.print("You should be able to see this text ");
System.out.println("on screen");
System.out.print("How about this text?");
System.out.print("Can you see the effect?");
}
}
Screen output:
9
You should be able to see this text on screen
How about this text?Can you see the effect?

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 28 / 42


Output Data on Screen
// Filename: OutputDataDemo2.java
/* An example showing how to output different types
of data on screen */
public class OutputDataDemo2 {
public static void main(String[] args) {
String str = "Desmond";
char gender = 'M';
int age = 18;
double height = 1.72;
System.out.println("Hi " + str);
System.out.println("Your age is " + age);
System.out.println("Your gender is " + gender);
System.out.println("Your height is " + height + 'm');
}
} Screen output:
Hi Desmond
Your age is 18
Your gender is M
Your height is 1.72m
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 29 / 42
Get User’s Input from Keyboard
Java provides a class named ”Scanner” for getting user’s input from
keyboard
The Scanner class is a part of the package java.util
I Package is a collection of classes
To use the Scanner class, you can follow the syntax shown below
Syntax
// Put the following line at the top of the Java source file
import java.util.Scanner;

Scanner <object name> = new Scanner(System.in);


<variable name> = <object name>.<method name>();
<object name>.close();
where <object name> is the name of the newly created Scanner class object, new
is the keyword to create an object, <variable name> is the name of the variable
to store the data obtained from the keyboard using Scanner method

Note: Make sure the variable with <variable name> has been declared
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 30 / 42
Scanner Class Methods
Method Description
boolean nextBoolean() Returns the next input token as a Boolean value
byte nextByte() Returns the next input token as a byte value
short nextShort() Returns the next input token as a short value
int nextInt() Returns the next input token as an int value
long nextLong() Returns the next input token as a long value
float nextFloat() Returns the next input token as a float value
double nextDouble() Returns the next input token as a double value
String next() Returns the next input token as a String value
String nextLine() Returns all input remaining on the current line
as a String value
The “Method” column describes two things: name of the method and
type of data returned
For instance: int nextInt()
I This means the name of the method for obtaining an int from keyboard
is nextInt, and
I The keyword int means it returns an int, which is the integer it obtains

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 31 / 42


Example: Input Data from Keyboard
// Filename: InputDataDemo1.java
/* An example showing how to get input
from keyboard */ Screen output:
import java.util.Scanner;
Enter your name: Tom
public class InputDataDemo1 {
Enter your age: 18
public static void main(String[] args) {
Enter your gender: M
Scanner sc = new Scanner(System.in);
Enter your height: 1.71
System.out.print("Enter your name: ");
String name = sc.nextLine(); Your name is Tom
System.out.print("Enter your age: "); Your age is 18
int age = sc.nextInt(); Your gender is M
System.out.print("Enter your gender: "); Your height is 1.71
String gender = sc.next();
System.out.print("Enter your height: ");
double height = sc.nextDouble();
sc.close();
System.out.println();
System.out.println("Your name is " + name);
System.out.println("Your age is " + age);
System.out.println("Your gender is " + gender);
System.out.println("Your height is " + height);
}
}

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 32 / 42


Get User’s Input from Keyboard
Users are allowed to enter more than one values (separated by blank
spaces) in one line
With successive calls of Scanner’s methods, all the entered values can
be read
For example
System.out.print("Read user input data: ");
Scanner sc = new Scanner(System.in);
int data1 = sc.nextInt();
int data2 = sc.nextInt();
int data3 = sc.nextInt();
Output:
Read user input data: 10 20 30

Input data can be separated by blank spaces such that Java reads each
chunk of data and assigns it to the respective variable, i.e. 10 to data1, 20
to data2, 30 to data3 respectively

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 33 / 42


Example: Input Data from Keyboard
// Filename: InputDataDemo2.java
/* An example showing how to get input from keyboard */
import java.util.Scanner;
public class InputDataDemo2 {
public static void main(String[] args) {
int data1, data2, data3;
double real1, real2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter three integers: ");
data1 = sc.nextInt();
data2 = sc.nextInt();
data3 = sc.nextInt();
System.out.print("The three integers are: ");
System.out.println(data1 + " " + data2 + " " + data3);
System.out.print("Enter two double values: ");
real1 = sc.nextDouble();
real2 = sc.nextDouble();
sc.close();
System.out.println("The two doubles are: ");
System.out.print(real1 + " " + real2);
}
}

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 34 / 42


Example: Input Data from Keyboard (Cont’d)

Screen output:

Enter three integers: 10 20 30


The three integers are: 10 20 30
Enter two double values: 1.123
4.3567
The two doubles are:
1.123 4.3567

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 35 / 42


Free Format
The difference in indentation does not disturb Java compiler to
translate the source code into bytecode
However, if the indentation is bad, it does affect you to read and hard
to fix the errors (“fix errors” is typically called “fix bugs”)
// Filename: BadIndentation.java
/* An example showing bad indentation */
public class BadIndentation
{
public static void main(String[] args)
{
System.out.println("Hello Students");
}
}

// Filename: GoodIndentation.java
/* An example showing good indentation */
public class GoodIndentation
{
public static void main(String[] args)
{
System.out.println("Hello Students");
}
}
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 36 / 42
Good Programming Style
To write code that are readable, programs are generally formatted /
indented using the rules as follows:
I Put class and method (operation) headers on lines by themselves
I Put no more than one statement on each line (a statement is ended
with a semi-colon, i.e., ; )
I Indent your program properly
F When an opening brace appears, increase the indentation of the
following lines
F When a closing brace appears, reduce the indentation
F Indent statements inside curly braces by a consistent number of spaces
(a common choice is 3 spaces per level of indentation)
I Use blank lines to separate parts of the program
(e.g., methods / operations)

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 37 / 42


Good Programming Style

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 38 / 42


Key Terms
Object-Oriented Access modifier
Programming (OOP) Comments
Class Variables
Object Constant variables
Data / Attributes / States Primitive data types
Operations / Actions / Literals
Behaviors Declaration and initialization
Blueprint / Template Reserved words
Instance variables / Data Case-sensitive
members
Java convention
Methods / Member
Java I/O
functions
Free format
User-defined classes
Good programming style
Java pre-defined classes
Indentation
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 39 / 42
Review Questions
Fill in the blanks in each of the following sentences about the Java environment
1. Every class declaration contains keyword followed immediately
by class’s name
2. begins and end-of-line comments.
3. Java applications begin execution at method .
4. A(n) begins the body of the main method, and a(n)
ends the body of the main method.
5. Every statement ends with a(n) .
6. Methods and display information in the
command window.
7. Keyword creates an object of the class specified to the right of
the keyword.

Answer: 1. class, 2. Double-slash(//), 3. main, 4. left-brace ({), right-brace (}),


5. semi-colon (;), 6. print, println, 7. new
Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 40 / 42
Further Reading
Read Section 2.1 - 2.10 of
”Introduction to Java Programming and Data Structures:
Comprehensive Version” textbook

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 41 / 42


That’s all!
Any questions?

Rm 3553, desmond@ust.hk COMP1022P (Spring 2020) 42 / 42

You might also like