[go: up one dir, main page]

0% found this document useful (0 votes)
44 views115 pages

Java Lecture Slides

The document provides a comprehensive overview of the Java programming language, covering its definition, features, and the importance of programming languages. It includes details on Integrated Development Environments (IDEs), how to execute Java code, and fundamental concepts such as variables, data types, control statements, and exception handling. Additionally, it presents examples of Java code and explains the structure of a Java program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views115 pages

Java Lecture Slides

The document provides a comprehensive overview of the Java programming language, covering its definition, features, and the importance of programming languages. It includes details on Integrated Development Environments (IDEs), how to execute Java code, and fundamental concepts such as variables, data types, control statements, and exception handling. Additionally, it presents examples of Java code and explains the structure of a Java program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

Java Language

M.Samly - Bcas Kandy Campus 1


Content
• Programming Language
• Why Programming languages?
• What is Java?
• IDE
• IDE Tools
• How to execute the java code?
• Understanding java code structure
• Variables & Data Types
• Valid and Invalid variable
• NetBeans IDE Tool
• First java code (hello world)

M.Samly - Bcas Kandy Campus 2


Content
• How to execute the code?
• Output
• Comment
• Variable Declaration
• Printing Variables as Output
• Operations
• Control Statements
• Looping Statements
• Jump Statement
• Array
• Exception Handling

M.Samly - Bcas Kandy Campus 3


Content
• String Manipulation
• Scanner Class
• Access Modifiers
• How to Write a Method?
• How to create a Class?
• Object Oriented Programming

M.Samly - Bcas Kandy Campus 4


Programming language
• A programming language is a formal language that consists of a
set of instructions used to produce a desired output or behavior in
a computer.
• It is used to communicate with a computer to perform specific
tasks.

M.Samly - Bcas Kandy Campus 5


Why Programming Languages?
Computers understand machine language (binary: 0s and 1s), but
humans need a way to communicate with them in a more
understandable way. Programming languages are the bridge
between human instructions and machine actions.

M.Samly - Bcas Kandy Campus 6


What is Java?
• Java is a high-level, object-oriented programming language
• It is used to create a wide variety of applications: web, mobile
(Android), desktop, enterprise
• Java programs are platform-independent because they run on the
Java Virtual Machine (JVM).
• Key Feature of Java
• Object-Oriented Programming (OOP).
• Platform Independence.
• Robust and Secure.
• Large developer community and plenty of libraries.
M.Samly - Bcas Kandy Campus 7
IDE
• IDE stands for Integrated Development Environment.
• It is a software application that provides comprehensive tools to
developers for writing, testing, and debugging their code.
• Code Editor: For writing code.
• Compiler/Interpreter: To convert your code into machine-readable
language.
• Debugger: For finding and fixing errors in your code.
• Build Automation Tools: For managing code compilation, dependencies,
and execution.
• Version Control Integration: To work with version control systems like
Git.
M.Samly - Bcas Kandy Campus 8
IDE tools
• Eclipse: Widely used, supports Java, and has a wide range of
plugins.
• IntelliJ IDEA: Known for advanced features, great for larger
projects, highly popular among Java developers.
• NetBeans: Another popular IDE for Java with great support for
JavaFX and other technologies.
• Visual Studio Code: A lightweight, customizable IDE with Java
support through extensions.

M.Samly - Bcas Kandy Campus 9


M.Samly - Bcas Kandy Campus 10
How to execute the java code?
1. Download and Install JDK (Java Development Kit):
• Go to the official Oracle JDK download page and download the latest JDK
version for your operating system. (Windows, Mac, Linux, etc.)
(https://www.oracle.com/java/technologies/javase-jdk11-
downloads.html)

M.Samly - Bcas Kandy Campus 11


Continue…
2. Set Up the JDK Path (Environment Variables):

Step 01 Step 02
M.Samly - Bcas Kandy Campus 12
Continue…
• Find your java file on
File Explorer → C drive → Program Files → Java → jdk folder

Step 03 Step 04
M.Samly - Bcas Kandy Campus 13
Continue…

Step 07

Step 05 Step 06

