0% found this document useful (0 votes)
43 views15 pages

201 Lecture 2 2024

The document discusses Java syntax, data types, variables, and keywords. It provides details on the structure of a Java program including classes, methods, and how to print output. It also explains primitive and non-primitive data types in Java including boolean, byte, short, int, long, float, double, char, arrays, classes and objects.

Uploaded by

Aliyu Umar Isa
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)
43 views15 pages

201 Lecture 2 2024

The document discusses Java syntax, data types, variables, and keywords. It provides details on the structure of a Java program including classes, methods, and how to print output. It also explains primitive and non-primitive data types in Java including boolean, byte, short, int, long, float, double, char, arrays, classes and objects.

Uploaded by

Aliyu Umar Isa
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/ 15

SOKOTO STATE UNUVERSITY

DEPARTMENT OF COMPUTER SCIENCE


CSC 201: INTRODUCTION TO PROGRAMMING LECTURE 2

Java Syntax

Every line of code that runs in Java must be inside a class. We will name the class Main in the
coming example below. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: "MyJava" and "myjava" has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class
name and add ".java" to the end of the filename.
The main Method

The main() method is required and you will see it in every Java program:

public static void main (String [] args)

Any code inside the main() method (between the curly braces {}) will be executed. Don't worry
about the keywords before and after main..

For now, just remember that every Java program has a class name which must match the
filename, and that every program must contain the main() method System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen:

public class Main {

public static void main (String[args]) {

System.out.println("Hello world");

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include Boolean, char, byte, short, int, long, float
and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in java
Note that: Java is a statically-typed programming language. It means, all variables must be
declared before its use. That is why we need to declare variable’s and name.

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
e.g. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
Example:
byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
Example:
short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is
2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807 (2^63 -1) (inclusive). Its
minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of
Unicode system. To get detail explanation about Unicode visit next page.

Non-primitive data types


Unlike primitive data types, these are not predefined. These are user-defined data types created
by programmers. These data types are used to store multiple values.
For example an array that stores a group of values. Class is also a primitive type that stores
different methods and variables. Which is why they are also called advanced data types in Java.
Whenever a non-primitive data type is defined, it refers a memory location where the data is
stored in heap memory i.e., it refers to the memory location where an object is placed. A non-
primitive data type variable is also called referenced data type or simply object reference
variable.
An object reference variable lives on the stack memory and the object to which it points always
lives on the heap memory. The stack holds a pointer to the object on the heap.
In Java programming, all non-primitive data types are simply called objects that are created by
instantiating a class.
\
Types of Non-primitive data types
There are four types of non-primitive data types in Java. They are as follows:
• Class
• Object
• String
• Array

Class and objects:


A class in Java is a user defined data type i.e. it is created by the user. It acts a template to the
data which consists of member variables and methods.
An object is the variable of the class, which can access the elements of class i.e. methods and
variables.

String:
A string represents a sequence of characters for example "Javatpoint", "Hello world", etc. String
is the class of Java.
One of the ways to create a string and store a value in it is shown below:
String str = "You're the best";
Here, String type variable str has the value "You're the best".

Array:
An array is a data type which can store multiple homogenous variables i.e., variables of same
type in a sequence. They are stored in an indexed manner starting with index 0. The variables
can be either primitive or non-primitive data types.

Difference between Primitive and Non-primitive Data types in Java


In Java, the primitive data types are system defined but we have to create and define the non-
primitive data types.
In primitive data type, variables can store only one value at a time but in non-primitive data
types, either multiple values of the same type or different type or both can be stored.
All the data for primitive type variables are stored on the stack whereas, for reference types, the
stack holds a pointer to the object on the heap.
A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase
letter.
The size of a primitive type depends on the data type, while non-primitive types have all the
same size.

Java Variables
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed
e.g. int data=50;//Here data is variable.

Identifier/variable Naming Rules


Identifiers are the names you give to user-defined items in 4Test code. These items include
constants, variables, functions, methods, properties, windows, window classes, and data
types.
Identifiers have the following naming rules:
i. They are case-sensitive. That is, "myvar" and "MyVar" are not the same.
ii. They begin with an alphabetic character or an underscore (_).
iii. They include any combination of alphabetic characters, numerals, and underscore
characters. They can contain single-byte international characters, such as é and ñ.
iv. All characters are significant.
v. They do not contain a space.
vi. Must not contain java reserve words

Types of Variables
There are three types of variables in Java:
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Example to understand the types of variables in java

Reserved Words
Which Words are reserved in Java?
Keywords are special identifiers that are reserved by the compiler. You can use a keyword only
as a keyword, not as an identifier name or function name. Case is significant in keywords, so
"exit" is a reserved word, but "EXIT" and "Exit" are not.
Type names, shown in CAPITALS below, are also reserved by the compiler. You can use a type
name only as a type name, not as an identifier name or function name. Unlike keywords, type
names are not case-sensitive, so "CHAR" and "char" are both reserved words.
The Boolean constants TRUE and FALSE are also reserved by the compiler and are case
insensitive.
The following are reserved words in the 4Test language:
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
• Java Operator Precedence
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Java Arithmetic Operator Example
Java Arithmetic Operator Example: Expression

Java Left Shift Operator Example

The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.

Java AND Operator Example: Logical && vs Bitwise &


Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left.
Java Assignment Operator Example

Java Assignment Operator Example


Types of Errors in Java
Basically, error is any obstacle that could prevent compiler from executing the program or yields
the wrong output or even triggers the java to crash.
We have three types of errors in java:

 Syntax Error
 Logical Error
 Run Time Error

Syntax Error
The syntax error occurs when one of the java rules is compromised. The line of code that has the
error will be underline with a red line. Some of the rule that triggers syntax errors includes;
misspelled of java key words, termination at the end of line, inappropriate use of brackets,
coding out of main method or class, a wrong identifier, wrong data type and etc.
Example
Explanation;
Line 3. A variable X is declared as type int but the value initialized to it was of type double.
Line 4. A variable Y is declared as double but a string value is initialized to it.

Line 5. A variable Z is declared as int data type. Similarly, int value is saved in it but the error
is that the line is not terminated with semicolon.

Line 6. The data type is correct, the value initialized to the data type is correct, the line has been
terminated but the variable is not correct

Logical Error
Logical errors are an error that yields incorrect output; this type of errors allows the programs to
execute but gives out the incorrect results. It usually happens when someone use greater than
instead of less than, plus instead of minus, ++ instead of - -, and etc. so the compiler is not smart
enough to know that user is not meant the type of operations he/she used.

Example: “the below example is the simulation of the Nigerian System of voting. According to
the law only citizen that their age is greater or equal to 18 can vote. But in this example a person
of 10years is allow to vote, simply because we made logical errors, we use less than instead of
greater than.”
Output

Runtime Errors

Runtime Errors occur during the execution of a program, due to lack of system resources, or due
to irrelevant input by the user. The compiler has no idea whatsoever how to detect these kinds of
errors. For example, dividing a number by 0, accessing an element from an array that is out of
range, trying to convert an invalid string to an integer, out of memory error, etc.

Example; “In the example, we divide the number by 0 which is not possible, as a result it gives
us runtime error”.
Output

You might also like