Oop Using Java
Oop Using Java
Java Install
if you want to run Java on your own computer, follow the instructions below.
Some PCs might have Java already installed.
To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in
Command Prompt (cmd.exe):
C:\Users\Your Name>java -version
If Java is installed, you will see something like this (depending on version):
java version "22.0.0" 2024-08-21 LTS
Java(TM) SE Runtime Environment 22.9 (build 22.0.0+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 22.9 (build 22.0.0+13-LTS, mixed mode)
If you do not have Java installed on your computer, you can download it at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an
Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful
when managing larger collections of Java files.
Java Quickstart
In Java, every application begins with a class name, and that class must match the filename.
Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad).
The file should contain a "Hello World" message, which is written with the following code:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus
on how to run the code above.
Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the directory where
you saved your file, and type "javac Main.java":
C:\Users\Your Name>javac Main.java
This will compile your code. If there are no errors in the code, the command prompt will take you to the next
line. Now, type "java Main" to run the file:
C:\Users\Your Name>java Main
The output should read:
Hello World
Congratulations! You have written and executed your first Java program.
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to print "Hello
World" to the screen:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Example explained
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.
The name of the java file must match the class name. When saving the file, save it using the class name and add
".java" to the end of the filename. To run the example above on your computer, make sure that Java is properly
installed: Go to the Get Started Chapter for how to install Java. The output should be:
Hello World
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
}
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about how System, out and println() works. Just know that you need them together to print
stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Print Text
You learned from the previous chapter that you can use the println() method to output values or print text in Java:
Example
System.out.println("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each method:
Example
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
Double Quotes
Text must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);
Example
System.out.print("Hello World! ");
System.out.print("I will print on the same line.");
Note that we add an extra space (after "Hello World!" in the example above) for better readability.
In this tutorial, we will only use println() as it makes the code output easier to read.
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and methods from the class
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and
brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we can use this
to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
public class Main {
int x = 5;
Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
Run the Second.java file:
C:\Users\Your Name>java Second
And the output will be:
5
Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown below). It is actually
an attribute of the class. Or you could say that class attributes are variables within a class:
Example
Create a class called "Main" with two attributes: x and y:
public class Main {
int x = 5;
int y = 3;
}
Another term for class attributes is fields.
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax ( .):
The following example will create an object of the Main class, with the name myObj. We use the x attribute on the
object to print its value:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
public class Main {
int x;
Example
Change the value of x to 25:
public class Main {
int x = 10;
If you don't want the ability to override existing values, declare the attribute as final:
Example
public class Main {
final int x = 10;
Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one object, without affecting
the attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {
int x = 5;
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
myMethod() prints a text (the action), when it is called. To call a method, write the method's name followed by
two parentheses () and a semicolon;
Example
Inside main, call myMethod():
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
Example
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Example explained
1) We created a custom Main class with the class keyword.
2) We created the fullThrottle() and speed() methods in the Main class.
3) The fullThrottle() method and the speed() method will print out some text, when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that runs your program (any
code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program using the
name of the object (myCar), followed by a dot (.), followed by the name of the method
(fullThrottle(); and speed(200);). Notice that we add an int parameter of 200 inside the speed() method.
Remember that..
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon (;).
A class must have a matching filename (Main and Main.java).
Main.java
public class Main {
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}
Second.java
class Second {
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
Run the Second.java file:
C:\Users\Your Name>java Second
And the output will be:
The car is going as fast as it can!
Max speed is: 200
Java Constructors
Java Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes:
Example
Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
// Outputs 5
Note that the constructor name must match the class name, and it cannot have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for
you. However, then you are not able to set initial values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y).
When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
}
Example
public class Main {
int modelYear;
String modelName;
Example
public class Main {
int x; // Class variable x
Example
public class Main {
int modelYear;
String modelName;
car1.printInfo();
car2.printInfo();
}
}
Output:
2020 Corvette
1969 Mustang
Note: The call to this() must be the first statement inside the constructor.
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our examples:
public class Main
The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes,
methods and constructors.
We divide modifiers into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level, but provides other functionality
Access Modifiers
For classes, you can use either public or default:
Modifier Description
default The class is only accessible by classes in the same package. This is used when you don't specify a
modifier. You will learn more about packages in the Packages chapter
For attributes, methods and constructors, you can use the one of the following:
Modifier Description
default The code is only accessible in the same package. This is used when you don't specify a modifier.
You will learn more about packages in the Packages chapter
protected The code is accessible in the same package and subclasses. You will learn more about subclasses
and superclasses in the Inheritance chapter
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description
final The class cannot be inherited by other classes (You will learn more about inheritance in
the Inheritance chapter)
abstract The class cannot be used to create objects (To access an abstract class, it must be inherited from
another class. You will learn more about inheritance and abstraction in
the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:
Modifier Description
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a
body, for example abstract void run();. The body is provided by the subclass (inherited from). You
will learn more about inheritance and abstraction in the Inheritance and Abstraction chapters
transient Attributes and methods are skipped when serializing the object containing them
volatile The value of an attribute is not cached thread-locally, and is always read from the "main memory"
Final
If you don't want the ability to override existing attribute values, declare attributes as final:
Example
public class Main {
final int x = 10;
final double PI = 3.14;
Static
A static method means that it can be accessed without creating an object of the class, unlike public:
Example
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Abstract
An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass:
Example
// Code from filename: Main.java
// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you
must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of a private variable
Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Example explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to
refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class:
Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
If the variable was declared as public, we would expect the following output:
John
However, as we try to access a private variable, we get an error:
MyClass.java:4: error: name has private access in Person
myObj.name = "John";
^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors
Instead, we use the getName() and setName() methods to access and update the variable:
Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John"
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use
the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Example
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the
Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by
inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in
different ways.
For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of
Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the
pig oinks, and the cat meows, etc.):
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in
the Polymorphism chapter to an abstract class:
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Why And When To Use Abstract Classes and Methods?
To achieve security - hide certain details and only show the important details of an object.
Note: Abstraction can also be achieved with Interfaces,
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to
perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class. You will
learn more about objects and how to access methods through objects later in this tutorial.
void means that this method does not have a return value. You will learn more about return values later
in this chapter
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
Example
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
Example
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
When a parameter is passed to the method, it is called an argument. So, from the example above: fname is
a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must have the same number of
arguments as there are parameters, and the arguments must be passed in the same order.
Example
public class Main {
Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with
the implements keyword (instead of extends). The body of the interface method is provided by the "implement"
class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible
to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Java Errors
Even experienced Java developers make mistakes. The key is learning how to spot and fix them!
These pages cover common errors and helpful debugging tips to help you understand what's going wrong and
how to fix it.
Runtime Error Occurs while the program is running. Often causes crashes.
Logical Error Code runs but gives incorrect results. Hardest to find.
Example
int x = 5
System.out.println(x);
Result:
error: ';' expected
Tip: Java requires a semicolon at the end of every statement (int x = 5;).
2) Undeclared Variables
Example
System.out.println(myVar);
Result:
cannot find symbol
symbol: variable myVar
Tip: You must declare a variable before using it (int myVar = 50;).
3) Mismatched Types
Example
int x = "Hello";
Result:
incompatible types: String cannot be converted to int
Tip: Make sure the value matches the variable type (String x = "Hello";).
Example
int[] numbers = {1, 2, 3};
System.out.println(numbers[8]);
Result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 3
Logical Errors
Logical errors happen when the code runs, but the result is not what you thought:
Example:
int x = 10;
int y = 2;
int sum = x - y;
System.out.println("x + y = " + sum);
Result:
x+y=8
Expected Result: 12
Logical Error: The code mistakenly subtracts instead of adds.
Tip: Test your program with different inputs to catch logic flaws (try using x + y instead). This is part
of debugging, which you will learn more about in the next chapter.
Java Debugging
After learning about common errors, the next step is understanding how to debug your Java code - that is, how to
find and fix those errors effectively.
This page introduces simple debugging techniques that are useful for beginners and helpful even for experienced
developers.
What is Debugging?
Debugging is the process of identifying and fixing errors or bugs in your code.
It often involves:
Reading error messages
Tracing variable values step by step
Testing small pieces of code independently
Tip: Debugging is a skill that improves with practice. The more you debug, the better you get at spotting
problems quickly.
Example
int x = 10;
int y = 0;
Debugging Checklist
Read the full error message, it often tells you exactly what's wrong
Check if all variables are initialized before use
Print variable values to trace the problem
Watch for off-by-one errors in loops and arrays
Comment out sections of code to find bugs
Java Exceptions
As mentioned in the Errors chapter, different types of errors can occur while running a program - such as coding
mistakes, invalid input, or unexpected situations.
When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java
will throw an exception (throw an error).
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)
Note: ArrayIndexOutOfBoundsException occurs when you try to access an index number that does not exist.
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
ADVERTISEMENT
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
Java Files
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
Example
import java.io.File; // Import the File class
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the
file was successfully created, and false if the file already exists. Note that the method is enclosed in
a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):
Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file
we created in the example above. Note that when you are done writing to the file, you should close it with
the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous
chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
ADVERTISEMENT
Example
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output will be:
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader,
BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use
depends on the Java version you're working with and whether you need to read bytes or characters, and the size
of the file/lines etc.
Java Generics
Generics allow you to write classes, interfaces, and methods that work with different data types, without having
to specify the exact type in advance.
This makes your code more flexible, reusable, and type-safe.
T get() {
return value;
}
}
// Array of Integers
Integer[] numbers = {1, 2, 3};
Example Explained
<T> is a generic type parameter - it means the method can work with any type: String, Integer, Double,
etc.
The method printArray() takes an array of type T and prints every element.
When you call the method, Java figures out what T should be based on the argument you pass in.
This is useful when you want to write one method that works with multiple types, instead of repeating code for
each one.
Bounded Types
You can use the extends keyword to limit the types a generic class or method can accept.
For example, you can require that the type must be a subclass of Number:
class Stats<T extends Number> {
T[] nums;
// Constructor
Stats(T[] nums) {
this.nums = nums;
}
// Calculate average
double average() {
double sum = 0;
for (T num : nums) {
sum += num.doubleValue();
}
return sum / nums.length;
}
}
Example Explained
<T extends Number>: Restricts T to only work with numeric types like Integer, Double, or Float.
.doubleValue(): Converts any number to a double for calculation.
Works for any array of numbers as long as the elements are subclasses of Number.
Generic Collections
Java Collections like ArrayList and HashMap use generics internally:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
String fruit = list.get(0); // No need to cast
Summary
Generics make your code flexible and type-safe.
Use T or another letter to define a type placeholder.
Generics can be applied to classes, methods, and interfaces.
Use bounds to limit what types are allowed.