M.Samly - Bcas Kandy Campus 14


Continue…

Step 08 Step 09 Step 10

M.Samly - Bcas Kandy Campus 15


Continue…

Step 11 Step 12 Step 13

M.Samly - Bcas Kandy Campus 16


Continue…

Step 14

M.Samly - Bcas Kandy Campus 17


Understanding Java Code Structure
• Basic Structure of a Java Program:
• Every Java program must contain a class and a main method.

• Explanation of the Components:


• Class: A blueprint that defines the properties and behaviors of an object.
• Main Method: Every Java application starts execution from the main
method.

M.Samly - Bcas Kandy Campus 18


Example of Java
public class Student{
public static void main(String args[]){
//codes
}
}

M.Samly - Bcas Kandy Campus 19


Continue…
• public: The access modifier; allows access from anywhere.
• static: Belongs to the class rather than an instance.
• void: The method does not return any value.
• String[] args: Command-line arguments, not used in this basic
example.

M.Samly - Bcas Kandy Campus 20


Example of Java class & Main Method
public class Student{ Class Name

public static void main(String args[]){


Main Method
//codes
}
}

M.Samly - Bcas Kandy Campus 21


Variables & Data Types
• Variable
• A variable is a container used to store data values.
• It has a specific type (int, double, String, etc.), a name, and holds a value.

• Data Types
• int: for integers (whole numbers).
• double: for floating-point numbers (decimal values).
• char: for a single character.
• boolean: for true/false values.
• String: for text data.

M.Samly - Bcas Kandy Campus 22


Example
• int age;
• double price;
• char grade;
• boolean isJavaFun;
• String name;

M.Samly - Bcas Kandy Campus 23


Valid and Invalid variable
• Variable names must start with a letter, underscore (_), or dollar sign
($).
• Cannot use reserved keywords (e.g., class, int, float, string, final, etc…).
• Follow conventions (camelCase for variables).
Correct Variable Names: Incorrect Variable Names:
• int myAge; • int 1myAge;
• double totalPrice; • double total-Price;
• String userName; • String class;
• boolean isValid; • boolean int;
• char $grade; • float total price;
• float _temperature; • char #grade;

M.Samly - Bcas Kandy Campus 24


