- Java Tutorial - Eclipse Installation and First Run
- Java Tutorial - Detailed Explanations
- Java Tutorial - Variables and Concatenation
- Java Tutorial - Data Types
- Java Tutorial - Data Type Conversions
- Java Tutorial - Arithmetic Operations - Simple Calc
- Java Tutorial - Simple Math Methods
- Java Tutorial - User Input - Scanner Class
- Java Tutorial - Simple Calculator with User Input
- Java Tutorial - If..Else If..Else
- Java Tutorial - If Statement with User Input
- Java Tutorial - Switch Statement
- Java Tutorial - For Loop
- Java Tutorial - Arrays and ForEach Loop
- Java Tutorial - While and Do..While Loop
- Java Tutorial - Break and Continue inside For Loop
- Java Tutorial - Break and Continue inside While Loop
- Java Tutorial - Array Operations
- Java Tutorial - Methods
- Java Tutorial - Method Parameters
- Java Tutorial - Returning a Value from Method
- Java Tutorial - Method Overloading
- Java OO Tutorial - Classes and Objects
- Java OO Tutorial - Static vs Non Static Methods
- Java OO Tutorial - Constructors
- Java OO Tutorial - Inheritance
- Java OO Tutorial - this Keyword in Java
- Java OO Tutorial - super Keyword in Java
- Java OO Tutorial - Inner Class - Nesting
- Java OO Tutorial - Abstract Classes and Methods
- Java OO Tutorial - Getters and Setters - Encapsulation
- Java OO Tutorial - Interfaces
- Java OO Tutorial - Polymorphism
- Java OO Tutorial - ArrayList
- Java OO Tutorial - ArrayList - For Loop - ForEach
- Java OO Tutorial - Enums
- Java OO Tutorial - LinkedList
- Java OO Tutorial - HashMap
- Java OO Tutorial - HashSet
- Java OO Tutorial - Try..Catch..Finally
- Java OO Tutorial - Create File in Java
- Java OO Tutorial - Write and Append to File in Java
- Java OO Tutorial - Reading a Text File in Java
Thursday, May 1, 2025
Java Tutorial
Monday, April 28, 2025
Java OO Tutorial - Reading a Text File in Java
Our Java program import needed classes from the java.io
package: File
and FileNotFoundException
.
The File
class is used to represent a file or directory in the file system. It provides methods to create, read, update, and delete files and directories.
The FileNotFoundException
class is a type of IOException
that is thrown when a file cannot be found during file I/O operations. It is often used in conjunction with the File
class to handle errors that may occur when working with files.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File fileObj = new File("externalfile.txt");
Scanner readFile = new Scanner(fileObj);
while (readFile.hasNextLine()) {
System.out.println(readFile.nextLine());
}
readFile.close();
}
catch (FileNotFoundException e) {
System.out.println("This file doesn't exists ");
System.out.println(e);
}
finally {
System.out.println("---------------------------");
System.out.println("I will work no matter what.");
System.out.println("---------------------------");
}
}
}
Here's an explanation of the code block by block:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
The program starts with the standard header for a Java file, which includes the package and import statements. In this case, we're importing java.io.File
, java.io.FileNotFoundException
, and java.util.Scanner
.
try {
File fileObj = new File("externalfile.txt");
Scanner readFile = new Scanner(fileObj);
The code then creates a File
object called fileObj
that represents the file we want to read. The filename is "externalfile.txt".
A Scanner
object is then created with the File
object as an argument. This sets up a scanner to read from the specified file.
while (readFile.hasNextLine()) {
System.out.println(readFile.nextLine());
}
The while
loop reads each line of the file until there are no more lines to read. The hasNextLine()
method checks whether there is another line in the file, and nextLine()
reads the next line.
readFile.close();
Once the file has been read, the Scanner
object is closed using the close()
method. This is good practice to ensure that system resources are freed up.
It is important to close files while operating on them with programming languages for several reasons:
-
Release of resources: When a file is opened, the operating system allocates resources to it, such as memory and CPU time. Closing the file releases these resources, freeing them up for other programs or processes to use.
-
Data integrity: If data is still being written to a file when it is closed, it can become corrupted or incomplete. Closing the file ensures that all data has been written to it and that it is saved in a consistent state.
-
Security: Open files can be accessed by other programs or processes, potentially leading to data breaches or other security issues. Closing the file ensures that it is no longer accessible to other programs.
In most programming languages, failing to close a file can result in resource leaks or other errors that can impact performance, stability, or security. Therefore, it is generally good practice to close files as soon as they are no longer needed.
} catch (FileNotFoundException e) {
System.out.println("This file doesn't exists ");
System.out.println(e);
}
If the file specified in the File
object is not found, a FileNotFoundException
will be thrown. The catch
block catches the exception and prints a message to the console.
finally {
System.out.println("---------------------------");
System.out.println("I will work no matter what.");
System.out.println("---------------------------");
}
The finally
block is executed after the try
block has finished executing, regardless of whether an exception was thrown or not. This block simply prints a message to the console to indicate that it has been executed.
Java OO Tutorial - Write and Append to File in Java
In this Java code, we are writing a string to a file named "externalfile.txt". The program tries to open the file using FileWriter and then writes the string to the file using the write()
method. Finally, it closes the file using the close()
method.
The try-catch
block is used to handle any exceptions that may be thrown while writing to the file. If an exception occurs, an error message is displayed on the console.
The finally
block is used to execute code that needs to be run regardless of whether an exception occurred or not. In this case, the "I am all over the place" message is displayed on the console.
This program demonstrates how to write data to a file in Java using FileWriter class.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter fileObj = new FileWriter("externalfile.txt");
fileObj.write("I will end up in external file\n");
fileObj.close();
System.out.println("Operation done.");
} catch (IOException fError) {
System.out.println(fError);
} finally {
System.out.println("I am all over the place.");
}
}
}
Here's a breakdown of the code block by block:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
This block of code imports necessary classes for file operations, including File
, FileWriter
, and IOException
.
public class Main {
public static void main(String[] args) {
This block of code begins the definition of the Main
class and the main()
method.
try {
FileWriter fileObj = new FileWriter("externalfile.txt");
fileObj.write("I will end up in external file\n");
fileObj.close();
System.out.println("Operation done.");
}
This block of code uses a try
block to write a string to a file named "externalfile.txt".
A FileWriter
object named fileObj
is created, which represents the file we want to write to.
The write()
method is then called on fileObj
to write the string "I will end up in external file" to the file, followed by a new line character.
Finally, the close()
method is called on fileObj
to close the file.
catch (IOException fError) {
System.out.println(fError);
}
This block of code uses a catch
block to catch any IOException
that may occur while writing to the file. If an exception is caught, an error message is printed to the console.
finally {
System.out.println("I am all over the place.");
}
This block of code uses a finally
block to execute code that needs to be run regardless of whether an exception occurred or not. In this case, the message "I am all over the place" is printed to the console.
Java OO Tutorial - Create File in Java
File operations are an essential part of programming. Some of the most common file operations in programming are:
-
Creating a file: Creating a file is the first step to storing data in a file. The file creation process may vary depending on the programming language and the platform.
-
Opening a file: Once a file is created, it needs to be opened to access or manipulate its contents. This step requires the use of file access methods and APIs provided by the programming language.
-
Reading from a file: This operation involves reading data from a file and storing it in a variable or data structure. Reading can be done in different ways such as line-by-line, character-by-character, or in a single chunk.
-
Writing to a file: Writing to a file is the process of adding data to a file. Like reading, this can be done in different ways such as line-by-line, character-by-character, or in a single chunk.
-
Closing a file: Once a file has been opened and manipulated, it needs to be closed. Closing a file ensures that all data is written to the file and that resources are freed up.
-
Deleting a file: Deleting a file removes it from the system permanently. This operation is irreversible, and once a file is deleted, it cannot be recovered.
-
Renaming a file: Renaming a file involves changing its name. This operation is useful when you want to change the name of a file to make it more meaningful or when you want to move a file to a different directory.
-
Moving a file: Moving a file involves transferring it from one directory to another. This operation is useful when you want to reorganize your file system or move files between different devices.
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File fileObj = new File("externalfile.txt");
if (fileObj.createNewFile()) {
System.out.println("Operation done: " + fileObj.getName());
} else {
System.out.println("Check local directory, file with that name exists.");
}
}
catch (IOException fError) {
System.out.println(fError);
}
finally {
System.out.println("I am all over the place.");
}
}
}
This is a Java program that creates a new file named "externalfile.txt" in the current directory, and handles any possible errors using try
, catch
, and finally
blocks. Here's a line-by-line explanation of the code:
import java.io.File;
import java.io.IOException;
These lines import the File
class from the java.io
package, and the IOException
class from the java.io
package.
public class Main {
This line declares a public class named Main
.
public static void main(String[] args) {
This line declares the main()
method which is the entry point of the program. It takes an array of strings as a parameter.
try {
File fileObj = new File("externalfile.txt");
if (fileObj.createNewFile()) {
System.out.println("Operation done: " + fileObj.getName());
} else {
System.out.println("Check local directory, file with that name exists.");
}
}
This line starts a try
block which contains the code that may throw an exception. It creates a new File
object named fileObj
and initializes it with the name "externalfile.txt". It then attempts to create a new file with that name using the createNewFile()
method. If the file is successfully created, it prints a success message to the console. Otherwise, it prints a message indicating that a file with that name already exists.
catch (IOException fError) {
System.out.println(fError);
}
This line starts a catch
block which catches any IOException
that is thrown in the try
block. If an exception is caught, the block prints the exception message to the console.
finally {
System.out.println("I am all over the place.");
}
This line starts a finally
block which is executed whether or not an exception is thrown in the try
block. This block prints a message to the console.
Java OO Tutorial - Try..Catch..Finally
In Java, try
, catch
, and finally
are used together to handle exceptions or errors that occur during program execution.
The try
block contains the code that may throw an exception. This block is followed by one or more catch
blocks that catch the exception and handle it accordingly. If an exception is thrown in the try
block, the catch
block with a matching exception type will execute.
The finally
block, which is optional, is used to execute code that needs to be executed regardless of whether an exception is thrown or not. This block is typically used to release any resources that were acquired in the try
block, such as closing a file or releasing a database connection.
public class Main {
public static void main(String[] args) {
String[] monitors = { "Dell", "IBM", "Benq" };
try {
System.out.println(monitors[2]);
}
catch (Exception z) {
System.out.println("Error 4731 - Can't find specific index");
System.out.println(z);
}
finally {
System.out.println("--------------------------");
System.out.println("I will run no matter what.");
System.out.println("--------------------------");
}
}
}
Here's a line-by-line explanation of the code:
public class Main {
This line declares a public class named Main
.
public static void main(String[] args) {
This line declares the main()
method which is the entry point of the program. It takes an array of strings as a parameter.
String[] monitors = { "Dell", "IBM", "Benq" };
This line declares an array of strings named monitors
and initializes it with three elements: "Dell"
, "IBM"
, and "Benq"
.
try {
System.out.println(monitors[2]);
}
This line starts a try
block which contains the code that may throw an exception. It tries to print the value of the element at index 2 of the monitors
array using the println()
method.
catch (Exception z) {
System.out.println("Error 4731 - Can't find specific index");
System.out.println(z);
}
This line starts a catch
block which catches any Exception
that is thrown in the try
block. If an exception is caught, the block prints an error message and the exception message to the console.
finally {
System.out.println("--------------------------");
System.out.println("I will run no matter what.");
System.out.println("--------------------------");
}
This line starts a finally
block which is executed whether or not an exception is thrown in the try
block. This block prints a separator line and a message to the console.
Java OO Tutorial - HashSet
A HashSet
is a collection that stores unique elements. It is implemented using a hash table data structure. The elements in a HashSet
are not stored in any particular order, and their position in the HashSet
can change as elements are added or removed.
When you add an element to a HashSet
, the hash code of the element is used to calculate its position in the hash table. If another element already exists at that position, the HashSet
uses the equals() method to determine if the two elements are equal. If the two elements are equal, the new element is not added. If the two elements are not equal, the HashSet
puts the new element in a different position in the hash table.
HashSet
is often used when you want to maintain a set of unique elements and don't care about their order.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> monitors = new HashSet<String>();
monitors.add("Dell");
monitors.add("IBM");
monitors.add("Benq");
System.out.println(monitors);
//Size
System.out.println("Set Size: " + monitors.size());
//Check for element
System.out.println("Set Size: " + monitors.contains("Dell"));
//Get all elements
for (String x : monitors) {
System.out.println(x);
}
//Remove element
monitors.remove("Benq");
System.out.println(monitors);
//Clear all elements
monitors.clear();
System.out.println(monitors);
}
}
This is Java code that demonstrates the usage of a HashSet. The HashSet is a collection in Java that is used to store unique elements. Below is a breakdown of the code, line by line:
import java.util.HashSet;
This line imports the HashSet class from the Java Utility library. This is required because the code will make use of the HashSet.
public class Main {
This line declares a class called Main
. The class has a public access modifier, which means it can be accessed from outside of the class.
public static void main(String[] args) {
This line declares a main method, which is the entry point of the Java program. The public
modifier means the method can be accessed from outside of the class. The static
modifier means the method can be called without an instance of the class. The void
keyword indicates that the method doesn't return a value. The String[] args
parameter allows the method to accept command-line arguments.
HashSet<String> monitors = new HashSet<String>();
This line declares a HashSet called monitors
. The HashSet is used to store unique strings. The String
in HashSet<String>
specifies the type of elements to be stored in the HashSet. Here, it is String
.
monitors.add("Dell");
monitors.add("IBM");
monitors.add("Benq");
These three lines add three elements to the monitors
HashSet. The add
method is called on the HashSet to add each element.
System.out.println(monitors);
This line prints the entire monitors
HashSet to the console. The println
method is used to print the object to the console.
System.out.println("Set Size: " + monitors.size());
This line prints the size of the monitors
HashSet to the console. The size
method is called on the HashSet to get the number of elements in it. The +
operator is used to concatenate the size with the string "Set Size: ".
System.out.println("Set Size: " + monitors.contains("Dell"));
This line checks whether the monitors
HashSet contains the element "Dell". The contains
method is called on the HashSet to check whether the element is present. The result is then printed to the console.
for (String x : monitors) {
System.out.println(x);
}
This loop prints all the elements of the monitors
HashSet to the console. The loop iterates over each element in the HashSet, and the println
method is used to print each element to the console.
monitors.remove("Benq");
System.out.println(monitors);
This line removes the element "Benq" from the monitors
HashSet. The remove
method is called on the HashSet to remove the element. The updated HashSet is then printed to the console.
monitors.clear();
System.out.println(monitors);
This line removes all elements from the monitors
HashSet. The clear
method is called on the HashSet to remove all elements. The updated HashSet is then printed to the console.
Java OO Tutorial - HashMap
A HashMap is a data structure that is used to store key-value pairs. It is part of the java.util package and is implemented as a hash table. HashMaps are useful when you need to store and retrieve data based on keys rather than indexes, as in the case of arrays and ArrayLists.
In a HashMap, the keys must be unique, but the values can be duplicated.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> people = new HashMap<String, String>();
people.put("Alabama", "Monica");
people.put("Arizona", "John");
people.put("Idaho", "Samantha");
//Get by Key - left side
System.out.println(people.get("Alabama"));
//Number of elements
System.out.println("Hash Size: " + people.size());
//Get all pairs
for (String x : people.keySet()) {
System.out.println("Pair: " + x + "->" + people.get(x));
}
//Remove pair
people.remove("Idaho");
System.out.println(people);
//Clear all pairs
people.clear();
System.out.println(people);
}
}
Explanation, block by block:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> people = new HashMap<String, String>();
people.put("Alabama", "Monica");
people.put("Arizona", "John");
people.put("Idaho", "Samantha");
-
We start by importing the
HashMap
class from thejava.util
package and creating a newMain
class. -
In the
main
method, we create a newHashMap
object calledpeople
that will holdString
keys andString
values. -
We use the
put
method to add three key-value pairs to thepeople
map. The keys are U.S. state names and the values are people's names.
//Get by Key - left side
System.out.println(people.get("Alabama"));
- We use the
get
method to retrieve the value associated with the key"Alabama"
and print it to the console.
//Number of elements
System.out.println("Hash Size: " + people.size());
- We use the
size
method to print the number of key-value pairs in thepeople
map.
//Get all pairs
for (String x : people.keySet()) {
System.out.println("Pair: " + x + "->" + people.get(x));
}
- We use a
for
loop to iterate over all the keys in thepeople
map using thekeySet
method. For each key, we use theget
method to retrieve its associated value and print both to the console.
//Remove pair
people.remove("Idaho");
System.out.println(people);
- We use the
remove
method to remove the key-value pair with the key"Idaho"
from thepeople
map, and then print the updated map to the console.
//Clear all pairs
people.clear();
System.out.println(people);
}
}
- Finally, we use the
clear
method to remove all the key-value pairs from thepeople
map and then print the empty map to the console.
Java OO Tutorial - LinkedList
A linked list is a data structure that represents a sequence of nodes, where each node points to the next node in the list. Each node in the list contains an element of data, as well as a reference to the next node in the list.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> pLanguages = new LinkedList<String>();
pLanguages.add("Java");
pLanguages.add("Lisp");
pLanguages.add("C++");
System.out.println(pLanguages);
//Adding Stuff
pLanguages.addFirst("Prolog");
System.out.println(pLanguages);
pLanguages.addLast("Ada");
System.out.println(pLanguages);
//Get Stuff
System.out.println("First Element: " + pLanguages.getFirst());
System.out.println("Last Element: " + pLanguages.getLast());
System.out.println(pLanguages);
//Remove Stuff
pLanguages.removeFirst();
pLanguages.removeLast();
System.out.println(pLanguages);
}
}
Our program here demonstrates the use of LinkedList in Java.
import java.util.LinkedList;
This line imports the LinkedList class from the Java.util package.
public class Main {
public static void main(String[] args) {
The class Main is declared with a main() method inside.
LinkedList<String> pLanguages = new LinkedList<String>();
A LinkedList object named pLanguages is created, which will contain strings.
pLanguages.add("Java");
pLanguages.add("Lisp");
pLanguages.add("C++");
Elements are added to the LinkedList using the add() method.
System.out.println(pLanguages);
This prints the LinkedList pLanguages to the console.
pLanguages.addFirst("Prolog");
System.out.println(pLanguages);
pLanguages.addLast("Ada");
System.out.println(pLanguages);
Two new elements are added to the LinkedList at the beginning and the end of the list using the addFirst() and addLast() methods.
System.out.println("First Element: " + pLanguages.getFirst());
System.out.println("Last Element: " + pLanguages.getLast());
System.out.println(pLanguages);
The first and last elements of the LinkedList are retrieved using the getFirst() and getLast() methods.
pLanguages.removeFirst();
pLanguages.removeLast();
System.out.println(pLanguages);
Finally, the first and last elements are removed from the LinkedList using the removeFirst() and removeLast() methods. The resulting list is printed to the console using println().
The output of this program should be:
[Java, Lisp, C++]
[Prolog, Java, Lisp, C++]
[Prolog, Java, Lisp, C++, Ada]
First Element: Prolog
Last Element: Ada
[Prolog, Java, Lisp, C++, Ada]
[Java, Lisp, C++]
Java OO Tutorial - Enums
Enums in Java are a special data type that allow you to define a set of constants with a specific name and value. They are used to represent a fixed set of values that don't change during the execution of the program. Enum constants are static and final by default.
In Java, you define an enum using the enum
keyword followed by the name of the enumeration.
enum Options {
AUDIO,
VIDEO,
CONTROLS
}
public class Main {
public static void main(String[] args) {
for (Options someObj : Options.values()) {
System.out.println(someObj);
}
/*
Options inputObj = Options.VIDEO;
switch(inputObj) {
case AUDIO:
System.out.println("Audio Settings");
break;
case VIDEO:
System.out.println("Video Settings");
break;
case CONTROLS:
System.out.println("Joystick and Keyboard Settings");
break;
}*/
}
}
Here's an explanation of the code block by block:
enum Options {
AUDIO,
VIDEO,
CONTROLS
}
This defines an enum
called Options
with three possible values: AUDIO
, VIDEO
, and CONTROLS
.
public class Main {
public static void main(String[] args) {
...
}
}
This defines a class called Main
with a main
method.
for (Options someObj : Options.values()) {
System.out.println(someObj);
}
This loop iterates over all the possible values of the Options
enum using the values
method, and prints each value to the console.
/*
Options inputObj = Options.VIDEO;
switch(inputObj) {
case AUDIO:
System.out.println("Audio Settings");
break;
case VIDEO:
System.out.println("Video Settings");
break;
case CONTROLS:
System.out.println("Joystick and Keyboard Settings");
break;
}*/
This is a commented out code block that demonstrates how enum
values can be used in a switch
statement. Here, VIDEO
is used as the input object, and the switch
statement checks which value it matches and prints out the corresponding message.
Java OO Tutorial - ArrayList - For Loop - ForEach
For loops and foreach loops are commonly used with ArrayLists to iterate over the elements of the list and perform various operations.
import java.util.Collections
is a statement in Java that allows you to access the methods and classes defined in the java.util.Collections
package.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> pLanguages = new ArrayList<String>();
pLanguages.add("Lisp");
pLanguages.add("Java");
pLanguages.add("Python");
pLanguages.add("C++");
pLanguages.add("Ada");
System.out.println(pLanguages);
//System.out.println("Number of elements: " + pLanguages.size());
Collections.sort(pLanguages);
for (String x : pLanguages) {
System.out.println(x);
}
/*
for (int x = 0; x < pLanguages.size(); x++) {
System.out.println("Index: " + x + " " + pLanguages.get(x));
}
*/
}
}
Here's a detailed explanation of the code block by block:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> pLanguages = new ArrayList<String>();
pLanguages.add("Lisp");
pLanguages.add("Java");
pLanguages.add("Python");
pLanguages.add("C++");
pLanguages.add("Ada");
System.out.println(pLanguages);
In this code, we first import the necessary classes: ArrayList and Collections. We then create an ArrayList of Strings called pLanguages
and add five programming languages to it using the add
method. We then print the contents of the ArrayList using System.out.println(pLanguages)
.
//System.out.println("Number of elements: " + pLanguages.size());
This line is commented out, but it shows how to get the number of elements in the ArrayList using the size
method.
Collections.sort(pLanguages);
This line sorts the ArrayList in alphabetical order using the sort
method of the Collections
class.
for (String x : pLanguages) {
System.out.println(x);
}
This block of code uses a foreach loop to iterate over each element of the ArrayList and print it to the console. The loop variable x
is of type String
and takes on the value of each element of the ArrayList in turn.
/*
for (int x = 0; x < pLanguages.size(); x++) {
System.out.println("Index: " + x + " " + pLanguages.get(x));
}
*/
This block of code is commented out, but it shows how to use a traditional for loop to iterate over the ArrayList and print each element along with its index. The loop variable x
is of type int
and takes on the values of the indices of the ArrayList elements. The get
method is used to retrieve the element at each index.
Java OO Tutorial - ArrayList
An ArrayList
is a class that provides an implementation of a dynamic array. It is part of the java.util
package and is similar to a regular array, but with several additional features. Here are some key points to know about ArrayList
:
- An
ArrayList
is created with a default initial capacity, but the capacity can be increased as needed. - The size of an
ArrayList
can be changed dynamically as elements are added or removed. - An
ArrayList
can hold objects of any type, including custom-defined classes. - Elements in an
ArrayList
are stored in contiguous memory locations, just like a regular array. - An
ArrayList
supports several useful methods for adding, removing, and accessing elements, such asadd()
,remove()
,get()
,set()
,size()
,isEmpty()
, and more.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> pLanguages = new ArrayList<String>();
pLanguages.add("Lisp");
pLanguages.add("Java");
pLanguages.add("Python");
pLanguages.add("C++");
System.out.println(pLanguages); //get all elements
System.out.println(pLanguages.get(0)); //get by index
pLanguages.set(0, "Prolog"); //change by index
System.out.println(pLanguages);
pLanguages.remove(0); //remove element
System.out.println(pLanguages);
pLanguages.clear(); //delete all elements
System.out.println(pLanguages);
pLanguages.add("Perl");
System.out.println(pLanguages);
}
}
Here's an explanation of the code block by block:
import java.util.ArrayList;
This line imports the ArrayList
class from the java.util
package, which is required to use the ArrayList
in Java.
public class Main {
public static void main(String[] args) {
This code block defines the Main
class, which contains the main method that will be executed when the program is run.
ArrayList<String> pLanguages = new ArrayList<String>();
This line creates an ArrayList
of type String
named pLanguages
.
pLanguages.add("Lisp");
pLanguages.add("Java");
pLanguages.add("Python");
pLanguages.add("C++");
These lines add some elements to the pLanguages
list.
System.out.println(pLanguages); //get all elements
System.out.println(pLanguages.get(0)); //get by index
These lines demonstrate how to get the elements from the list. The first line prints all elements in the list, while the second line prints the element at index 0.
pLanguages.set(0, "Prolog"); //change by index
System.out.println(pLanguages);
This line demonstrates how to modify an element in the list. It changes the element at index 0 from "Lisp" to "Prolog", and then prints the updated list.
pLanguages.remove(0); //remove element
System.out.println(pLanguages);
This line demonstrates how to remove an element from the list. It removes the element at index 0 (which is now "Prolog" because we changed it in the previous step), and then prints the updated list.
pLanguages.clear(); //delete all elements
System.out.println(pLanguages);
This line demonstrates how to delete all elements from the list. It calls the clear()
method on the pLanguages
list, which removes all elements, and then prints the updated list (which should be empty).
pLanguages.add("Perl");
System.out.println(pLanguages);
This line demonstrates how to add a new element to the list. It adds the string "Perl" to the pLanguages
list, and then prints the updated list.
Java OO Tutorial - Polymorphism
Polymorphism is a fundamental concept in Java that refers to the ability of objects to take on multiple forms.
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
class SecondaryA extends Primary {
public void sameName() {
System.out.println("I am from SecondaryA Class");
}
}
class SecondaryB extends Primary {
public void sameName() {
System.out.println("I am from SecondaryB Class");
}
}
public class Main {
public static void main(String[] args) {
Primary primObj = new Primary();
Primary secAObj = new SecondaryA();
Primary secBObj = new SecondaryB();
primObj.sameName();
secAObj.sameName();
secBObj.sameName();
}
}
Here's an explanation of the code block by block:
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
This code defines a class Primary
with a method sameName()
, which simply prints "I am from Primary Class" to the console.
class SecondaryA extends Primary {
public void sameName() {
System.out.println("I am from SecondaryA Class");
}
}
This code defines a subclass SecondaryA
of the Primary
class. SecondaryA
also has a sameName()
method, but in this case, it prints "I am from SecondaryA Class" to the console. Since SecondaryA
extends Primary
, it inherits the sameName()
method from Primary
but overrides it with its own implementation.
class SecondaryB extends Primary {
public void sameName() {
System.out.println("I am from SecondaryB Class");
}
}
This code defines another subclass SecondaryB
of the Primary
class. SecondaryB
also has a sameName()
method, which prints "I am from SecondaryB Class" to the console. Again, since SecondaryB
extends Primary
, it inherits the sameName()
method from Primary
but overrides it with its own implementation.
public class Main {
public static void main(String[] args) {
Primary primObj = new Primary();
Primary secAObj = new SecondaryA();
Primary secBObj = new SecondaryB();
primObj.sameName();
secAObj.sameName();
secBObj.sameName();
}
}
This code defines the Main
class with a main()
method. In the main()
method, we create objects of Primary
, SecondaryA
, and SecondaryB
classes and assign them to variables of type Primary
. We then call the sameName()
method on each of these objects. The output will be:
I am from Primary Class
I am from SecondaryA Class
I am from SecondaryB Class
This demonstrates the concept of polymorphism in Java, where the same method (sameName()
) can be called on different objects (primObj
, secAObj
, and secBObj
), and the implementation of the method that is called depends on the actual type of the object that the method is called on.
Java OO Tutorial - Interfaces
An interface is a collection of abstract methods (methods without an implementation) and constants. An interface can be used to define a set of methods that a class must implement, without specifying how those methods are implemented.
To declare an interface in Java, you use the interface
keyword followed by the name of the interface.
interface Car {
public void operationA();
public void operationB();
}
interface Bike {
public void lights();
}
class ModelA implements Car, Bike {
public void operationA() {
System.out.println("Operation A");
}
public void operationB() {
System.out.println("Operation B");
}
public void lights() {
System.out.println("Generic Lights Starts");
}
}
public class Main {
public static void main(String[] args) {
ModelA firstObj = new ModelA();
firstObj.operationA();
firstObj.operationB();
firstObj.lights();
}
}
This code defines an interface Car
with two abstract methods operationA()
and operationB()
. It also defines another interface Bike
with one abstract method lights()
.
interface Car {
public void operationA();
public void operationB();
}
interface Bike {
public void lights();
}
Next, a class named ModelA
is defined that implements both the Car
and Bike
interfaces. This class provides the implementation of all the abstract methods declared in the interfaces it implements.
class ModelA implements Car, Bike {
public void operationA() {
System.out.println("Operation A");
}
public void operationB() {
System.out.println("Operation B");
}
public void lights() {
System.out.println("Generic Lights Starts");
}
}
The operationA()
method of ModelA
class simply prints "Operation A" to the console. The operationB()
method of ModelA
class prints "Operation B" to the console. The lights()
method of ModelA
class prints "Generic Lights Starts" to the console.
Finally, in the main()
method of the Main
class, an instance of the ModelA
class is created and the methods operationA()
, operationB()
, and lights()
are called on it.
public class Main {
public static void main(String[] args) {
ModelA firstObj = new ModelA();
firstObj.operationA();
firstObj.operationB();
firstObj.lights();
}
}
This code demonstrates how a class can implement multiple interfaces and provide implementation for all the methods declared in them. It also demonstrates how objects of a class can be created and methods can be called on them.
Java OO Tutorial - Getters and Setters - Encapsulation
Getters and setters are methods that are used to access and modify the values of private instance variables of a class, respectively.
A getter method is used to retrieve the value of a private instance variable, and it typically has a name that starts with "get" followed by the name of the variable. For example, if a class has a private instance variable named "name", then the getter method for that variable could be named "getName()". A typical implementation of a getter method simply returns the value of the instance variable.
A setter method, on the other hand, is used to set the value of a private instance variable, and it typically has a name that starts with "set" followed by the name of the variable. For example, if a class has a private instance variable named "age", then the setter method for that variable could be named "setAge(int age)". A typical implementation of a setter method takes a parameter of the same type as the instance variable and sets its value to the instance variable.
By using getters and setters, you can control the access to the instance variables of a class, and you can enforce constraints on the values that are being set. For example, you could check if the value being set is within a certain range or if it meets certain conditions before actually setting it. This way, you can ensure that the state of your object remains consistent and valid.
//Base.java
public class Base {
private String name;
public void setName(String a) {
this.name = a;
}
public String getName() {
return name;
}
}
Our code defines a class named Base
that has a private instance variable name
of type String
. It also provides two methods to access and modify the value of this variable: a setter method setName()
and a getter method getName()
.
The setName()
method takes a parameter of type String
and sets the value of the name
variable to the value of the parameter. The getName()
method returns the current value of the name
variable.
The use of the private
access modifier for the name
variable ensures that it can only be accessed and modified within the Base
class. By providing public getter and setter methods, other classes can access and modify the value of the name
variable in a controlled way, without exposing the variable itself to direct modification from outside the class.
Note that the use of the this
keyword in the setName()
method is used to refer to the instance variable name
, which is otherwise shadowed by the method parameter a
of the same name.
//Main.java
public class Main {
public static void main(String[] args) {
Base someObj = new Base();
someObj.setName("Some Value");
System.out.println(someObj.getName());
}
}
In this case our code defines a class named Main
that has a main()
method. The main()
method creates a new object of type Base
named someObj
using the new
operator. It then calls the setName()
method on the someObj
object, passing it a string value "Some Value" as a parameter. This sets the value of the name
instance variable of the someObj
object to "Some Value".
Finally, the main()
method calls the getName()
method on the someObj
object and passes its return value to the println()
method of the System.out
object, which prints the value of the name
instance variable to the console.
This code demonstrates the use of getter and setter methods to access and modify private instance variables of an object in a controlled way. It also demonstrates the use of the new
operator to create new objects of a class, and the use of the System.out.println()
method to print output to the console.
Java OO Tutorial - Abstract Classes and Methods
An abstract class is a class that is declared with the abstract
keyword, which means that it cannot be instantiated directly. An abstract class is designed to be extended by other classes, and it provides a base set of methods or functionality that derived classes can implement or override. An abstract class can have both abstract and non-abstract methods.
An abstract method is a method that is declared with the abstract
keyword, but does not have an implementation. It only has a method signature, which includes the method name, return type, and parameters, but does not have any method body. Abstract methods are declared in abstract classes, and they are meant to be implemented by non-abstract subclasses.
abstract class Base {
public abstract void firstAbsMethod();
public abstract void secondAbsMethod();
}
class Details extends Base {
public void firstAbsMethod() {
System.out.println("I am from firstAbsMethod");
}
public void secondAbsMethod() {
System.out.println("I am from secondAbsMethod");
}
}
public class Main {
public static void main(String[] args) {
Details someObj = new Details();
someObj.firstAbsMethod();
someObj.secondAbsMethod();
}
}
Here is a block-by-block explanation of the code:
abstract class Base {
public abstract void firstAbsMethod();
public abstract void secondAbsMethod();
}
This defines an abstract class Base
that contains two abstract methods named firstAbsMethod
and secondAbsMethod
. These methods have no implementation and are intended to be overridden by subclasses of Base
.
class Details extends Base {
public void firstAbsMethod() {
System.out.println("I am from firstAbsMethod");
}
public void secondAbsMethod() {
System.out.println("I am from secondAbsMethod");
}
}
The Details
class extends the Base
class and provides implementations for the two abstract methods declared in Base
. In other words, Details
is a concrete class that can be instantiated and used. It defines its own behavior for the two abstract methods, providing the necessary implementations.
public class Main {
public static void main(String[] args) {
Details someObj = new Details();
someObj.firstAbsMethod();
someObj.secondAbsMethod();
}
}
Finally, the Main
class contains a main
method that creates an instance of Details
and calls its firstAbsMethod
and secondAbsMethod
methods. The output of running this program will be:
I am from firstAbsMethod
I am from secondAbsMethod
This demonstrates the concept of abstract classes and methods in Java, where a subclass must provide implementations for the abstract methods declared in its superclass, or else be declared abstract itself.
Java OO Tutorial - Inner Class - Nesting
An inner class is a class that is defined within the body of another class.
class OutsiderClass {
public void outsiderMethod() {
System.out.println("I am from outsiderMethod");
}
class InsiderClass {
public void insiderMethod() {
System.out.println("I am from insiderMethod");
}
}
}
public class Main {
public static void main(String[] args) {
OutsiderClass outObj = new OutsiderClass();
outObj.outsiderMethod();
OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
inObj.insiderMethod();
}
}
Here's a detailed explanation of the code, block by block:
class OutsiderClass {
public void outsiderMethod() {
System.out.println("I am from outsiderMethod");
}
class InsiderClass {
public void insiderMethod() {
System.out.println("I am from insiderMethod");
}
}
}
The above code defines two classes: OutsiderClass
and InsiderClass
. InsiderClass
is an inner class defined inside OutsiderClass
.
OutsiderClass
has one method outsiderMethod()
that simply prints out a message to the console using System.out.println()
.
InsiderClass
has one method insiderMethod()
that also prints out a message to the console.
public class Main {
public static void main(String[] args) {
OutsiderClass outObj = new OutsiderClass();
outObj.outsiderMethod();
OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
inObj.insiderMethod();
}
}
The above code is the Main
class, which contains the main()
method. Inside the main()
method:
- An instance of
OutsiderClass
is created using thenew
keyword:OutsiderClass outObj = new OutsiderClass();
- The
outsiderMethod()
is called on the instance ofOutsiderClass
using the dot notation:outObj.outsiderMethod();
- An instance of
InsiderClass
is created using thenew
keyword and the constructor forInsiderClass
, which is accessed using the instance ofOutsiderClass
created earlier:OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
- The
insiderMethod()
is called on the instance ofInsiderClass
using the dot notation:inObj.insiderMethod();
When this code is run, it will output the following to the console:
I am from outsiderMethod
I am from insiderMethod
Java OO Tutorial - super Keyword in Java
In Java, super
is a keyword that refers to the immediate parent class of a subclass. It is used to call a constructor, method, or variable of the parent class from within the subclass.
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
class Secondary extends Primary {
public void sameName() {
super.sameName();
System.out.println("I am from Secondary Class");
}
}
public class Main {
public static void main(String[] args) {
//Primary primObj = new Primary();
//primObj.sameName();
Secondary secObj = new Secondary();
secObj.sameName();
}
}
This Java program defines three classes: Primary
, Secondary
, and Main
.
The Primary
class has one method called sameName()
, which simply prints the message "I am from Primary Class" to the console.
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
The Secondary
class extends the Primary
class and overrides the sameName()
method. Inside the sameName()
method of the Secondary
class, the super
keyword is used to call the sameName()
method of the parent class, and then it prints the message "I am from Secondary Class" to the console.
class Secondary extends Primary {
public void sameName() {
super.sameName();
System.out.println("I am from Secondary Class");
}
}
The Main
class contains the main()
method, which creates an object of the Secondary
class using the new
keyword and assigns it to a reference variable named secObj
. Then, it calls the sameName()
method on the secObj
reference variable.
public class Main {
public static void main(String[] args) {
Secondary secObj = new Secondary();
secObj.sameName();
}
}
When the sameName()
method of the secObj
object is called, the following output will be printed to the console:
I am from Primary Class
I am from Secondary Class
This shows that when a subclass overrides a method of its parent class, it can call the overridden method of the parent class using the super
keyword, and then it can add its own functionality to the method.
In this example, the Secondary
class added the message "I am from Secondary Class" to the output, but it first called the sameName()
method of the parent Primary
class to include its message "I am from Primary Class".
Java OO Tutorial - this Keyword in Java
In Java, this
is a keyword that refers to the current instance of a class. It can be used inside the methods or constructors of a class to refer to the current object on which the method is being called or the constructor is being invoked.
class InternalOperations {
int x;
int y;
public InternalOperations(int a, int b) {
this.x = a;
this.y = b;
}
}
public class Main {
public static void main(String[] args) {
InternalOperations someObj = new InternalOperations(10, 20);
System.out.println("X Value: " + someObj.x);
System.out.println("Y Value: " + someObj.y);
InternalOperations otherObj = new InternalOperations(5, 55);
System.out.println("X Value: " + otherObj.x);
System.out.println("Y Value: " + otherObj.y);
}
}
This Java program defines two classes: InternalOperations
and Main
.
The InternalOperations
class has two instance variables x
and y
of type int
. It also has a constructor that takes two integer parameters a
and b
, and initializes the instance variables x
and y
with the values of the parameters.
class InternalOperations {
int x;
int y;
public InternalOperations(int a, int b) {
this.x = a;
this.y = b;
}
}
The Main
class contains the main()
method, which is the entry point of the program.
Inside the main()
method, two objects of the InternalOperations
class are created using the new
keyword and the constructor that takes two integer arguments.
The first object is assigned to a reference variable named someObj
, and the second object is assigned to a reference variable named otherObj
.
public class Main {
public static void main(String[] args) {
InternalOperations someObj = new InternalOperations(10, 20);
InternalOperations otherObj = new InternalOperations(5, 55);
// ...
}
}
After the objects are created, the values of the instance variables x
and y
of both objects are printed using the System.out.println()
method.
System.out.println("X Value: " + someObj.x);
System.out.println("Y Value: " + someObj.y);
System.out.println("X Value: " + otherObj.x);
System.out.println("Y Value: " + otherObj.y);
The output of the program will be:
X Value: 10
Y Value: 20
X Value: 5
Y Value: 55
This shows that each object of the InternalOperations
class has its own instance variables x
and y
, which can be initialized and accessed independently of each other.
The program demonstrates the use of constructors to create objects of a class and the use of instance variables to store object-specific data.
Java OO Tutorial - Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit the properties (fields) and behaviors (methods) of another class. In Java, we use the "extends" keyword to create a subclass that inherits from a parent (superclass) class.
A subclass can inherit fields and methods from a superclass and also add its own fields and methods, and override the behavior of inherited methods. The benefit of inheritance is that it allows us to reuse code that already exists in a superclass, reducing the amount of code we need to write.
//Operations.java
class BasicOperations {
public void addition(int x, int y) {
System.out.println(x + y);
}
}
class MoreOperations extends BasicOperations {
public void multiplication(int x, int y) {
System.out.println(x * y);
}
}
public class Operations extends MoreOperations {
public void substraction(int x, int y) {
System.out.println(x - y);
}
public static void main(String[] args) {
Operations myObj = new Operations();
myObj.addition(10, 5);
myObj.substraction(10, 5);
myObj.multiplication(10, 5);
}
}
Here's an explanation of the code block by block:
//Operations.java
class BasicOperations {
public void addition(int x, int y) {
System.out.println(x + y);
}
}
This is the BasicOperations
class with a single method addition
that takes two integer arguments and prints their sum.
class MoreOperations extends BasicOperations {
public void multiplication(int x, int y) {
System.out.println(x * y);
}
}
This is the MoreOperations
class that extends the BasicOperations
class and adds a method multiplication
that takes two integer arguments and prints their product.
public class Operations extends MoreOperations {
public void subtraction(int x, int y) {
System.out.println(x - y);
}
public static void main(String[] args) {
Operations myObj = new Operations();
myObj.addition(10, 5);
myObj.subtraction(10, 5);
myObj.multiplication(10, 5);
}
}
This is the Operations
class that extends the MoreOperations
class and adds a method subtraction
that takes two integer arguments and prints their difference. It also contains a main
method that creates an instance of the Operations
class and calls its addition
, subtraction
, and multiplication
methods.
When we run the main
method, it creates an instance of the Operations
class and calls its addition
, subtraction
, and multiplication
methods.
Since the Operations
class extends the MoreOperations
class, which in turn extends the BasicOperations
class, it has access to all the methods in these classes.
Therefore, it can call the addition
, subtraction
, and multiplication
methods without having to define them in the Operations
class itself.
Java OO Tutorial - Constructors
A constructor is a special method that is used to create objects of a class. It is called automatically when an object is created using the "new" keyword. The constructor has the same name as the class and does not have a return type, not even void.
public class Main {
int x;
//This is Constructor - same name as Class name
public Main() {
x = 10;
}
public static void main(String[] args) {
Main newObj = new Main();
System.out.println(newObj.x);
newObj.x = 555;
System.out.println(newObj.x);
}
}
Here's a block-by-block breakdown of the program:
public class Main {
int x;
public Main() {
x = 10;
}
In this block, we define a class named "Main" with a single member variable "x". We also define a constructor for this class that sets the value of "x" to 10.
public static void main(String[] args) {
Main newObj = new Main();
System.out.println(newObj.x);
newObj.x = 555;
System.out.println(newObj.x);
}
In this block, we define the main method which is the entry point for the program. Inside this method, we create an instance of the Main class named "newObj" using the constructor. We then print out the value of "x" using "System.out.println(newObj.x);", which will output "10" since that is the value set by the constructor. We then set the value of "x" to 555 and print it out again, which will output "555".
When we run this program, it will output the following to the console:
10
555
This program demonstrates how a constructor can be used to set initial values for member variables when an object is created using the "new" keyword. In this case, the constructor sets the initial value of "x" to 10.
public class Main {
int x;
String someString;
//This is Constructor - same name as Class name
public Main(int a, String b) {
x = a;
someString = b;
}
public static void main(String[] args) {
Main newObj = new Main(777, "hack The Planet");
System.out.println("X value: " + newObj.x + " String Value: " + newObj.someString);
}
}
Here's a block-by-block breakdown of the program:
public class Main {
int x;
String someString;
public Main(int a, String b) {
x = a;
someString = b;
}
In this block, we define a class named "Main" with two member variables "x" and "someString". We also define a constructor for this class that takes two parameters, "a" and "b", which are used to set the values of "x" and "someString", respectively.
public static void main(String[] args) {
Main newObj = new Main(777, "hack The Planet");
System.out.println("X value: " + newObj.x + " String Value: " + newObj.someString);
}
In this block, we define the main method which is the entry point for the program. Inside this method, we create an instance of the Main class named "newObj" using the constructor and passing the arguments 777 and "hack The Planet". We then print out the value of "x" and "someString" using "System.out.println()", which will output "X value: 777 String Value: hack The Planet".
When we run this program, it will output the following to the console:
X value: 777 String Value: hack The Planet
This program demonstrates how a constructor with parameters can be used to set initial values for member variables when an object is created using the "new" keyword with specific arguments. In this case, the constructor takes two arguments, an integer and a string, and sets the initial values of "x" and "someString" to the values passed as arguments.
Tkinter Introduction - Top Widget, Method, Button
First, let's make shure that our tkinter module is working ok with simple for loop that will spawn 5 instances of blank Tk window . ...
