Notes 5
Notes 5
Notes 5
PROGRAMMING
Creating a Class
Creating a Class
Every line of code that runs in Java must be inside a class. In our
example, we named the class Main. A class should always start with
an uppercase first letter.
The main Method
The main() method is required and you will see it in every Java
program:
Inside the main() method, we can use the println() method to print a
line of text to the screen:
Exercise
Java Comments
To create a variable that should store text, look at the following
example:
int
To create a variable that should store a number, look at the following
example:
int
You can also declare a variable without assigning the value, and
assign the value later:
int
However, you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the variable as
"final" or "constant", which means unchangeable and read-only):
Other Types
To declare more than one variable of the same type, use a comma-
separated list:
Java Identifiers
Type casting is when you assign a value of one primitive data type to
another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size
type to a larger size type:
Narrowing Casting
Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
Java Operators
In the example below, we use the + operator to add together two
values:
Java Operators (cont....)
Although the + operator is often used to add together two values, like
in the example before, it can also be used to add together a variable
and a value, or a variable and another variable:
Type of Java Operator
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
If you add two strings, the result will be a string concatenation:
If you add a number and a string, the result will be a string
concatenation:
End of Introduction to
Object Oriented
Programming
Prepared By :