NetBeans IDE Tool
• NetBeans is an open-source Integrated Development
Environment (IDE) used for Java development.
• Visit the official NetBeans download page:
NetBeans Download.
(https://netbeans.apache.org/front/main/download/index.html)

M.Samly - Bcas Kandy Campus 25


Create a Project using NetBeans

M.Samly - Bcas Kandy Campus 26


Continue…

M.Samly - Bcas Kandy Campus 27


Continue…

M.Samly - Bcas Kandy Campus 28


First java code (hello world)
public class first{
public static void main(String[] args){
System.out.println(“Hello World”);
}
}

M.Samly - Bcas Kandy Campus 29


How to execute the code?

Run Button

Run File or Shift + f6

M.Samly - Bcas Kandy Campus 30


Output

Output

M.Samly - Bcas Kandy Campus 31


Comment
• Java comments are used to annotate and explain code. They help
developers understand the purpose of code segments and
improve readability.
• Types of Comments:
• Single-line Comments (//)
• Multi-line Comments (/* ... */)

M.Samly - Bcas Kandy Campus 32


Example
• Single-line Comments (//) used for short explanations or notes
within a line.
// This is a single-line comment
int x = 5;
• Multi-line Comments (/* ... */) used for longer descriptions or
comments spanning multiple lines.
/*
* This is a multi-line comment
* that spans multiple lines.
*/
int y = 10;

M.Samly - Bcas Kandy Campus 33


Variable Declaration
• Variable declaration refers to the process of defining a variable with a specific data
type and assigning it a name, so the program can store and manipulate data.

<data_type> <variable_name> = <value>;

Example:
• int age = 25; // Declare an integer variable 'age' with a value of 25
• double price = 19.99; // Declare a double variable 'price' with a value of 19.99
• char grade = 'A'; // Declare a char variable 'grade' with a value of 'A'
• boolean isJavaFun = true; // Declare a boolean variable 'isJavaFun' with a value of true
• String name = "John"; // Declare a String variable 'name' with a value of "John"

M.Samly - Bcas Kandy Campus 34


Printing Variables as Output
To print variables in Java, you can use the System.out.println() or
System.out.print() methods.
• System.out.println(): Prints the variable value followed by a
newline (moves to the next line after printing).
• System.out.println(variable_name);

• System.out.print(): Prints the variable value without moving to the


next line (continues printing on the same line).
• System.out.print(variable_name);

M.Samly - Bcas Kandy Campus 35


System.out.println Example

M.Samly - Bcas Kandy Campus 36


System.out.print Example

M.Samly - Bcas Kandy Campus 37


Printing Variables with Declaration
System.out.println("Some text " + variableName);

M.Samly - Bcas Kandy Campus 38


Operations
Arithmetic Operators: Comparison Operators:
• Addition (+) • Equal to (==)
• Not equal to (!=)
• Subtraction (-)
• Greater than (>)
• Multiplication (*) • Less than (<)
• Division (/) • Greater than or equal to (>=)
• Modulus (%) • Less than or equal to (<=)
Unary Operators: Logical Operators:
• Increment (++) • Logical AND (&&)
• Decrement (--) • Logical OR (||)

M.Samly - Bcas Kandy Campus 39


Example of Operations

M.Samly - Bcas Kandy Campus 40


Continue…

M.Samly - Bcas Kandy Campus 41


Continue…

M.Samly - Bcas Kandy Campus 42


Control Statements
• Decision-Making (Conditional) Statements
• If Statement
• If-else Statement
• Else-if Statement
• Switch Statement

M.Samly - Bcas Kandy Campus 43


IF Statement

M.Samly - Bcas Kandy Campus 44


Example

M.Samly - Bcas Kandy Campus 45


IF-ELSE Statement

M.Samly - Bcas Kandy Campus 46


Example

M.Samly - Bcas Kandy Campus 47


ELSE-IF Statement

M.Samly - Bcas Kandy Campus 48


Example

M.Samly - Bcas Kandy Campus 49


SWTCH Statement

M.Samly - Bcas Kandy Campus 50


Example

M.Samly - Bcas Kandy Campus 51


Looping Statements
• for Loop
• while Loop
• do-while Loop

M.Samly - Bcas Kandy Campus 52


FOR Loop
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}

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


System.out.println(i);
}

M.Samly - Bcas Kandy Campus 53


Example

M.Samly - Bcas Kandy Campus 54


Example

M.Samly - Bcas Kandy Campus 55


WHILE Loop
while (condition) {
// Code to execute while condition is true
}

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

M.Samly - Bcas Kandy Campus 56


Example

M.Samly - Bcas Kandy Campus 57


Example

M.Samly - Bcas Kandy Campus 58


DO WHILE Loop
do {
// Code to execute
} while (condition);

int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

M.Samly - Bcas Kandy Campus 59


Example

M.Samly - Bcas Kandy Campus 60


Example

M.Samly - Bcas Kandy Campus 61


Jump Statement
• Break Statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // Exits the loop when i equals 3
}
System.out.println(i);
}

M.Samly - Bcas Kandy Campus 62


Jump Statement
• Continue Statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // Skips this iteration when i equals 3
}
System.out.println(i);
}

M.Samly - Bcas Kandy Campus 63


Array
• What is an Array?
• An array is a data structure that can store multiple values of the same
type in a single variable.

• Stores elements of the same type.


• Fixed size (size is defined when the array is created).
• Indexed from 0 to n-1 (where n is the number of elements)

M.Samly - Bcas Kandy Campus 64


Declaring and Initializing Arrays
• dataType[] arrayName;
• Example:
• int[] numbers = {1, 2, 3, 4, 5};
• String[] fruits = {"Apple", "Banana", "Cherry"};

0 1 2
Apple Banana Cherry

Fruits[0] = “Apple”
Fruits[2] = “Cherry”
Fruits[1] = “Banana”
M.Samly - Bcas Kandy Campus 65
Array Length
String[] fruits = {"Apple", "Banana", "Cherry"};
int size = fruits.length;
System.out.println(size);

