What is Java?
•Java is a popular programming language, created in 1995.
• It is owned by Oracle, and more than 3 billion devices run Java.
• It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
2.
Why Use Java?
•Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming languages in the world
• It has a large demand in the current job market
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
• As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa
3.
Java Syntax :-To print hello world
• public class Main {
• public static void main(String[] args) {
• System.out.println("Hello World");
• }
• }
• We use System.out.printrln(“”) in java to print message or output
• Every line of code that runs in Java must be inside a class. And the class name should
always start with an uppercase first letter. In our example, we named the class Main.
• Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning
Java Comments
• Single-linecomments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by Java (will not be
executed).
public class Main {
public static void main(String[] args) {
// This is a comment
System.out.println("Hello World");
}
}
6.
Java Variables
• Variablesare containers for storing data values.
• In Java, there are different types of variables, for example:
• String - stores text, such as "Hello". String values are surrounded by double quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• boolean - stores values with two states: true or false
Java Data Types
•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
9.
Primitive Data Types
•A primitive data type specifies the type of a variable and the kind of
values it can hold.
• There are eight primitive data types in Java:
10.
Example
• public classMain {
• public static void main(String[] args) {
• // Create variables of different data types
• int items = 50;
• float costPerItem = 9.99f;
• float totalCost = items * costPerItem;
• char currency = '$';
• // Print variables
• System.out.println("Number of items: " + items);
• System.out.println("Cost per item: " + costPerItem + currency);
• System.out.println("Total cost = " + totalCost + currency);
• }
• }
11.
Non-Primitive Data Types
•Non-primitive data types are called reference types because they refer to objects.
• The main differences between primitive and non-primitive data types are:
• Primitive types in Java are predefined and built into the language, while non-primitive
types are created by the programmer (except for String).
• Non-primitive types can be used to call methods to perform certain operations,
whereas primitive types cannot.
• Primitive types start with a lowercase letter (like int), while non-primitive types
typically starts with an uppercase letter (like String).
• Primitive types always hold a value, whereas non-primitive types can be null
12.
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
13.
Example Widening Casting
•public class Main {
• public static void main(String[] args) {
• int myInt = 9;
• double myDouble = myInt; // Automatic casting: int to double
• System.out.println(myInt);
• System.out.println(myDouble);
• }
• }
14.
Example of narrowcasting
• public class Main {
• public static void main(String[] args) {
• // Set the maximum possible score in the game to 500
• int maxScore = 500;
• // The actual score of the user
• int userScore = 423;
• /* Calculate the percantage of the user's score in relation to the maximum available score.
• Convert userScore to float to make sure that the division is accurate */
• float percentage = (float) userScore / maxScore * 100.0f;
• // Print the result
• System.out.println("User's percentage is " + percentage);
• }
• }
15.
Java Operators
• Operatorsare used to perform operations on variables and values.
• In the example below, we use the + operator to add together two
values
• int x = 100 + 50;
• 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:
16.
Java divides theoperators into the following
groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
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:public class Main {
• public static void main(String[] args) {
• int x = 10;
• x += 5;
• System.out.println(x);
• }
• }
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:
• public class Main {
• public static void main(String[] args) {
• 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:
23.
Example of logicalOperator
• public class Main {
• public static void main(String[] args) {
• int x = 5;
• System.out.println(x > 3 && x < 10); // returns true because 5 is
greater than 3 AND 5 is less than 10
• }
• }
24.
Java Strings
• Stringsare used for storing text.
• A String variable contains a collection of characters surrounded by double
quotes:
• public class Main {
• public static void main(String[] args) {
• String greeting = "Hello";
• System.out.println(greeting);
• }
• }
25.
String Length
• AString 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:
• public class Main {
• public static void main(String[] args) {
• String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• System.out.println("The length of the txt string is: " + txt.length());
• }
• }
26.
More String Methods
•There are many string methods available, for example toUpperCase()
and toLowerCase():
• public class Main {
• public static void main(String[] args) {
• String txt = "Hello World";
• System.out.println(txt.toUpperCase());
• System.out.println(txt.toLowerCase());
• }
• }
27.
Finding a Characterin a String
• The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):
• public class Main {
• public static void main(String[] args) {
• String txt = "Please locate where 'locate' occurs!";
• System.out.println(txt.indexOf("locate"));
• }
• }
28.
Java String Concatenation
•The + operator can be used between strings to combine them. This is
called concatenation:
• public class Main {
• public static void main(String args[]) {
• String firstName = "John";
• String lastName = "Doe";
• System.out.println(firstName + " " + lastName);
• }
• }
29.
You can alsouse the concat() method to
concatenate two strings:
• public class Main {
• public static void main(String[] args) {
• String firstName = "John ";
• String lastName = "Doe";
• System.out.println(firstName.concat(lastName));
• }
• }
30.
Adding Numbers andStrings
• If you add two strings, the result will be a string concatenation:
• public class Main {
• public static void main(String[] args) {
• String x = "10";
• String y = "20";
• String z = x + y;
• System.out.println(z);
• }
• }
31.
Java Packages &API
• A package in Java is used to group related classes. Think of it as a
folder in a file directory. We use packages to avoid name conflicts, and
to write a better maintainable code. Packages are divided into two
categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)