Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Java Basics

To create a new Java Class:


src → New → Java Class

Printing Hello World


Shortcut for print -> sout = System.out.println()

public class Hello {

public static void main(String[] args){


System.out.println("Hello World");
}
}

Data types

󾠮Whole Number Data Types: [4 types]


Declaring a number variable
data type + variable name + (optional) value

Java Basics 1
int myFirstNumber = 5; // -> expression

Getting the minimum and maximum value of a Data Type

Int

int myMinIntValue = Integer.MIN_VALUE;


int myMaxIntValue = Integer.MAX_VALUE;

System.out.println("Integer Minimum Value = " + myMinIntValue);


System.out.println("Integer Maximum Value = " + myMaxIntValue);

Size of Primitive Types and Width


Primitive Types

Data Type Bits Width


Byte 8 8

Short 16 16
Int 32 32

Minimum and Maximum values


Min & Max value of Data Types

Data Type Min Max


Int -2147483648 2147483647

Byte -128 127


Short -32768 32767
Long -9223372036854776000 9223372036854776000

Casting in Java
data type → variable name = (data type/ CAST) value

Java Basics 2
The value of [myTotal] = 2 which is of the type int

int myTotal = 20 / 10

But the value of [myNewByteValue] will return an error since it's


value is of the type int instead of byte

byte myMaxByteValue = Byte.MAX_VALUE;


byte myNewByteValue = (myMinByteValue / 2);

To solve this issue we must specify the type of the value as well
using Casting

byte myNewByteValue = (byte) (myMinByteValue / 2);

So the retuned type of the value must be of the same type as the
variable

󾠯 Decimal-Point Number Data Types [4


Types]
Decimal Point numbers are used when we need extra precision.

There are 2 Primitive Types in Java → Float


(single precision number) and Double (
double precision number)

Java Basics 3
Float & Double

Data Type Bits Width


Float 32 32

Double 64 64

Declaring float & double variables


float myFloatValue = 5.25f; // f - float
double myDoubleValue = 5.25d; // d - double

Division using int , float & double (most used)


int myIntValue = 5 / 3; // 1
float myFloatValue = 5f / 3f; // 1.6666666
double myDoubleValue = 5d / 3d; // 1.6666666666666667

The int will return 1 because int only return a whole number

The float will return a decimal point number

The double will return a more precise decimal point number

Primitive data types: char & bool

Char can store only one character