M.Samly - Bcas Kandy Campus 66


Exception Handling
• Exception handling is a mechanism to handle runtime errors,
allowing the program to continue its execution without crashing.
1. Checked Exceptions: Exceptions that must be declared or handled
explicitly (e.g., IOException).
2. Unchecked Exceptions: Runtime exceptions (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException).
3. Errors: Serious problems that a program cannot handle (e.g.,
OutOfMemoryError).

M.Samly - Bcas Kandy Campus 67


Structure of Exception Handling
• Java provides a set of keywords to handle exceptions:
• try: Defines a block of code to test for exceptions.
• catch: Defines a block of code to handle exceptions.
• finally: Defines a block of code to execute after try and catch, regardless
of whether an exception occurs.
• throw: Used to explicitly throw an exception.
• throws: Declares exceptions that a method might throw.

M.Samly - Bcas Kandy Campus 68


Try, Catch, and Finally Block
• try block: Contains the code that might throw an exception.
• catch block: Catches the exception thrown in the try block and
handles it.
• finally block: Always executes, regardless of whether an exception
occurred or not. It's typically used for cleanup (e.g., closing files,
database connections).
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}

M.Samly - Bcas Kandy Campus 69


Example

M.Samly - Bcas Kandy Campus 70


String Manipulation
• Basic String Methods
• String Case Conversion
• String Comparison
• Whitespace Manipulation
• Replacing Substrings
• String Splitting
• String Conversion

M.Samly - Bcas Kandy Campus 71


Basic String Methods
• length(): Returns the length of the string.
• charAt(int index): Returns the character at a specified index.
• substring(int start): Returns a substring starting from the specified index.
• substring(int start, int end): Returns a substring between the specified start and
end indices.
• contains(CharSequence sequence): Checks if the string contains the specified
sequence of characters.
• indexOf(String str): Returns the index of the first occurrence of the specified
substring.
• lastIndexOf(String str): Returns the index of the last occurrence of the specified
substring.
• startsWith(String prefix): Checks if the string starts with the specified prefix.
• endsWith(String suffix): Checks if the string ends with the specified suffix.

M.Samly - Bcas Kandy Campus 72


Example
• length(): Returns the length of the string.
• String str = "Hello, World!";
• System.out.println(str.length()); // Output: 13

• charAt(int index): Returns the character at a specified index.


• String str = "Hello, World!";
• System.out.println(str.charAt(0)); // Output: H
• System.out.println(str.charAt(7)); // Output: W

• substring(int start): Returns a substring starting from the specified index.


• String str = "Hello, World!";
• System.out.println(str.substring(7)); // Output: World!

M.Samly - Bcas Kandy Campus 73


Example
• substring(int start, int end): Returns a substring between the specified start and end indices.
• String str = "Hello, World!";
• System.out.println(str.substring(0, 5)); // Output: Hello
• System.out.println(str.substring(7, 12)); // Output: World

• contains(CharSequence sequence): Checks if the string contains the specified sequence of


characters.
• String str = "Hello, World!";
• System.out.println(str.contains("World")); // Output: true
• System.out.println(str.contains("Java")); // Output: false

• indexOf(String str): Returns the index of the first occurrence of the specified substring.
• String str = "Hello, World!";
• System.out.println(str.indexOf("World")); // Output: 7
• System.out.println(str.indexOf("Java")); // Output: -1 (not found)

M.Samly - Bcas Kandy Campus 74


Example
• lastIndexOf(String str): Returns the index of the last occurrence of the
specified substring.
• String str = "Hello, World! Welcome to the World!";
• System.out.println(str.lastIndexOf("World")); // Output: 26 (last occurrence)

• startsWith(String prefix): Checks if the string starts with the specified prefix.
• String str = "Hello, World!";
• System.out.println(str.startsWith("Hello")); // Output: true
• System.out.println(str.startsWith("World")); // Output: false

• endsWith(String suffix): Checks if the string ends with the specified suffix.
• String str = "Hello, World!";
• System.out.println(str.endsWith("!")); // Output: true
• System.out.println(str.endsWith("World")); // Output: false

