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

Comp Prog and Funda Using Java 2

Computer Programming and Fundamentals (Java 2).

Uploaded by

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

Comp Prog and Funda Using Java 2

Computer Programming and Fundamentals (Java 2).

Uploaded by

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

Java tutorial

By Sir J
Java Data type
A variable in Java must be a specified data type:

Data type describes the variable

Example:

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99f; // Floating point number

double weight = 2.2;

char myLetter = 'a'; // Character

boolean myBool = true; // Boolean


Data types are divided into two groups:
● Primitive data types - includes byte , short , int, long , float , double , boolean and char
● Non-primitive data types - such as String , Arrays and Classes (you will learn more about these in a later chapter)

0 1 bit

8 bit = 1 byte

0000 0000 0000 0000

0000 0000 0110 0001

0000 0000 0110 0010

1 char = 2 bytes
Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java:


Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types
are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two
types: float and double.
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:

Example
byte myNum = 100;

System.out.println(myNum);
Short

The short data type can store whole numbers from -32768 to 32767:

Example
short myNum = 5000;

System.out.println(myNum);
Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.

Example
int myNum = 100000;

System.out.println(myNum);
Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is
used when int is not large enough to store the value. Note that you should end the value with an "L":

Example
long myNum = 15000000000L;

System.out.println(myNum);
Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.

The float and double data types can store fractional numbers. Note that you should end the value with an "f"
for floats and "d" for doubles:

Float Example
float myNum = 5.75f;

System.out.println(myNum);
Double Example

double myNum = 19.99d;

System.out.println(myNum);
Use float or double?

The precision of a floating point value indicates how many digits the value can have after the decimal point. The
precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.
Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example
float f1 = 35e3f;

double d1 = 12E4d;

System.out.println(f1);

System.out.println(d1);
Java Boolean Data Types
Boolean Types
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 only take the values true or false:
Boolean data type
Example
boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false


Java Characters
Characters
The char data type is used to store a single character. The character must be surrounded by single quotes, like
'A' or 'c':

Example:

char myGrade = 'B';

System.out.println(myGrade);
Java Non-Primitive Data Types
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

● 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).
● Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
● A primitive type has always a value, while non-primitive types can be null.
● A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.

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

● 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:

public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // 9.0

}
Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the value:

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

}
Java Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Note: Although the + operator is often used to add together two values, like in the example above, it can also be used to add
together a variable and a value, or a variable and another variable:
Java Operator
Example
int sum1 = 100 + 50; // 150 (100 + 50)

int sum2 = sum1 + 250; // 400 (150 + 250)

int sum3 = sum2 + sum2; // 800 (400 + 400)


Java divides the operators into the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Bitwise operators
Arithmetic Operator
Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;

x += 5;
A list of all assignment operators:
Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because
it helps us to find answers and make decisions.

The return value of a comparison is either true or false. These values are known as Boolean values, and you
will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;

int y = 3;

System.out.println(x > y); // returns true, because 5 is higher than 3


Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:
Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

Example

String greeting = "Hello";


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:

Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println("The length of the txt string is: " + txt.length());


More String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

Example

String txt = "Hello World";

System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD”

System.out.println(txt.toLowerCase()); // Outputs "hello world"


Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string
(including whitespace):

Example

String txt = "Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate")); // Outputs 7

Note: Java counts positions from zero.

0 is the first position in a string, 1 is the second, 2 is the third ...


Java String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:

Example
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:

Example

String firstName = "John ";

String lastName = "Doe";

System.out.println(firstName.concat(lastName));
Adding Numbers and Strings

WARNING!

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.


If you add two numbers, the result will be a number:

Example

String x = “24”;

String y = “203”;

String z = x + y;
If you add two strings, the result will be a string concatenation:

Example

String x = "10";

String y = "20";

String z = x + y; // z will be 1020 (a String)


If you add a number and a string, the result will be a string concatenation:

Example
String x = "10";

int y = 20;

String z = x + y;
Java Conditions and If Statements

You already know that 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

}
Best practice
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

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");

}
We can also test variables:

Example
int x = 11;

int y = 12;

if (x > y) {

System.out.println("x is greater than y");

}
Example explained

In the example above 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

}
If and else statement
Example
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

}
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

}
Example of If, else if and else statements
Example
int time = 22;

if (time != 10) {

System.out.println("Good morning.");

} else if (time <= 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

}
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."
Java Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else
statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;
If else statement
Instead of writing:
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

}
If else statement using shorthand
You can simply write:
int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result);
Java While Loop
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 While Loop
The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {

// code block to be executed

}
Structure
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:

Example
int i = 0;

while (i < 5) {

System.out.println(i);

i++;

}
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:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

}
For loop statements
Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Initial value; condition; increment or decrement


The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

System.out.println(i);

Example explained
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.
Another Example

This example will only print even values between 0 and 10:

Example

for (int i = 0; i <= 10; i = i + 2) {

System.out.println(i);

}
Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
for (int i = 1; i <= 2; i++) { // Outer loop

System.out.println("Outer: " + i); // Executes 2 times

for (int j = 1; j <= 3; j++) { // Inner loop

System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)

}
Java For Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

Syntax
for (type variableName : arrayName) {

// code block to be executed

}
The following example outputs all elements in the cars array, using a "for-each"
loop:

Example
String[] car = {"Volvo", "BMW", "Ford", "Mazda"};

for (String car : cars) {

System.out.println(car);

}
こんばんは ! ありがとう ございます!

You might also like