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

DCIT 22 Computer Programming 1 Lecture 4

Uploaded by

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

DCIT 22 Computer Programming 1 Lecture 4

Uploaded by

Norvin Lincallo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

JAVA BASIC

DCIT 22 –
COMPUTER
PROGRAMMING 1
JAVA BASIC
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class, object,
methods, and instance variables mean.

• Object − An object is a real-world entity that can be identified distinctly. For example, a desk, a
circle can be considered as objects. An object has a unique behavior, identity, and state. Data
fields with their current values represent the state of an object (also known as its properties or
attributes).

• Class A class is a template or blueprint or prototype that defines data members and methods of
an object. An object is the instance of the class. We can define a class by using the class
keyword.
JAVA BASIC
• Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.

• Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
FIRST JAVA PROGRAM
We will learn how to write the simple program of java.
Creating Hello World Example

Let’s Create the hello world Java Program:


1. class HelloWorld{
2. public static void main(String args[]){
3. System.out.println("Hello World");
4. }
5. }

Output: Hello World


BASIC SYNTAX
About Java programs, it is very important to keep in mind the following
points.

• Case Sensitivity − Java is case sensitive, which means identifier Hello


and hello would have different meaning in Java.

• Class Names − For all class names the first letter should be in Upper
Case. If several words are used to form a name of the class, each inner
word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
BASIC SYNTAX CONT…
• Method Names − All method names should start with a Lower Case
letter. If several words are used to form the name of the method, then
each inner word's first letter should be in Upper Case.

Example: public void myMethodName()


BASIC SYNTAX CONT…
• Program File Name − Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).

But please make a note that in case you do not have a public class present in the file
then file name can be different than class name. It is also not mandatory to have a
public class in the file.

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'
BASIC SYNTAX CONT…
• public static void main(String args[]) − Java program processing
starts from the main() method which is a mandatory part of every Java
program.
JAVA IDENTIFIERS
All Java components require names. Names used for classes,
variables, and methods are called identifiers.
In Java, there are several points to remember about identifiers.
They are as follows −

• All identifiers should begin with a letter (A to Z or a to z), currency


character ($) or an underscore (_).

• After the first character, identifiers can have any combination of


characters.
JAVA IDENTIFIERS CONT…
• A key word cannot be used as an identifier.

• Most importantly, identifiers are case sensitive.

• Examples of legal identifiers: age, $salary, _value, __1_value.

• Examples of illegal identifiers: 123abc, -salary.


JAVA MODIFIERS
Like other languages, it is possible to modify classes, methods, etc., by
using modifiers. There are two categories of modifiers −

• Access Modifiers − default, public , protected, private

• Non-access Modifiers – static, final, abstract, synchronized, transient,


volatile, native
JAVA VARIABLES
Following are the types of variables in Java −

• Local Variables – This is a variable that declared inside the body of a method.

• Instance Variables – This Java variable is defined without the STATIC keyword, but as
outside of a method declaration. They are object-specific variables, which is why they are
known by this name.

• Static Variables – This variable is initialized only once, just when the program execution
starts. It is the variable that should be initialized first, especially before an instance variable is
initialized.
JAVA VARIABLES EXAMPLE
public class A
{
static int m = 100; //static variable
void method()
{
int n = 90; //local variable
}
public static void main(String args[])
{
int data = 50; //instance variable
}
}//end of class
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
JAVA KEYWORDS CONT…
private protected public return
short static strictfp super

switch synchronized this throw


throws transient try void
volatile while
COMMENTS IN JAVA
• Java supports single-line
and multi-line comments very
similar to C and C++. All characters
available inside any comment are
ignored by Java compiler.
VARIABLES
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form of
a variable declaration −
Here data type is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated list.
VARIABLES CONT…
Following are valid examples of variable declaration and initialization in Java −

int a, b, c; //Declares three ints, a, b, and c.


int a = 10, b = 10; //Example of initialization
byte B = 22; //initializes a byte type variable B.
double pi = 3.14159; //declares and assigns a value of PI.
char a = ‘a’ //the char variable a is initialized with value ‘a’
string name = “Henry” //the string variable name is initialized with value “Henry”
VARIABLES CONT…
• There are eight basic types
for the storage of integers, floating-point
numbers, character, and Boolean values.
Types Memory size Values that can be stored
These often are called primitive types
byte 8 bits -128 to 127
because they are built-in parts of the Java
short 16 bits -32,768 to 32,767
language
int 32 bits -2,147,483,648 to 2,147,483,647

