Java Basics Notes
Java Basics Notes
09:35
Tags:
java-basics
Introduction:
JVM:
The java virtual machine is an abstract computing machine that enables a computer to run java
programs. It acts as interpreter between java bytecode and the underlying operating system.
Role of JVM:
Features of JAVA:
[Link]
Class:
It is an user defined data type which represents the blueprint or template of an object.
consists of methods and data member
In java the main function is always public.
Logical Entity
Object:
Abstraction:
It is the process of hiding internal implementation details and showing only essential features of an
object to the user.
in java we can create abstracted class using the abstract keyword.
Encapsulation:
It is the process of binding data and methods together into a single unit, called a class. It also
involves protecting data by restricting direct access using access modifiers.
Advantages of encapsulation:
Inheritance:
Inheritance is the mechanism by which one class acquires the properties and methods of another
class. The existing class is called superclass, and new class is called subclass
Advantages of inheritance:
Code reusability.
Faster development.
Improved program structure,
Reduced memory usage.
class Vehicle{
void start(){
[Link]("Vehicle starts");
}
}
class car extends Vehicle{
void speed(){
[Link]("Car speed is 80km\h ");
}
}
Polymorphism:
Polymorphism means one interface with multiple implementations. It allows a single method or
object to behave differently in different situations.
Can be done by two ways-
1. Method Overloading (Compile time polymorphism): In method overloading, multiple methods
have the same name but different parameters.
Compiling process is when we are converting into the bytecode
can change return type, sequence of parameters, number of parameters.
2. Overriding (Runtime polymorphism): In method overriding, a subclass provides its own
implementations of a method defined in the superclass
Runtime is when the code is converted into machine code and is executing
Basic Syntax:
class first{
public static void main(String[] args) {
[Link]("Hello World");
}
}
Operators in java:
Arithmetic:
- Subtraction a - b Subtracts
* Multiplication a * b Multiplies
/ Division a / b Divides
% Modulus a % b Remainder
Assignment operators:
Operator Example Meaning
= a = 5 Assign value
+= a += 3 a = a + 3
-= a -= 2 a = a - 2
*= a *= 4 a = a * 4
/= a /= 2 a = a / 2
%= a %= 2 a = a % 2
== a == b Equal to
!= a != b Not equal
Logical Operators:
Memory types:
class xyz{
static String a = "hello";
int b = 10;
2. Heap:
3. Method area:
1. Static variables and methods will be stored here. a will be stored here.
2. the code/logic inside the function demo() and the main()function will be stored here as well
3. stack and heap can access the method area.
4. Stores the class structure information
5. Stores Constant pool: It is a special memory area in which java stores constants and reusable values
6. This area is shared among all threads
Variables:
A variable is a named memory location used to store data whose value can be changed during the
program execution.
Java is an static language meaning the data type of the variable must be mentioned before
initialising.
only \$ and _ can be used at the start of the variable name.
There are three types of variables: Memory will be allocated differently for all three variables
1. Instance variable: allocates memory from heap, object calling works on heap. Each object will
have a copy of the instance variable
2. Static: allocates memory from stack, variables which are accessible all over the class are
stored in stack
3. Method level or local variable:
fastest execution is of: local variables
Stored in the stack memory
Access is direct and fastest
Scope limited to the function/block $\rightarrow$ no lookup needed
declared inside the method declared inside the class declared inside the class
Memory location is stack memory location is heap memory location is Method area
we use static when we want to call a variable or a method without creating a new object for it.
Data Types:
Primitive:
Integers:
char
boolean
Non-Primitive:
1. String
2. Array
3. Class
4. interface
Difference between java and cpp:
Java CPP
Keywords:
Keywords are reserved words in java that have predefined meanings. These words are part of the java
language syntax and cannot be used as identifiers such as variable names, class names or method
names.
Java has 50+ keywords:
abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do,
double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int,
interface, long, native, new, package, private, protected, public, return, short, static, strictfp,
super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while, module,
requires, exports, opens, to, uses, provides, with, transitive, var, yield, record, sealed, non-sealed,
permits
[!NOTE] Const and goto are reserved but unused var, yield, record, sealed, non-sealed, permits are
contextual keywords true, false, nulls are literals not keywords
Constructors:
Cannot be overridden.
It is of three types:
1. Default constructor: This is the default constructor created when a class is created. Has body
2. Parameterised constructor: We can pass parameters by the help of this constructor.
3. Non-Parameterised constructor: When we dont have to pass any value. Doesn’t have body
Code example:
class student{
class student{
public String name;
public int roll;
class parameterConst{
public static void main(String[] args) {
student details = new student("Anuj", 12);
[Link]();
}
}
class student{
String name;
int roll;
long mob;
student(){
[Link]("Object has been created");
}
public void show(){
[Link]("The student name is "+name + " \nRoll number is " +
roll + " \nMobile number is " + mob );
[Link]("");
}
}
class nonparam{
public static void main(String[] args) {
student s1 = new student();
// [Link]();
student s2 = new student();
// [Link]();
student s3 = new student();
// [Link]();
student s4 = new student();
// [Link]();
student s5 = new student();
// [Link]();
}
}
Copy Constructor:
By the help of this constructor we can create a shallow copy of the object.
shallow copy means the data will be created at a new memory reference.
Hard copy means the memory location will be different for both the original and the copy
variable
class student{
String name;
static String testing = "hello";
int roll;
String add;
student(student s){
name = [Link];
roll = [Link];
add = [Link];
}
public void show(){
[Link](name);
[Link](roll);
[Link](add);
[Link]("");
}
}
class copyConst{
public static void main(String[] args) {
student s1 = new student("Anuj",1,"Moradabad");
[Link]();
student s2 = new student(s1);
[Link]();
[Link]([Link]);
}
}
JVM architecture:
[Link]
Class loader:
Execution Engine:
It will communicate with heap for the actual data inside the methods.
Type Conversion:
1. Implicit
2. Explicit
Implicit(Widening):
Example:
int a = 10;
double b = a;
[Link](b);
output:
10.0
Explicit(Type Casting):
Example:
double d = 2313123.21;
int i = (int)d;
import [Link];
class hasVoterId{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
if (age>=18) {
[Link]("Eligible for voting");
}
else{
[Link]("Not eligible");
}
[Link]();
}
}
Here curly braces after an if statement is options IF THERE IS ONLY ONE LINE OF CODE
class nestedIfElse {
public static void main(String[] args) {
boolean hasMoney = true;
int money = 300;
if (hasMoney) {
if(money>=300){
[Link]("Can go to the movie");
}
else{
[Link]("Paisa nahi hai");
}
}
}
}
Switch:
Switch statement is used when we want to execute a block of code based on the value of a single
variable
[Link]
Syntax and example for switch:
class Switch {
public static void main(String[] args) {
String day = "Sunday";
switch (day) {
case "Monday":
[Link]("Today is monday");
break;
case "Tuesday":
[Link]("Today is Tuesday");
break;
case "Wednesday":
[Link]("Today is wednesday");
break;
default:
[Link]("Enter a valid day");
} } }
Arrays in java:
2d arrays:
To define 2d arrays:
we use the syntax : int arr [] [] = {{1,2,3,4,5},{6,7,8,9,10}}
Defining an empty 2d array : int arr [] [] = new int[<size-of-rows>][]
[Link]
Repetition statements:
1. while
2. do while
3. for
While:
class While{
public static void main(String args []){
int i = 0;
while(i<11){
[Link](i);
i++;
}
}
}
DO-while:
the do block will run once at least once after that it will check conditions.
For:
class xyz{
public static void main(string [] args){
int arr[] = {1,2,34,5,5};
for(int i : arr){
[Link](i + " ");
}
}
}
If an array contains equal number or rows and columns then we can simply iterate it using 2 for loops
and using the array length.
For example:
Here both rows and columns are same so we can iterate it simply using two for loops.
In the case of jagged arrays or arrays where the number of rows and column will not be the same, We
have to use other methods to access:
Here we are using j < arr[i].length this helps in automatically adjusting the value of the condition
so it does not go out of bounds.
In this example when the value of i will be 0 so the value of arr[i].length will be 3.
When i = 1 then the value of arr[i].length will be 5.
Jumping statements:
There are two jumping statements
1. continue: Used when we have to skip a particular iteration
2. break: Used to completely exit from a block and stop its execution
Example for break and continue:
for(int i = 0; i<11;i++){
if(i==9){
break;
}
if(i==7){
continue;
}
[Link](i + " ");
}
Wrapper class:
Autoboxing will be used to convert normal data type into wrapper classes.
when we have to convert wrapper classes into primitive data types we use unboxing.
Collection framework:
Vector:
Stores same datatype
syntax = Vector<String> vc = new Vector<>();
Types of Inheritance:
Single level:
class Vehicle{
int a = 10;
void engine(){
[Link]("Engine is working");
}
}
class SingleInheritance{
public static void main(String args[]){
Car o1 = new Car();
[Link](o1.a);
[Link]();
[Link]();
}
}
Multi Level:
class University{
final static String name = "GBU";
void course(){
[Link]("Multiple courses running in the university");
}
}
void dept(){
[Link]("Multiple schools are running in the department");
}
Multiple level:
Hybrid:
Hierarchy:
only one parent class but multiple number of child are possible
Requirement of inheritance:
1. code re usability
class B extends A{
@Override
void show(){
[Link]("Child class");
}
}
Super Keyword:
It is used when we have to call the variables, methods and constructor from the parent class
We can only call the constructor of a parent class but we cannot override it.
Constructors belong to a particular class and hence cannot be overridden
class A{
A(){
[Link]("Constructor of parent class");
}
int x = 20;
void show(){
[Link]("Parent class");
}
}
class B extends A{
B(){
[Link]("Constructor of child class");
}
int x = 30;
@Override
void show(){
[Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}
Inhibiting Inheritance:
To stop a child class from inheriting the parent class we can use the final keyword.
final keyword stops the parent class from getting inherited
final class A{
A(){
[Link]("Constructor of parent class");
}
int x = 20;
void show(){
[Link]("Parent class");
}
}
class B extends A{
B(){
[Link]("Constructor of child class");
}
int x = 30;
@Override
void show(){
[Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}
}
}
It is the process where a method is decided at runtime based on the object’s actual type. Rather than
reference type
Dispatcher is used to connect the request
output depends on the constructor which is being used while creating the object
class A{
// A(){
// [Link]("Constructor of parent class");
// }
int x = 20;
void show(){
[Link]("Parent class");
}
}
class B extends A{
// B(){
// [Link]("Constructor of child class");
// }
int x = 30;
@Override
void show(){
// [Link]();
[Link]("Child class");
}
void printX(){
[Link]("The value of x is: " + super.x);
}
}
Modifiers:
A modifiers is the statement which controls the accessibility, behavior and properties
They are of two types:
1. Access modifier: Used to control accessibility of the class, variable and methods
public: can be accessed from the same class, subclass and can be accessed in same
package can be accessed in different package
protected can be accessed from the same class, subclass, can be accessed in same
package but not in different package
private: can be accessed from the same class. Cannot be accessed in subclass and
same package and different package
default: can be accessed from the same class, subclass and cannot be accessed in same
package and different package
2. Non-access modifier: Used to decide the behavior or control the properties of class, variable
and method
static: used for making the access from object level to class level
If we use final with a class then no other can inherit that class
if we use final in a method within a class then no other class inheriting it will be
able to override it
blank final variable: A final variable that is not initialized at the time of declaration is
known as blank final variable. It can be initialized only in constructor
static blank final variable: A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can only be initialized in static
block
In class: an abstract class can contain both abstract and non abstracted methods
In method: methods which are incomplete are by default abstract. Abstract method
will only be used in abstract class
For ex: public void func();
This is an incomplete method
Abstraction:
Abstracted Class:
void Salary(){
int sal = 50000;
[Link]("Salary is: " + sal);
}
Interface:
An interface is a blueprint of a class which holds only final variable and abstract method
can contain final and static variable by default without using any keyword
only abstract method are allowed by default without any keyword
use interface keyword to create interface or abstract method created without any keyword
Object cannot be created of interface
Interface can only be used after implementing
concrete methods can be created using the default keyword
Packages:
Random numbers:
import [Link];
class RandomNumbers{
public static void main(String[] args) {
Random rn = new Random();
int num = [Link](100); // this is the range 0-100
[Link]("Random Numbers: " + " " + num);
}
}
String:
Collection of characters, enclosed in double quotes
String is a class that belongs to lang package
lang package is imported automatically
String s1 = "Anuj";
class Strings {
public static void main(String[] args) {
String s1 = "Hello "; // address of memory 231324
[Link](s1);
String s2 = "World";
s1 = "testing"; // address of memory 2323124
[Link](s1);
[Link](s1 + s2);
}
Strings are immutable, each time a new object is created whenever a string is mutated
This is called traditional string
String methods:
1. length()
2. toLowerCase()
3. toUpperCase()
4. trim()
5. SubString()
6. indexof("H")
In the case of String once the object is created it cannot be mutated. Any modification on that object
will result in a new object, which increases memory usage
String buffer:
String builder:
Stringbuilder is faster due to there being no locking overhead since its not thread safe
Multithreading:
Multithreading is a java feature that allows a program to execute multiple threads concurrently with a
single process. It is used to improve the performance, responsiveness and efficient utilization of the
CPU resources
Thread is the smallest unit of execution in a program. Each thread runs independently but shares the
same memory space of the process
Advantages of Multithreading:
Applications:
1. Web servers
2. Gaming applications
3. Multimedia processing
4. Real-time Systems
Creating a thread:
In this method we extend the Thread class and overrides the run() method.
Thread lifecycle:
Stopping a thread:
class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
try {
[Link](3000); // Main thread waits 3 sec
} catch(Exception e) {}
Thread Exception:
try {
[Link](1000);
} catch (Exception e) {}
JDBC:
It stands for java database connectivity.
It is an api in java that allows your program to connect to a database.
It is the part of java standard edition
Java standard edition
java enterprise edition: For web apps
Features of JDBC:
1. Platform independent
2. Supports multiple database
3. Provides standard interface for the database access
Drivers
The component that actually enable communication between your java program and a specific
database
A JDBC driver is a software module that implements the JDBC API and allows java application to
connect to a database
JDBC uses 4 types of drivers:
1. Type-1 Bridge
2. Type-2 Native
3. Network
4. Thin
Type-1 Bridge:
Disadvantage:
1. Performance degrade
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Returns in C or C++
The network protocol driver uses middleware that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java - Returns in java
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language
Architecture:
import [Link];
import [Link];
import [Link];
import [Link];
class question120 {
try {
[Link]("[Link]");
while ([Link]()) {
[Link]([Link]("Cid") + " " + [Link]("Cname")
+ " " + [Link]("City"));
}
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
2. the Just in time compiler is a component of JVM that improves the performance of Java
applications by converting bytecode into native machine code during runtime.↩