Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

03 - CSC 202 - Basics of Java Programming

Uploaded by

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

03 - CSC 202 - Basics of Java Programming

Uploaded by

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

BASICS OF JAVA PROGRAMMING

• Variables and Data Types


• Operators and Expressions
• Input and Output
• Comments

VARIABLES
In Java, variables are named storage locations used to store and manipulate data. Variables
are an essential part of Java programming, and they come in various types to represent
different kinds of data.

Declaration: Before using a variable, it must be declared with a specific data type. The
declaration provides information about the type of data the variable can hold.
Examples:
int age; // Declaration of an integer variable

double temperature; // Declaration of a double-precision floating-point variable

Initialisation: Initialisation involves assigning an initial value to the variable. Variables can be
initialised when declared or later in the code.
Examples:
int age = 20; // Declaration and Initialization of an integer variable

double temperature; // Declaration of a double-precision floating-point variable

temperature = 37.5; // Initialization later in the code

Rules for Naming a Variable


• Variable names must start with a letter, underscore (_), or a dollar sign ($).
• Variable names can include letters, digits, underscores, and dollar signs.
• Variable names are case-sensitive, so "count" and "Count" are considered different
variables.
• Variable names should be descriptive and follow naming conventions (e.g., camelCase for
local variables, PascalCase for class names, and UPPERCASE for constants).

Variable Scope and Lifetime


The scope of a variable defines where it is accessible in the code, while the lifetime refers to
how long it exists in memory.
Local variables are limited to the block or method in which they are declared. They are
created when the block is entered and destroyed when it exits.
Instance variables (non-static fields) belong to an instance of a class and are accessible from
any method within that instance. They exist as long as the object they belong to exists.
Class variables (static fields) are shared among all class instances. They are associated with
the class and exist for the duration of the program’s execution.

DATA TYPES
As the name suggests, data types specify the type of data that can be stored inside variables
in Java. Java is a statically typed language. This means that all variables must be declared
before they can be used. There are two types of data types in Java: Primitive and Non-
primitive data types.
1. Primitive data types: The primitive data types are the predefined data types in Java,
which include boolean, char, byte, short, int, long, float and double.
a. Boolean type: The boolean data type represents a boolean value, which can be true
or false. Booleans are commonly used for logical operations and conditional
statements. The default value is false.
Example: boolean isPrime = true;

b. Byte type: The byte data type represents a whole number (integers) within the range
of -128 to 127 (8-bit signed two’s complement). The default value is 0.
Example: byte num = 120;

c. Short type: The short data type represents a whole number (integers) within the
range of -32768 to 32767. The default value is 0.
Example: short num = 32000;

d. Int type: The int data type represents a whole number (integers) within the range of -
231 (2,147,483,648) to 231-1 (2,147,483,647) (32-bit signed two’s complement). The
default value is 0.
Example: int num = 550000;

e. Long type: The byte data type represents a whole number (integers) within the range
of -263 to 263 (64-bit signed two’s complement). The default value is 0.
Example: long num = 30000000000L;
Notice the use of L at the end of 30000000000. This represents that it’s an integer of
the long type.

f. Float type: The float data type represents a single-precision 32-bit floating-point
type (numbers with a fractional part). The default value is 0.0f
Example: float num = -39.8f;

Notice the use of f at the end of 39.8. in the example above, it is necessary to tell the
compiler to treat -39.8f as float instead of double. A decimal number without the f at
the end is a double by default.

g. Double type: The double data type represents a double-precision 64-bit floating-
point type (numbers with a fractional part). The default value is 0.0d.
Example: double num = -39.8;

h. Char type: The char data type represents a single character and stores letters, digits,
and special symbols. Characters are enclosed in single quotes (e.g., 'A', '5', '$').
Example: char character = ‘z’;

2. Non-primitive data types: The non-primitive data types or reference types are user-
defined data types in Java, which include Strings, Classes, Interfaces, and Arrays.

OPERATORS
In Java, operators are special symbols that perform operations on operands (variables, values,
or expressions). Java provides a wide range of operators that can be categorised into different
groups based on their functionality. Operators in Java can be classified into Arithmetic,
Assignment, Relational, Logical, Unary and Bitwise Operators.
1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic operations on
variables and data.

Operator Operation

+ Addition

- Subtraction

* Multiplication
/ Division

% Modulo Operation (Remainder after division)

class Main {
public static void main (String[] args) {

// declare and initialize variables


int a = 37;
int b = 5;

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));
}
}

Running the above program with output


a + b = 42
a - b = 32
a * b = 185
a / b = 7
a % b = 2

In the above output, notice that the 37 / 5 = 7 instead of 7.4. In Java, if the division operator
is applied to two integer operands, the result will also be an integer where the quotient is
truncated. However, if one of the operands is a floating-point number, the result will be floating-
point. The modulo operator % computes the remainder, 37 % 5 = 2 because the result 7
remainder 2. The % operator is mainly used with integers.
2. Assignment Operators: The assignment operators are used to assign values to variables.
Example: The = assignment operator assigns the value ‘A’ to the variable grade.
char grade;
grade = ‘A’;

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

3. Relational Operators: Relational operators are used to check the relationship between two
operands and return true or false. Relational operators are used in decision-making and
loops.
Example: a < b // checks if a is less than b

Operator Description Example

== Is Equal To 7 == 5 returns false

!= Not Equal To 7 != 5 returns true

> Greater Than 5 > 7 returns false

< Less Than 5 < 7 returns true

>= Greater Than or Equal To 5 >= 7 returns false