M.Samly - Bcas Kandy Campus 75


String Case Conversion
• toUpperCase(): Converts the string to uppercase.
• toLowerCase(): Converts the string to lowercase.

M.Samly - Bcas Kandy Campus 76


Example
• toUpperCase(): Converts the string to uppercase.
• String str = "Hello, World!";
• System.out.println(str.toUpperCase()); // Output: HELLO, WORLD!

• toLowerCase(): Converts the string to lowercase.


• String str = "Hello, World!";
• System.out.println(str.toLowerCase()); // Output: hello, world!

M.Samly - Bcas Kandy Campus 77


String Comparison
• equals(Object obj): Compares the string to the specified object for
equality.
• equalsIgnoreCase(String anotherString): Compares the string to
the specified string, ignoring case differences.
• compareTo(String anotherString): Compares two strings
lexicographically.
• compareToIgnoreCase(String anotherString): Compares two
strings lexicographically, ignoring case differences.

M.Samly - Bcas Kandy Campus 78


Example
• equals(Object obj): Compares the string to the specified object for equality.
• String str1 = "Hello";
• String str2 = "Hello";
• String str3 = "World";

• System.out.println(str1.equals(str2)); // Output: true (both are the same string)


• System.out.println(str1.equals(str3)); // Output: false (different strings)
• System.out.println(str1.equals(null)); // Output: false (comparison with null)

• equalsIgnoreCase(String anotherString): Compares the string to the specified string, ignoring case
differences.
• String str1 = "Hello";
• String str2 = "HELLO";
• String str3 = "World";

• System.out.println(str1.equalsIgnoreCase(str2)); // Output: true (ignores case)


• System.out.println(str1.equalsIgnoreCase(str3)); // Output: false (different strings)
• System.out.println(str1.equalsIgnoreCase(null)); // Output: false (comparison with null)

M.Samly - Bcas Kandy Campus 79


Example
• compareTo(String anotherString): Compares two strings lexicographically.
• String str1 = "apple";
• String str2 = "banana";
• String str3 = "apple";

• System.out.println(str1.compareTo(str2)); // Output: negative value (apple < banana)


• System.out.println(str2.compareTo(str1)); // Output: positive value (banana > apple)
• System.out.println(str1.compareTo(str3)); // Output: 0 (both are equal)

• compareToIgnoreCase(String anotherString): Compares two strings lexicographically, ignoring case


differences.
• String str1 = "apple";
• String str2 = "APPLE";
• String str3 = "banana";

• System.out.println(str1.compareToIgnoreCase(str2)); // Output: 0 (same string, ignores case)


• System.out.println(str1.compareToIgnoreCase(str3)); // Output: negative value (apple < banana)
• System.out.println(str3.compareToIgnoreCase(str1)); // Output: positive value (banana > apple)

M.Samly - Bcas Kandy Campus 80


Whitespace Manipulation
• trim(): Removes leading and trailing whitespace from the string.

• String str = " Hello, World! ";


// Using trim() to remove the spaces
• String trimmedStr = str.trim();
• System.out.println("Original: '" + str + "'"); // Output: ' Hello, World! ‘
• System.out.println("Trimmed: '" + trimmedStr + "'"); // Output: 'Hello,
World!’

• Output
• Original: ' Hello, World! '
• Trimmed: 'Hello, World!'

M.Samly - Bcas Kandy Campus 81


Replacing Substrings
• replace(char oldChar, char newChar): Replaces all occurrences of
the specified character with a new character.
• replace(CharSequence target, CharSequence replacement):
Replaces all occurrences of the specified substring with the given
replacement.
• replaceAll(String regex, String replacement): Replaces all
substrings that match the given regular expression with the
replacement string.
• replaceFirst(String regex, String replacement): Replaces the first
substring that matches the given regular expression with the
replacement string.
M.Samly - Bcas Kandy Campus 82
Example
• replace(char oldChar, char newChar): Replaces all occurrences of
the specified character with a new character.
• String str = "Hello, World!";
// Replace all occurrences of 'o' with 'a'
• String replacedStr = str.replace('o', 'a');
• System.out.println(replacedStr); // Output: Hella, Warld!