-9,223,372,036,854,775,808 to
long 64 bits
• There are four data types 9,223,372,036,854,775,807
you can use to store integers which one
you use depends on the size of the
integers.
VARIABLES CONT…
Another types of number that can be stored is a floating-point number, which has the
type float or double. The float type should be sufficient for most uses because it can handle
number from 1.4E-45 to 3.4E+38. If not, the double type can be used for more precise numbers
ranging from 4.9E-324 to 1.7E+308

The char type is used for individual characters, such as letters, numbers, punctuation,
and other symbols.

The last of the eight primitive data types is boolean. This data type holds either true or
false in Java.
BASIC OPERATORS
1. The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the


same way that they are used in algebra. The following table lists the
arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20,


then −
Operator Description Example

ARITHMETI + (Addition) Adds values on either side of the operator. A + B will give 30

C - (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10

OPERATORS * (Multiplication) Multiplies values on either side of the operator. A * B will give 200

CONT… / (Division) Divides left-hand operand by right-hand operand. B / A will give 2

Divides left-hand operand by right-hand operand and


% (Modulus) B % A will give 0
returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19


BASIC OPERATORS CONT…
2. The Relational Operators

There are following relational operators supported by Java


language.

Assume variable A holds 10 and variable B holds 20, then −


Operator Description Example

Checks if the values of two operands are equal or not, if yes then condition
== (equal to) (A == B) is not true.
becomes true.

!= (not equal to)


Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true.
(A != B) is true.
RELATIONAL
> (greater than)
Checks if the value of left operand is greater than the value of right operand,
if yes then condition becomes true.
(A > B) is not true. OPERATORS
< (less than)
Checks if the value of left operand is less than the value of right operand, if
(A < B) is true.
CONT…
yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the value of
>= (greater than or equal to) (A >= B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than or equal to the value of right
<= (less than or equal to) (A <= B) is true
operand, if yes then condition becomes true.
BASIC OPERATORS CONT…
2. The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds


false, then −
LOGICAL OPERATORS CONT…
Operator Description Example

Called Logical AND operator. If both the operands are


&& (logical and) (A && B) is false
non-zero, then the condition becomes true.

Called Logical OR Operator. If any of the two operands


|| (logical or) (A || B) is true
are non-zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the


! (logical not) logical state of its operand. If a condition is true then !(A && B) is true
Logical NOT operator will make false.
BASIC OPERATORS CONT…
2. The Assignment Operators

Following are the assignment operators supported by Java


language −
Operator Description Example

Simple assignment operator. Assigns values from right side operands

ASSIGNMEN
= C = A + B will assign value of A + B into C
to left side operand.

T
Add AND assignment operator. It adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left operand.

OPERATORS -=
Subtract AND assignment operator. It subtracts right operand from
the left operand and assign the result to left operand.
C -= A is equivalent to C = C – A

CONT…
Multiply AND assignment operator. It multiplies right operand with
*= C *= A is equivalent to C = C * A
the left operand and assign the result to left operand.

Divide AND assignment operator. It divides left operand with the


/= C /= A is equivalent to C = C / A
right operand and assign the result to left operand.

Modulus AND assignment operator. It takes modulus using two


%= C %= A is equivalent to C = C % A
operands and assign the result to left operand.
JAVA CONDITIONS AND IF
STATEMENTS
Java supports the usual logical conditions from mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.
JAVA CONDITIONS AND IF STATEMENTS
CONT…
Java has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified


condition is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first condition is
false
• Use switch to specify many alternative blocks of code to be executed
THE IF STATEMENT
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax

if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
THE IF STATEMENT CONT…
In the example below, we test two values to find out if 20 is greater than
18. If the condition is true, print some text:

Example:

if (20 > 18) {


System.out.println("20 is greater than 18");
}
THE IF STATEMENT CONT…
We can also test variables:

Example:

int x = 20;
int y = 18;

if (x > y) {
System.out.println("x is greater than y");
}
THE ELSE STATEMENT
Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
THE ELSE STATEMENT CONT…
Example:

int time = 20;

if (time < 18) {


System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
THE ELSE STATEMENT CONT…
Example explained:

In the example above, time (20) is greater than 18, so the condition is
false. Because of this, we move on to the else condition and print to the
screen "Good evening". If the time was less than 18, the program would
print "Good day".
THE ELSE IF STATEMENT
Use the else if statement to specify a new condition if the first condition
is false.

Syntax:

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
THE ELSE IF STATEMENT CONT…
Example:

int time = 22;

if (time < 10) {


System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
THE ELSE IF STATEMENT CONT…
Example explained:

In the example above, time (22) is greater than 10, so the first condition
is false. The next condition, in the else if statement, is also false, so we
move on to the else condition since condition1 and condition2 is both
false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."
THANK YOU!
Fonts used: Roboto Mono and Gugi

You might also like