CPE402 Chapter3 Programming Language Fundamentals - Final
CPE402 Chapter3 Programming Language Fundamentals - Final
JAVA PROGRAMMING
LANGUAGE
FUNDAMENTALS
PREPARED BY: ENGR. ERWIN S. COLIYAT, LECTURER I
BATANGAS STATE UNIVERSITY - PB MAIN II
COLLEGE OF ENGINEERING ARCHITECTURE AND FINE ARTS
CHAPTER 3.1
JAVA NAMING
CONVENTION
NAMING CONVENTIONS
Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.
All the classes, interfaces, packages, methods and fields of Java
programming language are given according to the Java naming convention. If
you fail to follow these conventions, it may generate confusion or erroneous
code.
All Java components require names. Names used for classes, variables and
methods are called identifiers.
Naming conventions in Java make programs more understandable by making
them easier to read.
NAMING CONVENTIONS
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
CamelCase in JAVA
Java follows camel-case syntax for naming the class, interface,
method, and variable.
If the name is combined with two words, the second word will
start with uppercase letter always such as actionPerformed(),
firstName, ActionEvent, ActionListener, etc.
CHAPTER 3.2:
VARIABLES
VARIABLES
• 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 type and name.
Syntax
type variable = value;
Where type is one of Java's data types (such as int or String), and variable is the name of the variable
(such as x or name). The equal sign is used to assign values to the variable.
int data=10;//Here data is variable
Types of Variables
• There are three types of variables in Java:
1) INSTANCE VARIABLE
A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific
and is not shared among instances.
2) STATIC VARIABLE
A variable which is declared as static is called static variable. It
cannot be local. You can create a single copy of static variable and
share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the
memory.
3) 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.
Types of Variables
1. INSTANCE VARIABLES - declare inside class but not inside method
class Instance {
float pi = 3.1416; //instance variable
int data = 20; //instance variable
}
PROPERTIES
1. Instance variable always 2. Cannot be reinitialized 3. We can reinitialized
get a default value. directly wilth class. instance variable inside the
method.
data
int data; class Instance { class Instance {
class Test{
static int data = 50;
can create a single copy of static variable and share among all the instances of the class
data_2
Obj1 Obj2
data data
Types of Variables
3. LOCAL VARIABLES - declared inside method or method parameters
PROPERTIES
1. Not accessible outside the method.
2. Do not get default value.
Example to understand the types of variables in java
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
CHAPTER 3.3:
DATA TYPES
DATA TYPES
Data types specify the different sizes and values that can be stored
in the variable. There are two types of data types in Java:
There are two types of data types in Java: primitive and non-primitive.
DATA TYPES IN JAVA
Floating point types - represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
Booleans - A boolean data type is declared with the boolean keyword and can only take the
values true or false:
The most used for numbers are int (for whole numbers) and double (for floating point numbers).
Integer Types
Byte - The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that the value will be
within -128 and 127:
Short - The short data type can store whole numbers from -32768 to 32767:
Int - The int data type can store whole numbers from -2,147,483,648 to 2,147,483,647. In
general, and in our tutorial, the int data type is the preferred data type when we create variables
with a numeric value.
Long - The long data type can store whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Float - The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that
you should end the value with an "f":
Double - The double data type can store fractional numbers from -1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
Booleans - A boolean data type is declared with the boolean keyword and can only take the
values true or false:
Characters - The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
The main difference between primitive and non-primitive data types are:
1. Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).
2. Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
3. A primitive type has always a value, while non-primitive types can be null.
4. A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all the
same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about
these in a later chapter.
Java Type Casting
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
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:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
ARITHMETIC OPERATORS
Arithmetic operators are used to perform common mathematical
operations.
Operator Name Description Example Try it
+ Addition Adds together two values x+y Try it »
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
JAVA Boolean
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can take the values true or false.
Java Math
Java Math Syntax Description
Math.max(x,y) can be used to find the highest value of x and y:
Math.min(x,y) can be used to find the lowest value of of x and y:
Math.sqrt(x) method returns the square root of x:
Math.abs(x) method returns the absolute (positive) value of x:
Math.random() returns a random number between 0.0 (inclusive), and
1.0 (exclusive):
int randomNum = (int) You can use this formula to get more control over the
(Math.random() * random number.
101); e.g. you only want a random number between 0 and
// 0 to 100 100.
Try this code!!!
package javamath;
public class JavaMath {
public static void main(String[] args) {
int a=-11;
int b=5;
int randNum = (int)(Math.random() * 101); // 0 to 100
System.out.println("maximum number is:" + " " + Math.max(a, b)); //maximum number
System.out.println("minimum number is:" + " " + Math.min(a, b)); //manimum number
System.out.println("the sqrt is:" + " " + Math.sqrt(a+b));
System.out.println("the absolute number is:" + " " + Math.abs(a+b));
System.out.println("This prints any value randomly:" + " " + Math.random() * 101); // 0 to 100);
}
}
CHAPTER 3.5:
JAVA STRINGS
Strings
Strings - The String data type is used to store a sequence of characters (text). String values
must be surrounded by double quotes:
The String type is so much used and integrated in Java, that some call it "the special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The String object has
methods that are used to perform certain operations on strings.
String Length
• A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with the length()
method:
• The + operator can be used between strings to combine them. This is called concatenation:
public class MyClass {
public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}
Note that we have added an empty text (" ") to create a space between firstName and lastName on print.
You can also use the concat() method to concatenate two strings:
If you add a number and a string, the result will be a string concatenation:
String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)
Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate an error:
String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
\\ \ Backslash
String txt = "We are the so-called \"Vikings\" from the north.";
String txt = "It\'s alright.";
String txt = "The character \\ is called backslash.";
CHAPTER 3.6:
USERS INPUT
AND OUTPUT
Learn simple ways to
display output and take
input from the user.
Java Output
class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}
class Output {
public static void main(String[] args) {
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
When you run the program, the output will be:
1. println
2. println
1. print 2. print
Example 3: Printing Variables and Literals
To display integers, variables and so on, do not use
quotation marks.
class Variables {
public static void main(String[] args) {
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Example 3:
When you run the program, the output will be:
5
-10.6
Example 4: Print Concatenated Strings
You can use + operator to concatenate strings and print it.
class PrintVariables {
public static void main(String[] args) {
Strings "I am " and "awesome." is concatenated first before it's printed on the
screen.
The value of variable number is evaluated first. It's value is in double which is
converted to string by the compiler. Then, the strings are concatenated and
printed on the screen.
Java Input
There are several ways to get input from the user in
Java. You will learn to get input by using Scanner
object.
import java.util.Scanner;
Learn more about Java import
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
When you run the program, the output will be:
Enter an integer: 23
You entered 23
• Here, input object of Scanner class is created. Then, the
nextInt() method of the Scanner class is used to get integer
input from the user.
• To get long, float, double and String input from the user,
you can use nextLong(), nextFloat(), nextDouble() and
next() methods respectively.
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Exam Scanner input = new Scanner(System.in);
ple 6: // Getting float input
Note: there are other several ways to get input from the user.
CHAPTER 3.7:
CONDITIONAL
STATEMENTS
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 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
}
Example 1:
if (20 > 18) {
System.out.println("20 is greater than 18");
}
Example 2: We can also test variables:
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
The if Statement
• In the previous example, we use two variables, x and y, to test
whether x is greater than y (using the > operator). As x is 20, and y
is 18, and we know that 20 is greater than 18, we print to the
screen that "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
Example:
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
EXAMPLE EXPLAINED
This will stop the execution of more code and case testing inside
the block.
When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
The break Keyword
System.out.println("Saturday");
Insert the missing break;
parts to complete the 2:
following switch System.out.println("Sunday");
statement. ;
}
int day = 4;
switch ( ){
PRACTICE 7: 1:
System.out.println("Saturday");
break;
Insert the missing 2:
parts to complete the
following switch
System.out.println("Sunday");
statement. ;
:
System.out.println("Weekend");
}
CHAPTER 3.8:
JAVA LOOPS
AND ITERATION
Loops can execute a block of code as long as a
specified condition is reached. Loops are handy
because they save time, reduce errors, and they
make code more readable.
JAVA FOR LOOP
When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
Statement 3 is executed (every time) after the code block has been
executed.
EXAMPLE:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
EXAMPLE:
This example will only print even values between 0 to 10.
while (condition) {
// code block to be executed
}
Java While Loop
The In the example below, the code in the loop will run, over and
over again, as long as a variable (i) is less than 5:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will
always be executed at least once, even if the condition is
false, because the code block is executed before the
condition is tested:
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
PRACTICE 8:
String[] cars;
JAVA ARRAYS
• We have now declared a variable that holds an array of strings. To
insert values to it, we can use an array literal - place the values in a
comma-separated list, inside curly braces:
cars[0] = "Opel";
If you compare the for loop and for-each loop, you will see
that the for-each method is easier to write, it does not require
a counter (using the length property), and it is more readable.
Multidimensional Arrays
• A multidimensional array is an array containing one or more
arrays.
Example
THANK YOU!