M.Samly - Bcas Kandy Campus 83


Example
• replace(CharSequence target, CharSequence replacement):
Replaces all occurrences of the specified substring with the given
replacement.
• String str = "Hello, World!";
// Replace the substring "World" with "Java"
• String replacedStr = str.replace("World", "Java");
• System.out.println(replacedStr); // Output: Hello, Java!

M.Samly - Bcas Kandy Campus 84


Example
• replaceAll(String regex, String replacement): Replaces all substrings
that match the given regular expression with the replacement string.
• String str = "apple 123, banana 456, cherry 789";
// Replace all numbers with "#" using regex
• String replacedStr = str.replaceAll("\\d+", "#");
• System.out.println(replacedStr); // Output: apple #, banana #, cherry #

• replaceFirst(String regex, String replacement): Replaces the first


substring that matches the given regular expression with the
replacement string.
• String str = "apple 123, banana 456, cherry 789";
// Replace the first occurrence of a number with "#"
• String replacedStr = str.replaceFirst("\\d+", "#");
• System.out.println(replacedStr); // Output: apple #, banana 456, cherry 789
M.Samly - Bcas Kandy Campus 85
String Splitting
• split(String regex): Splits the string into an array of substrings
based on the given regular expression.
• split(String regex, int limit): Splits the string into an array of
substrings with a limit on the number of substrings.

M.Samly - Bcas Kandy Campus 86


Example
• split(String regex): Splits the string into an array of substrings based on the given regular expression.
• String str = "apple,banana,cherry,dates";
// Split the string based on the comma (",") delimiter
• String[] fruits = str.split(",");
// Traditional for loop to iterate through the array
• for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
• }

• split(String regex, int limit): Splits the string into an array of substrings with a limit on the number of
substrings.
• String str = "apple,banana,cherry,dates";
// Split the string based on the comma (",") delimiter, but limit to 3 parts
• String[] fruits = str.split(",", 3);
// Traditional for loop to iterate through the array
• for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
• }

M.Samly - Bcas Kandy Campus 87


String Conversion
• valueOf(Object obj): Returns the string representation of the
specified object.
• format(String format, Object... args): Returns a formatted string
using the specified format string and arguments.

M.Samly - Bcas Kandy Campus 88


Example
• valueOf(Object obj): Returns the string representation of the specified object.
• int num = 100;
// Using valueOf to convert different objects to their string representation
• String str1 = String.valueOf(num); // Converts int to String
// Output the string representations
• System.out.println("Integer as String: " + str1); // Output: Integer as String: 100

• format(String format, Object... args): Returns a formatted string using the specified format
string and arguments.
• String name = "Alice";
• int age = 30;
• double salary = 55000.75;
// Using format to create a formatted string
• String formattedStr = String.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
// Output the formatted string
• System.out.println(formattedStr); // Output: Name: Alice, Age: 30, Salary: 55000.75

M.Samly - Bcas Kandy Campus 89


Scanner Class
• The Scanner class is part of the java.util package.
• It is used to read input from various sources, such as the keyboard
(standard input), files, or other input streams.
• The most common usage is for reading user input from the
console.

M.Samly - Bcas Kandy Campus 90


Continue…
• Importing the Scanner Class
• To use the Scanner class, you must import it at the beginning of your
program.
• import java.util.Scanner;

• Creating a Scanner Object


• To read from the standard input (keyboard), create a Scanner object like
this.
• Scanner scanner = new Scanner(System.in);

M.Samly - Bcas Kandy Campus 91


Reading Different Types of Input
• Reading Strings
• next(): Reads the next token (word) from input.
• String name = scanner.next();

• nextLine(): Reads the entire line of text (including spaces).


• String sentence = scanner.nextLine();

M.Samly - Bcas Kandy Campus 92


Continue…
• Reading Numbers
• nextInt(): Reads an integer.
• int age = scanner.nextInt();

• nextDouble(): Reads a double.


• double height = scanner.nextDouble();

• nextFloat(): Reads a float.


• float weight = scanner.nextFloat();

• nextLong(): Reads a long.