Also stores unicode charactrers ( takes 2 bits ) [https://unicode-table.com/en/]

// Regular Characters
char myChar = 'D';
char myChar = 'DD'; // will retun an error since DD is more than one character

// Unicode Characters // output D


char myUnicodeChar = '\u0044';

Java Basics 4
Strings
Strings are immutable

Strings are a Class in Java

Java do not convert a string to a number [ "10" =! 10] and


it will concatenate the result

String + int = stringint


string + double = stringdouble
and so on...

String laststring = "10";


int myInt = 50;
laststring = laststring + myInt; // 1050

double doubleNumber = 120.47d;


laststring = laststring + doubleNumber; 1050120.47

The if statements in Java


Example: no curly brackets

if(isAlien == false)
System.out.println("It is not alien!");

Example: with curly brackets

Java Basics 5
int newValue = 50;
if(newValue == 50) {
System.out.println("This is an error");
}

Ternary Operator
boolean wasCar = isCar ? true : false;
If isCar = true then wasCar = true, else wasCar = false

boolean isCar = true


boolean wasCar = isCar ? true : false;
if(wasCar) {
System.out.println("wasCar is true");
}

Methods inside methods


Let's create a score calculator:
We have 4 variables ( 1 boolean & 3 int )

Each variable has a defined value

boolean gameOver = true;


int score = 800;
int levelCompleted = 5;
int bonus = 100;

Then we have an if statement that will calculate our finalScore

The code block inside the if statement gets executed only if the parameter
gameOver is true

If gameOver is true , the finalScore will be calculated and printed

Printed value is: Your final score was 2300

Java Basics 6
public class Main {

public static void main(String[] args) {


boolean gameOver = true;
int score = 800;
int levelCompleted = 5;
int bonus = 100;

if(gameOver){
int finalScore = score + (levelCompleted * bonus);
finalScore += 1000;
System.out.println("Your final score was " + finalScore);
}
}
}

Now if we want to add a second score, levelCompleted and bonus and print out
the finalScore we can use the existing variables, assign them new values
and then duplicate the if statement.
Remember that when we will assign new values to already defined variables we
will not specify their data types again ( no boolean & int ) since we do not want
to declare the variables again, but to assign new values to them.
Whitch is called code duplication and it IS NOT a good practice.

Imagine if we want to add 50 new game results. We will end with 1000 lines of
duplicated code. That's a nono.

We will use the example below as an NOT LIKE THIS example

public class Main {

public static void main(String[] args) {


boolean gameOver = true;
int score = 800;
int levelCompleted = 5;
int bonus = 100;

if(gameOver){
int finalScore = score + (levelCompleted * bonus);
finalScore += 1000;
System.out.println("Your final score was " + finalScore);
}

score = 10000;
levelCompleted = 8;
bonus = 200;

if(gameOver){
int finalScore = score + (levelCompleted * bonus);
System.out.println("Your final score was " + finalScore);

Java Basics 7
}
}
}

Duplicate code is bad, so let's see how we can create an method that
we can reuse in order to add as many new values we want without
duplicating existing code.

Step #1
We will work inside the public class Main {}

public class Main {


// our code will go here
}

Step #2
We will define the values inside the main method by calling a new method inside
here that will perform the calculation

public static void main(String[] args) {


// the calculation result will be printed from here
}

Step #3
Now we will create a new method that will calculate our finalPrice

public static void calculateScore(// we will need to pass some parameters here) {
}

Step #4

Java Basics 8
Now let's pass some parameters inside the () so we can use those parameters to
create the if statement and calculate the finalPrice

This way we can always change the way the finalScore is calculated (adding
1000 extra points, etc) and we can do it in only one place. We will not need to
make the change inside all the places where the code was duplicated.

public static void calculateScore(boolean gameOver, int score, int levelCompleted, int bonus) {
}

Step #5
Now that we have the needed parameters let's use them inside the if statement
and calculate the finalPrice

public static void calculateScore(boolean gameOver, int score, int levelCompleted, int bonus) {
if (gameOver) {
int finalScore = score + (levelCompleted * bonus);
finalScore += 2000;
System.out.println("Your final score was " + finalScore);
}
}

Now we can call the calculateScore() method inside our


main() method, and we can do this in 2 ways

Final step - 1st way


Inside the main() method we can call the calculateScore() method and directly
pass in the values we need

public static void main(String[] args) {


calculateScore(true, 800, 5, 100); // 1st score
calculateScore(true, 10000, 8, 200); // 2nd score
}

Final step - 2nd way

Java Basics 9
For the second way we will define the variables and then use the variable names
as arguments

public static void main(String[] args) {


// 1st player's score
boolean gameOver = true;
int score = 800;
int levelCompleted = 5;
int bonus = 100;

calculateScore(gameOver, score, levelCompleted, bonus);

// 2nd player's score


score = 10000;
levelCompleted = 8;
bonus = 200;

calculateScore(gameOver, score, levelCompleted, bonus);

Useful shortcut psvm =


public static void main(String[] args) {

Method Overloading
Guide to Overloading Methods in Java
Java defines a method as a unit of the tasks that a class can perform.
And proper programming practice encourages us to ensure a method
does one thing and one thing only. It is also normal to have one
https://stackabuse.com/guide-to-overloading-methods-in-java

In Java we can have multiple methods with the same


name.

Java Basics 10
But in order to do that every method needs to have it's
unique signature.

#1 The original method - 2 parameters [String, int]

public static int calculateScore(String playerName, int score){


System.out.println("Player " + playerName + " scored " + score + " points");
return score * 1000;
}

#2 A new method with the same name - 2 parameters[int,


int]

public static int calculateScore(int age, int score){


System.out.println("Player is " + age + " years old and he scored "
+ score + " points");
return score * 1000;
}

#3 A new method with the same name - 1 parameter [int]

public static int calculateScore(int score){


System.out.println("Unnamed player scored " + score + " points");
return score * 1000;
}

#4 A new method with the same name - 0 parameters

public static int calculateScore(){


System.out.println("No player name, no player score.");
return 0;
}

Java Basics 11
As we can see above, all methods have the same name,
but they have have a different number and type of
parameters.

Control Slow Statements


Switch , For, While & do-while

Switch - same as always


We can also combine multiple cases that will return/print the same
thing [case 3: case 4: case 5:]

int switchValue = 3;

switch (switchValue) {
case 1:
System.out.println("Value was 1");
break;

case 2:
System.out.println("Value was 2");
break;

case 3: case 4: case 5:


System.out.println("Was a 3 or 4 or 5");
System.out.println("Actually was " + switchValue);
break;

default:
System.out.println("Was not 1 or 2");
break;
}

While

Java Basics 12
Here we will create a loop that outputs all the even numbers in a
range

int number → represents the starting point


int finishNumber → represents the end point
So while the number is ≤ finishNumber increase the number by 1 (number++)
If during its increase, the number becomes an odd number(ex 5,7,9, etc.) we use
[continue] to skip the odd number and continue increasing it.
The way [continue] works is like this:

The number is increased and printed while number ≤ finishNumber is true

If the number is not even(ex. 5) , continue will skip the printing and go back to
(number <= finishNumber)

If (number <= finishNumber) is evaluated as true, it's gonna increase the number(ex
ro 6) and check if it's even, if it is, then it' gonna print it and do the same thing untill
(number <= finishNumber) will be evaluated as false

The while loop example

int number = 4;
int finishNumber = 20;

while (number <= finishNumber){


number++;
if(!isEvenNumber(number)){
continue;
}
System.out.println("Even number " + number);
}

Method checking if number is even or odd

public static boolean isEvenNumber(int number) {


return number % 2 == 0;
}

Java Basics 13
Java Basics 14

You might also like