Welcome to the Java Basics repository! This repository contains all the foundational concepts you need to get started with Java programming.
- Introduction
- Data Types
- Setup and Environment
- Operations and Expressions
- String Class and Printing
- Conditional Statement
- Loops
- Arrays
- Methods
- Principles of OPP
- Inheritance
- Abstract class
- Interface
- Inner classes
- Static and final
- Exception Handling
This section provides you with how to take the input and how to print the output on the console.
An overview of the different data types in Java, including primitives (int, char, boolean, etc.) and reference types (arrays, strings, etc.).
Overview of the JDK, JRE, and JVM.
- Arithmetic operator and expressions
- Increment / decrement operators and expressions
- Bitwise operators
To understand about the String objects, methods of the String class, and regular expressions.
Understand the various control structures in Java such as if-else statements, switch cases, loops (for, while, do-while), and break/continue statements.
- Loops are repeating statements.
- There are four types of loops.
- In loops, the steps are repeated till the given condition is reached.
- The steps are executed if the condition is true.
- The condition is checked first and the process is followed.
- It is a pre-tested loop.
- If the condition is false, then the process is never executed.
- First, the process is followed and then the condition is checked.
- It is a post-tested loop.
- If the condition is false, then the process is executed at least once.
- Both loops work for the same purpose.
- But do-while loop is more suitable than while loop.
- For loop is a counter-controlled loop.
- It is the most frequently used loop.
- Syntax: for(initialization; condition; updation)
- For loop inside a for loop is an example of a nested loop.
- The above one is used commonly.
- The working of the body is more than one dimensional.
- Nesting of any two types of loops can be done.
- Nested for loop may create the dimensional loops.
Example program for nested for loop.
- Array is a collection of similar data elements.
- In Java, the array size is given after creating the new object.
- As
int A[] = new int[x]; - Where
A[]is the reference andint[x]is the object. - Where the object is created in the heap.
- And the reference is either in the stack or heap.
- Location of characters in an array can be accessed by using their index.
- Every array in Java has length as its property which can be accessed by using
array-name.length. - For loops are most frequently used for arrays.
- Using for loop all the elements in the arrays can be accessed.
- Java has introduced for each loop for accessing arrays in version Java 1.5 or Java 5.
- Two-dimensional arrays are suitable for matrices and tabular forms.
- Syntax for creating a two-dimensional array in Java is:
int A[][] = new int[3][4]; - It is also known as array of arrays or collection of arrays.
- The object is created in heap but the reference may or may not be created in heap.
Array_name.lengthgives the number of rows.Array_name[index].lengthgives the number of columns.
- Methods are members of classes which provide functionality for classes.
- We can write our own methods in the classes.
- The functions performing on the data are known as methods.
- When a method returns a value then the method itself takes the value.
- A method will have its own copy of variable.
- To call a method from the main method it needs to be made static.
- When the method is called the value of actual parameters are copied in formal parameters which is the only parameter passing method in Java.
- The address of the object in formal and actual parameters is the same.
- String cannot be modified as it is immutable.
- A method can also return an object.
- Whoever is calling a method is called a caller or a method call.
- The method which is called by a caller is known as the called method.
- The parameters/arguments passed in the calling method are called actual parameters.
- The parameters of a called method are called formal parameters.
- Formal parameters are nothing but input into a method where the return type is known as output to a method.
- The contents of actual parameters are copied in formal parameters which is the only method of parameter passing in Java.
- Passing of objects also follows the same method.
- Parameter passing for primitive data types the values are copied in formal parameters, whereas in parameter passing of objects the reference of the object ID is copied in formal parameters.
- In short, the primitive data types are passed by value and the objects are passed by reference.
- Method overloading means writing more than one method having the same names but different parameter lists or data types.
- Compiler will call the corresponding method depending upon the parameter list.
- It is nothing but writing a single method which can run for a number of parameters of the same data types.
- For example:
void show(int ...x) - Where
...represents the variable arguments. - It is similar to ellipsis in C/C++.
- The parameters passed are converted into an array.
- The parameters can be directly passed using an anonymous array.
- Variable argument should always be the last parameter.
Printfis based on variable arguments in version 1.7 Java.
-
Java programs can utilize command line arguments.
-
DOS file is used for command line arguments.
-
There are different commands like:
cls: to clear the screen.dir: to display the contents of the disk.cd windows: to change the directory.
-
C:\Windows> dir v*.* -
The above is a command line in which
diris the command andv*.*is an argument.
- Abstraction means hiding internal details and showing the required things
- For Example Consider a man driving a car, while driving he focus on using of steering, gear, accelerator etc. He does not require to know the inner mechanism of the car.
- Encapsulation is the process of grouping data in a single section.
- For Example Complete television is single box where all the mechanism are hidden inside the box all are capsuled
- Inheritance means designing an object or a class by re-using the properties of the existing class and object.
- Inheritance is same as specialization.
- For Example A old style television (idiot box) is transformed with extra features into slim and smart television where it re-used the properties of old television.
- Polymorphism is a concept in which we can execute a single operation in different ways.
- polymorphism is same as generalization.
- Object is deEined in terms of its properties and behaviour.
- Operation of behaviours will affect the properties.
- Anything in the world can be deEined in the terms of properties and behaviour.
- For a single class wee can have many objects.
- Multiple number of objects can be created by one single class
-
Usually data is hidden and the operations are made visible and operations or methods are performed over the data
-
For example Actual operation of the television is performed in the circuitry which is done by pressing a button.so the circuitry is data and operations are methods where the data is hidden inside the box.
- Read and writable property.
- getLength() method will allow us to read the property and setLength() method will allow us to write the property .
- Read only property.
- When there is no modiEication to the property then read only property is used.
- Write only property.
- Only set method is used for writing the property where no get method is used.
- A method is required for Initialization of properties at the time of construction of an object, this method is known as constructor.
- Constructor is a method of class called when an object is created.
- Every class will have a default constructor provided by java compiler.
- Constructor will not have any return type.
- There are two types of constructors
-
- parameterized
-
- Non-parameterized.
-
- Non-parameterized constructors is a replacement for default constructors.
- Constructors can be overloaded.
-Common thing in Generalisation and Specialisation is they are in the form of Hierarchy -It is Like a Parent Class and Child Class(or)Base Class and Derived Class(or) Super Class and Sub Class.
- In Generalisation group of classes are referred with Super class with single name.
- Generalisation means Bottom Up.
- In Generalisation A Super Class Is made by Grouping Multiple Sub Classes.
- Generalisation is achieved using Interfaces.
- In Specialisation a new Sub Class is Generated by borrowing the features of existing concrete class and adding new features to it.
- -Specialisation means Top Down.
- In specialisation a new Class is derived from an existing Super Class.
- Specialisation is achieved using Inheritance.
- Inheritance is the process of acquiring features of an existing Class into a New Class.
- A Class will have Properties and Method.
- Constructors are the methods of class which are automatically called when an object is created.
- Constructors are executed from Top to Bottom Class.
- To make the child class object Pirstly the parent class constructor must be created
- RedePining the method of the Super Class in the Sub Class.
- Method will be called depending on the object.
- Method overriding is achieved in Inheritance.
- When the sub class object is called then the display method inherited from the super class is shadowed and the sub class display method is executed.
- Super Class method never be called upon the object of Sub Class.
- In the given example program the super class have a method called display which is saying hello and another class sub class is taken where it inherits the display method from super class and redePines the method.
- When a super class reference holding the object of sub class and overridden method is called then method of object will be called it is Dynamic Method Dispatch.
- It is useful for achieving Runtime Polymorphism
- Super Class reference can have Object of Sub Class but a Sub Class reference cannot have Super Class Object.
- A Super Class Reference can hold the Object of Sub Class but it can call only those methods which are present in super class.
- Methods are called depending on the object not the reference then the overridden object is called it is Runtime Polymorphism.
- Dynamic Method Dispatch means calling a Method dynamically because program make the decision at runtime for which object to be called.
- Signature must be same in method overriding.
- If the method name is different the method is not overridden but it is overloaded.
- Argument may be different but the parameter must be same.
- Return type must be same, if it is not same then the method is neither overridden nor overloaded.
- Final and static methods cannot be overridden.
- Method can be overridden with same or lenient (public, protected) access speciPiers but the stricter(private) access speciPiers cannot be used in sub class.
- Polymorphism is one of the principles of Object-oriented-programming, polymorphism means one name different actions.
- Poly means ’many’, morphism means ’forms’.
- Polymorphism is achieved using method overriding and overloading.
- In method overloading access speciPiers, return types are same but number of parameters or type of parameters are different.
- In overloading number or type of argument will decides which method is to be called.
- Overloading is achieved in same class whereas overriding is achieved in inheritance.
- In method overriding signature is same but in overloading signatures must be different.
- Method calls are different in overriding it depends on object.
- overloading is used for compile time polymorphism.
- The abstractclass branch covers the concept of abstract classes in Java. Abstract classes are classes that cannot be instantiated on their own and are meant to be subclassed. They can contain abstract methods (without implementation) as well as concrete methods (with implementation).
- Abstract classes are declared with the
abstractkeyword. - They can have both abstract and non-abstract methods.
- They are used to provide a base for subclasses to build upon.
The interface branch focuses on interfaces in Java. Interfaces are abstract types that allow you to define methods that a class must implement, without providing the method implementation.
- Interfaces are declared with the
interfacekeyword. - They can only contain method declarations and constants (until Java 8, which allows default and static methods).
- A class can implement multiple interfaces.
-The staticfinal branch explores the usage of the static and final keywords in Java. These keywords are used to define constants and class-level fields/methods.
statickeyword: Used for class-level fields and methods that are shared across all instances.finalkeyword: Used to declare constants and prevent inheritance or method overriding.static finalfields are constants, shared among all instances, and cannot be changed.
- The
innerclassbranch dives into inner classes in Java. Inner classes are defined within another class and have access to the members of the outer class.
- Inner classes can be static or non-static.
- Non-static inner classes can access outer class members directly.
- Static inner classes (nested classes) do not have access to the instance variables of the outer class.
- Exceptions are Runtime Errors.
- There are various types of errors:
- Syntax Error
- Logical Error
- Runtime Error
- Syntax and Logical errors are faced by programmers, while runtime errors are faced by users.
- Syntax errors include spelling or grammatical mistakes, such as using an uninitialized variable, using an undefined variable, or missing a semicolon.
- Syntax errors can be removed with the help of a compiler.
- A logical error is a bug in the program that causes it to operate incorrectly, such as missing parentheses in a calculation.
- Logical errors can be removed with the help of a debugger.
- Mishandling of a program causes runtime errors.
- Causes of runtime errors include bad input or the unavailability of resources.
- A major problem with runtime errors is that the program will crash.
- Exception handling is the process of responding to runtime errors.
- The
trystatement allows you to define a block of code to be tested for errors while it is being executed. - The
catchstatement allows you to define a block of code to be executed if an error occurs in thetryblock. - The
tryandcatchkeywords come in pairs. - A
tryblock can have multiplecatchblocks. Tryandcatchblocks can be nested.- When a
try-catchblock is present in anothertryblock, it is called a nestedtry-catchblock.
- Object is the base class for all Java classes.
- Exception is the parent class for all exceptions.
- ClassNotFoundException: Raised when an object is used, but the class is not found.
- IOException: Occurs when there is an issue accessing input/output, usually related to files. A common example is
FileNotFoundException, which is thrown when a file is not found or is corrupted. - InterruptedException: Related to multithreading; this exception is thrown if a thread is interrupted or stops abnormally.
- NumberFormatException: Thrown when a string that is expected to be a number is not properly formatted as such.
- RuntimeExceptions: Includes exceptions like
ArithmeticException,IndexOutOfBoundException, andNullPointerException.
- Checked exceptions must be handled using
tryandcatchblocks. The Java compiler enforces handling these exceptions. - Unchecked exceptions do not need to be explicitly handled. Only
RuntimeExceptionsfall under this category.
string getMessage(): Returns a string containing a message about the exception.string toString(): Also returns a string with a message about the exception. While both methods serve a similar purpose, they may be used in different contexts.
-
throw:
- The
throwkeyword is used to logically throw an exception. - Only one exception can be thrown at a time using the
throwkeyword. - It is used within the method.
- It is followed by an instance of an exception.
- The
-
throws:
- The
throwskeyword is used for declaring that a method may throw an exception. throwsis written in the method's signature.
- The
-
Resources in a Program:
- All external elements that a program interacts with are considered resources, including files, network connections, and more.
- The heap is also considered a resource for a program.
- A program should acquire the necessary resources when needed and release them when they are no longer required.
- In Java, objects are created in the heap memory using the
newkeyword. - Java's garbage collector automatically deallocates objects in the heap memory when they are no longer in use.
-
Finally Keyword:
- The
finallykeyword is used in association with atry/catchblock. - The
finallyblock is executed whether an exception occurs or not. - Resources should be closed within the
finallyblock to ensure they are released properly.
- The
-
Try-with-Resources Statement:
- The try-with-resources statement is a
trystatement that declares one or more resources. - It ensures that each resource is closed automatically at the end of the statement, eliminating the need for an explicit
finallyblock to close resources.
- The try-with-resources statement is a
Note: This documentation is from the Java-study-note branch.