Thank you for exploring my Java repository on GitHub! Feel free to follow for updates and consider contributing to my open-source projects.Github Profile
Week 01 Code
-
Hello World code
-
Data types in Java code
-
Get Value From User code
-
If Else Condition code
-
Switch Statement code
-
For loop in java code
week2 updated soon
week3 Code
week5 Code
week7 Code
Java was created by James Gosling, Mike Sheridan, and Patrick Naughton at Sun Microsystems in 1991. Java was officially released by Sun Microsystems in 1995.
Bytecode in Java refers to the intermediate, platform-independent code generated by the Java compiler from the source code. The bytecode is a set of instructions that is designed to be executed by the Java Virtual Machine (JVM).
- Platform Independence
- Object-Oriented
- Simple and Easy to Learn
- Robust and Secure
- Multi-threaded
- Distributed Computing
- Dynamic and Extensible
- High Performance
- Rich Standard Library
- Community Support
Java | C++ |
---|---|
Platform Independence | Platform-Dependent Compilation |
Automatic Memory Management | Manual Memory Management |
Object-Oriented | Procedural and Object-Oriented |
Multiple Inheritance (via interfaces) | Multiple Inheritance Directly |
Compiled to Bytecode (JVM) | Compiled Directly to Machine Code |
Aspect | JVM (Java Virtual Machine) | JDK (Java Development Kit) | JRE (Java Runtime Environment) |
---|---|---|---|
Functionality | Executes Java bytecode | Full development kit with tools | Runtime environment for Java apps |
Components | Virtual Machine | Compiler, JRE, Development Tools | JVM, Class Libraries |
Purpose | Provides runtime environment | Comprehensive development kit | Minimum requirements for runtime |
Key Role | Translates bytecode, memory management | Compilation, development, debugging | Executes bytecode, provides libraries |
InheritanceUsage** | Installed on host machine | Used by developers for Java development | End-users need it to run Java apps |
A class in Java is a blueprint or template for creating objects. It serves as a prototype that defines the attributes (fields) and behaviors (methods) that objects instantiated from the class will possess.
In Java, a class is defined using the class
keyword, followed by the class name. Here is an example of a Student
class:
public class Student {
// Attributes of the Student
String name;
int age;
String studentAridNo;
// Behaviors
void study() {
// Implementation
}
void attendClass() {
// Implementation
}
}
In the example above, the Student
class has attributes (name
, age
, and studentAridNo
) that represent properties of a student, and it has behaviors (study
and attendClass
) that represent actions a student can perform.
An object is an instance of a class. It is a concrete realization of the blueprint defined by the class. Objects have state (values for attributes) and behavior (execution of methods).
Objects are created from a class using the new
keyword. For example, creating an instance of the Student
class:
Student myStudent = new Student();
myStudent.name = "John Doe";
myStudent.age = 20;
myStudent.studentAridNo = "S12345";
myStudent.study();
In this example, myStudent
is an object of the Student
class. It has specific values for the attributes name
, age
, and studentId
, and it can invoke the methods study
and attendClass
defined in the Student
class.
Encapsulation in Java is a fundamental object-oriented programming concept that involves bundling the data (attributes) and methods (behaviors) that operate on the data within a single unit, known as a class. The primary goal of encapsulation is to restrict direct access to some of an object's components, promoting data hiding, and enhancing security and maintainability.
In Java, encapsulation is often achieved by using access modifiers
Example Consider the following Student
class as an example of encapsulation:
public class Student {
// Private attributes
private String name;
private int age;
private String studentId;
// Public methods for accessing and modifying private attributes
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public int getAge() {
return age;
}
public void setAge(int newAge) {
// Validate age if needed
age = newAge;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String newStudentId) {
// Validate student ID if needed
studentId = newStudentId;
}
// Other public methods
public void study() {
// Implementation
}
public void attendClass() {
// Implementation
}
}
In this example:
- The
name
,age
, andstudentId
attributes are marked as private, making them accessible only within theStudent
class. - Public methods (
getName
,setName
,getAge
,setAge
,getStudentId
,setStudentId
,study
,attendClass
) are provided to access and modify the private attributes. These methods can include additional logic or validation if needed.
--
Access modifiers in Java control the visibility of classes, methods, and fields:
- Public: Accessible from any class or package.
- Private: Accessible only within the same class.
- Protected: Accessible within the same package or by subclasses.
- Default (Package-Private): Accessible within the same package but not from outside.
Access Modifier | Class | Interface | Public |
---|---|---|---|
Public | Yes | Yes | Yes |
Private | Yes | No | No |
Protected | Yes | No | No |
Default | Yes | No | No |
Inheritance in Java is a mechanism where a class (subclass or derived class) inherits properties and behaviors from another class (superclass or base class).
Example Consider the following Person
class and its subclass Student
:
public class Person {
String name;
int age;
void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Student extends Person {
String studentId;
void study() {
System.out.println("Studying...");
}
// Overriding method from
void displayDetails() {
super.displayDetails(); // Invoking superclass method
System.out.println("Student ID: " + studentId);
}
}
In this example, the Student
class inherits the attributes (name
and age
) and behavior (displayDetails()
) from the Person
class. It also introduces its own attribute (studentId
) and behavior (study()
).
The super
keyword in Java is used to refer to the immediate parent class. It can be used to access the fields, methods, and constructors of the superclass.
public class Student extends Person {
String studentId;
// Overriding method from
void displayDetails() {
super.displayDetails(); // Invoking superclass method
System.out.println("Student ID: " + studentId);
}
void study() {
System.out.println("Studying...");
super.displayDetails(); // Invoking superclass method within subclass
}
}
In the Student
class, super.displayDetails()
is used to invoke the displayDetails()
method of the superclass (Person
).
Abstraction in Java is the process of hiding the implementation details and showing only the essential features of an object. It allows the creation of abstract classes and interfaces. code
An interface in Java is a collection of abstract methods. Interfaces provide a way to achieve abstraction and support multiple inheritance.code
Implementation in Java refers to the process of providing concrete code for the abstract methods defined in an interface or an abstract class. code
The extends
keyword is used to establish an inheritance relationship. It allows a class to inherit attributes and behaviors from another class. code
Multiple inheritance in Java refers to a class or interface inheriting from more than one class or interface. Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces, achieving a form of multiple inheritance. code
abstract class Bank {
String bankName;
Bank(String name) {
this.bankName = name;
}
abstract void displayDetails(); // Abstract method
}
class BankAccounts extends Bank {
BankAccounts(String name) {
super(name);
}
@Override
void displayDetails() {
System.out.println("Bank Name: " + bankName);
System.out.println("Type: Savings and Current Accounts");
}
}
interface Loan {
void provideLoan(); // Abstract method in the interface
}
class LoanImplementation implements Loan {
@Override
public void provideLoan() {
System.out.println("Loan provided successfully.");
}
}
class Customer extends BankAccounts implements Loan {
Customer(String bankName) {
super(bankName);
}
// Implementing the abstract method from the Bank class
@Override
void displayDetails() {
super.displayDetails();
System.out.println("Customer Information: Regular Account Holder");
}
// Implementing the method from the Loan interface
@Override
public void provideLoan() {
System.out.println("Customer eligible for a loan.");
}
}
public class Main {
public static void main(String[] args) {
// Example of abstraction and class
BankAccounts myBank = new BankAccounts("XYZ Bank");
myBank.displayDetails();
System.out.println("---------------");
// Example of interface and implementation
LoanImplementation loanProvider = new LoanImplementation();
loanProvider.provideLoan();
System.out.println("---------------");
// Example of multiple inheritance
Customer customer1 = new Customer("ABC Bank");
customer1.displayDetails();
customer1.provideLoan();
}
}
it is use to handle the file
File file = new File("FileName.txt");
It create a new file.
File file = new File("FileName.txt");
try{
file.createNewFile();
}catch(IOException e){
//Error which you want to print
}
It is used to delete the file.
File file = new File("FileName.txt");
try{
file.delete();
}catch(IOException e){
//Error which you want to print
}
It return boolean type value .
File file = new File("FileName.txt");
if(file.exists()){
//code
}else{
//code
}
It return the space of our file in bytes if you want to convert it in kb then divide it with 1024 .
File file = new File("FileName.txt");
long size = file.getTotalSpace();
//now it return size of file in bytes
It return the path of the our file .
File file = new File("FileName.txt");
String PathofFile = file.getAbsolutePath();
Returns the absolute form of this abstract pathname..
File file = new File("FileName.txt");
String filePath = file.getAbsoluteFile();
Returns the length of file in 'long' type.
File file = new File("FileName.txt");
long fileLength = file.length();
The object of FileWriter is used to write the file
.
This method is used to append the file.
FileWriter fw = new FileWriter("FileName.txt", true);
//This true keyword is use to append the file
This is use to write the file.
try {
FileWriter fw = new FileWriter("fileName.txt", true);
//get value from user
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
fw.write(" " + str);
fw.close();
} catch (IOException e) {
//exception handling
e.printStackTrace();
}
It is used to close the file
try {
FileWriter fw = new FileWriter("fileName.txt", true);
//get value from user
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
fw.write(" " + str);
//close is used to close the file
fw.close();
} catch (IOException e) {
//exception handling
e.printStackTrace();
}
It is used to read the file
try {
FileReader fr = new FileReader("text.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
This method is same like other read() method. it read file line by line.
try{
BufferedReader br = new BufferedReader(new FileReader("FileName.txt" , true));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
Close the file.
try{
BufferedReader br = new BufferedReader(new FileReader("FileName.txt" , true));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
//this is used to close the file best practice
br.close();
}catch(IOException e){
e.printStackTrace();
}
This method is used to write the file.
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName,true));
//here get input from user using scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter any String");
String input = sc.nextLine();
bw.write(input );
bw.close();
}catch(IOException e){
e.printStackTrace();
}
Close the file.
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName,true));
//here get input from user using scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter any String");
String input = sc.nextLine();
bw.write(input );
//this method is used to close the file
bw.close();
}catch(IOException e){
e.printStackTrace();
}