<= Less Than or Equal To 5 <= 7 returns true

4. Logical Operators: Logical operators are used to check whether an expression


is true or false. They are used in decision-making.
Operator Example Meaning

expression1 && true only if both expression1 and


&& (Logical AND)
expression2 expression2 are true

expression1 || true if either expression1 or


|| (Logical OR)
expression2 expression2 is true

true if expression is false and


! (Logical NOT) !expression
vice versa

class Main {
public static void main (String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // prints true
System.out.println((5 > 3) && (8 < 5)); // prints false

// || operator
System.out.println((5 < 3) || (8 > 5)); // prints true
System.out.println((5 > 3) || (8 < 5)); // prints true
System.out.println((5 < 3) || (8 < 5)); // prints false

// ! operator
System.out.println(!(5 == 3)); // prints true
System.out.println(!(5 > 3)); // prints false
}
}

5. Unary Operators: Unary operators are used with only one operand. For example, ++ is
a unary operator that increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:

Operator Meaning

Unary plus: not necessary to use since numbers


+
are positive without using it

- Unary minus: inverts the sign of an expression


++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

Logical complement operator: inverts the


!
value of a boolean

++ and -- operator as prefix and postfix


• If you use the ++ operator as a prefix like ++var, the value of var is incremented by
1; then it returns the value.
• If you use the ++ operator as a postfix like var++, the original value of var is returned
first; then, var is incremented by 1.

class Operator {
public static void main (String[] args) {
int x = 5, y = 5;

// 5 is displayed
// Then, x is increased to 6.
System.out.println(x++);

// y is increased to 6
// Then, y is displayed
System.out.println(++y);
}
}

6. Bitwise Operators: Bitwise operators in Java are used to perform operations on individual
bits. Bitwise operators in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift


>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

Example: Bitwise complement operation of 55


55 = 00110111 (In Binary)

~ 00110111
________
11001011 = 203 (In decimal)

BASIC INPUT AND OUTPUT


Java Output
In Java, the System.out.println() method is used to print output to the console (screen). It can
be used with variable, strings and any other data types.
Example:
int age = 25;
System.out.println("The age is: " + age);

In the above example, System is a class, out is a public static field that accepts output data.
Other output methods are: System.out.print(), System.out.printf(). The print() prints the
output data and keep the cursor on the same line, while println() moves the cursor to the next
line. The printf() method on the other hand, provides string formatting.

class PrintVariables {
public static void main(String[] args) {

int score = 49;


System.out.println("your score is " + "score");
}
}

The above program will print “your score is 49” to the screen. The + operator, in this case, is
used on strings for concatenation (joining of strings).
Java Input
Java provides different ways to get input from the user. However, in this class, we will learn
how to get input from users using the object of the Scanner class. In order to use the object
of Scanner, we need to import java.util.Scanner package.

Getting Integer Input from Users


import java.util.Scanner; // import the Scanner class

class Input {
public static void main (String[] args) {

Scanner input = new Scanner(System.in); // create a Scanner object

System.out.print("Enter an integer: ");


int number = input.nextInt(); // read input from user
System.out.println("You entered " + number);

// closing the scanner object


input.close(); // close the Scanner object
}
}

To get input of long, float, double, and string, we use the nextLong(), nextFloat(),
nextDouble(), and next() methods, respectively.

JAVA EXPRESSIONS, STATEMENTS AND BLOCKS


Java Expressions: An expression is a construct that evaluates to a single value. Expressions can
consist of variables, operators, method calls, and literals, which are resolved to produce a single
value. Examples of expressions include arithmetic expressions, logical expressions, and method
invocations that return a value.

Java Statements: A statement is a complete command that expresses some action. In Java,
statements represent executable units of code. Java supports various types of statements, such
as declaration statements, control flow statements, loop statements, and branching statements.
Java Blocks: A block is a group of statements (zero or more) enclosed in curly braces { }.
Blocks can be used wherever a single statement is allowed. They enable the creation of
compound statements, local variable declarations, and method declarations.

class Main {
public static void main(String[] args) {

int score = 49;

if (score >= 50) { // start of block


System.out.print("Hey, you passed");
} // end of block
}
}
In the above example, aside from the if block, we also have the main method block and the
class block all enclosed in the { }.
Expressions are used where values are needed, such as in variable assignments or method
parameters. Statements are complete lines of code that perform some action, such as declaring
variables, invoking methods, or controlling the flow of execution.

JAVA COMMENTS
In computer programming, comments are a portion of the program that are completely ignored
by Java compilers. They are mainly used to help programmers to understand the code. For
example,

Types of Comments in Java


In Java, there are two types of comments:
• Single-line comment: A single-line comment starts and ends in the same line. To write a
single-line comment, we use the // symbol. We have used single-line comments in the
programs written in the lecture notes.
Example:
// This is a single-line comment in Java
int score = 55; // This line declares and initialises the variable score
• Multi-line comments: They can span multiple lines and are often used for longer explanations
or temporarily commenting out a block of code. Multi-line comments start with /* and end
with */.
Example:
/*
This is a multi-line comment
It can span multiple lines
*/
int score = 10; // This line declares and initialises the variable score

• Documentation Comments: They are used for generating documentation from the source
code and are commonly used to create API documentation. Documentation comments, or
Javadoc comments, begin with /** and end with */.
Example
/**
* This method calculates the sum of two numbers.
* @param a the first number
* @param b the second number
* @return the sum of a and b
*/
public int calculateSum (int a, int b) {
return a + b;
}

You might also like