• long distance = scanner.nextLong();

• nextBoolean(): Reads a boolean (true/false).


• boolean isStudent = scanner.nextBoolean();

M.Samly - Bcas Kandy Campus 93


Example

M.Samly - Bcas Kandy Campus 94


Example

M.Samly - Bcas Kandy Campus 95


Example

M.Samly - Bcas Kandy Campus 96


Access Modifiers
• Access modifiers in Java determine the visibility or accessibility of
classes, methods, fields, and constructors.
• Types of Access Modifiers
• Public
• Protected
• Default
• Private

M.Samly - Bcas Kandy Campus 97


Types of Access Modifiers
• Public
• Accessible from any other class or package.

• Protected
• Accessible within the same package and by subclasses (even if they are in
different packages).

• default (Package-Private)
• Accessible only within the same package. No modifier is specified.

• Private
• Accessible only within the class it is defined in.
M.Samly - Bcas Kandy Campus 98
Example

M.Samly - Bcas Kandy Campus 99


Summary of Access Modifier

Modifier Class Same Subclass Other


Package Package
Public Yes Yes Yes Yes
Protected Yes Yes Yes No
Default Yes Yes No No
Private Yes No No No

M.Samly - Bcas Kandy Campus 100


How to Write a Method?
• A method is a block of code that performs a specific task. It has:
• Return type: The type of value it returns (or void if it doesn't return
anything).
• Method name: The name of the method.
• Parameters (optional): Inputs the method can take.
• Body: The code inside the method that executes when it's called.

returnType methodName(parameters) {
// Method body (code to be executed)
}
M.Samly - Bcas Kandy Campus 101
Example
public int add(int a, int b) {
return a + b; //returning integer number
}

public String greet() {


return "Hello, World!"; //returning string values
}

public boolean isEven(int number) {


return number % 2 == 0;
}

M.Samly - Bcas Kandy Campus 102


Example
public void printMessage() {
System.out.println("This is a message"); //No returning
}

public double calculateArea(double radius) {


return Math.PI * radius * radius; //Returning double number
}

M.Samly - Bcas Kandy Campus 103


Example

M.Samly - Bcas Kandy Campus 104


How to Create a Class?
public class Main {//main class
public static void main(String[] args){//main method
className objectName = new className(); //object
creating and object name is objectName
}
}

class className { //new calss


//codes
}
M.Samly - Bcas Kandy Campus 105
Example

M.Samly - Bcas Kandy Campus 106


Object Oriented Programming (OOP)
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

M.Samly - Bcas Kandy Campus 107


Encapsulation
• Encapsulation is the technique of keeping the data (variables)
and methods that manipulate the data within a single unit, known
as a class.
• Private Variables: Data is hidden and can only be accessed or modified
via public methods.
• Getter and Setter Methods: These provide controlled access to private
data.

M.Samly - Bcas Kandy Campus 108


Example

M.Samly - Bcas Kandy Campus 109


Abstraction
• Abstraction is the concept of hiding complex implementation
details and showing only the essential features of an object.
• Abstract Class or Interface: Used to define abstract behavior without
providing the full implementation.
• Methods: Abstract methods define actions without specifying how they
are implemented.

M.Samly - Bcas Kandy Campus 110


Example

M.Samly - Bcas Kandy Campus 111


Inheritance
• Inheritance is a mechanism where one class (child/subclass) can
inherit fields and methods from another class
(parent/superclass).
• Parent Class (Superclass): The class that is inherited from.
• Child Class (Subclass): The class that inherits from the parent class.
• extends Keyword: Used to inherit from a class in Java.

M.Samly - Bcas Kandy Campus 112


Example

M.Samly - Bcas Kandy Campus 113


Polymorphism
• Polymorphism means "many forms" and allows objects to be
treated as instances of their parent class, but to behave differently
based on their specific type.
• Method Overloading: Same method name with different parameters
(compile-time polymorphism).
• Method Overriding: Same method name and parameters in a subclass
(runtime polymorphism).

M.Samly - Bcas Kandy Campus 114


Example

M.Samly - Bcas Kandy Campus 115

You might also like