Basic conception

  • First, every line of the code must be in the class.

  • Second, a java file can have more than one class. However, there can only be one public class per java file and the name of public class must be the same name as its file name.

Variables

A class can contain any of the following variable types.

  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
  • float

    The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an “f”.

  • static

    In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects.

    • This instance method cannot override the static method from A

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      class A{
      static int m;
      static void f() {
      m=20;
      }
      }

      class B extends A{
      void f() { //wrong
      m=222;
      }
      }
  • Non-Primitive Data Types

    Non-primitive data types are called reference types because they refer to objects.

    • Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
    • Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
    • A primitive type has always a value, while non-primitive types can be null.
    • A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
    • The size of a primitive type depends on the data type, while non-primitive types have all the same size.
  • Type Casting

    In Java, there are two types of casting:

    • Widening Casting (automatically) - converting a smaller type to a larger type size
      byte -> short -> char -> int -> long -> float -> double

    • Narrowing Casting (manually) - converting a larger type to a smaller size type
      double -> float -> long -> int -> char -> short -> byte

    1
    2
    3
    4
    float n=1.1f;
    double m =1.1;
    m=n; //Widening Casting(automatically)
    n=(float)m; //Narrowing Casting(manually)
  • special character

    The backslash (\) escape character turns special characters into string characters:

    Escape character Result Description
    \' Single quote
    \" Double quote
    \\ \ Backslash
  • Loop the Array

    1
    2
    3
    4
    5
    6
    7
    8
    for (type variable : arrayname) {
    ...
    }

    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    for (String i : cars) {
    System.out.println(i);
    }
  • constructor

    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.

Overload the method

After we overloaded a method, there will be two method that have the same name but have the differences that are the numbers or the type of the parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A{
float computer(float x, float y) {
return x+y;
}
public int g(int x, int y) {
return x+y;
}
}

class B extends A{
float computer(float x, float y,double z) {//overload
return x*y;
}
}

Packages

A package in Java is used to group related classes. Think of it as a folder in a file directory.

We use packages to avoid name conflicts.

1
2
import package.name.Class;   // Import a single class
import package.name.*; // Import the whole package

Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

To inherit from a class, use the extends keyword.

We can inherit attributes and methods from one class to another

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

class Calculation{
int z;
public void addition(int x, int y) {
z=x+y;
System.out.println("The sum of the given number: "+z);
}

public void subtraction(int x, int y) {
z=x-y;
System.out.println("The difference between the given number: "+z);
}
}

public class My_Calculation extends Calculation{

public void multiplication(int x, int y) {
z=x*y;
System.out.println("The product of the given number: "+z);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=20, b=10;
My_Calculation c=new My_Calculation();
c.addition(a, b);
c.subtraction(a, b);
c.multiplication(a, b);

}

}
  • If we create a reference variable to the superclass, it can only access the members of the superclass, so to access the members of both classes it is recommend to always create reference variables to the subclass.

Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. (How do we invoke it? we just use the super keyword)

The super keyword

The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.

  • It is used to differentiate the members of superclass from the members of subclass, if they have same names.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    class Super_class{
    int num=20;
    public void display() {
    System.out.println("This is the display method of the super class");
    }
    }

    public class Sub_class extends Super_class{
    int num=10;
    public void display() {
    System.out.println("This is the display method of the sub class");
    }

    public void method() {
    Sub_class sub=new Sub_class();
    sub.display();
    super.display();
    System.out.println("value of the variable named num in sub class: "+num);
    System.out.println("value of the variable named num in super class: "+ super.num);
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Sub_class obj=new Sub_class();
    obj.method();

    }
    }
  • It is used to invoke the superclass constructor from subclass.

    If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword

    As the following example, we use super(val) to call the parameterized constructor.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    class SuperClass {
    int age;

    SuperClass(int age){
    this.age=age;
    }

    public void getAge() {
    System.out.println("The value of varible named age in the super class name is "+ age);
    }
    }

    public class SubClass extends SuperClass{

    SubClass(int age) {
    super(age);
    // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    SubClass s=new SubClass(19);
    s.getAge();
    }
    }

instanceof

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal.

(obj name) instanceof (class name)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface Animal{

}

class Mammal implements Animal{

}

public class Dog extends Mammal{

public static void main(String[] args) {
// TODO Auto-generated method stub
Mammal m=new Mammal();
Dog d=new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}

}

Output

1
2
3
true
true
true

Override the method

After we override, the method in the subclass covers the method in the superclass that has the same name. Note that the method in the subclass must have the same name, the same numbers and same type of parameters as the superclass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A{
float computer(float x, float y) {
return x+y;
}
public int g(int x, int y) {
return x+y;
}
}

class B extends A{
float computer(float x, float y) {
return x*y;
}
}
  • Even though b is a type of Animal it runs the move method in the Dog class

    In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.

    As an example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    class Animal {
    public void move() {
    System.out.println("Animals can move");
    }
    }

    class Dog extends Animal {
    public void move() {
    System.out.println("Dogs can walk and run");
    }
    }

    public class T {

    public static void main(String args[]) {
    Animal a = new Animal(); // Animal reference and object
    Animal b = new Dog(); // Animal reference but Dog object

    a.move(); // runs the method in Animal class
    b.move(); // runs the method in Dog class
    }
    }
  • If we call the method only exists in the Animal but not in the Dog, the error will occur. This program will throw a compile time error since b’s reference type Animal doesn’t have a method by the name of bark.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    package a;
    class Animal{
    public void move() {
    System.out.println("The animals move");
    }
    }

    class Dog extends Animal{
    public void move() {
    System.out.println("The dog moves");
    }

    public void bark() {
    System.out.println("The dog barks");
    }

    }


    public class TestDog {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Animal d=new Dog(); // Animal reference but Dog object
    d.move(); //output: The dog moves

    d.bark(); //error
    }
    }

Certainly, it is possible to invoke the method that has been overridden. Just use the super keyword

1
2
3
4
5
6
7
8
9
class Dog extends Animal{

public void move() {

super.move();

System.out.println("The dog moves");
}
}

Output

1
2
The animals move
The dog moves

Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

  • runtime polymorphism

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    class Animal{
    void cry() {

    }
    }

    class Dog extends Animal{
    void cry() {
    System.out.println("wang wang");
    }
    }

    class Cat extends Animal{
    void cry() {
    System.out.println("miao miao");
    }
    }

    public class E {

    public static void main(String[] args) {
    Animal a;
    a =new Dog();
    a.cry();

    a=new Cat();
    a.cry();
    }

    }

    output

    1
    2
    wang wang
    miao miao

Inner Classes

To access the inner class, create an object of the outer class, and then create an object of the inner class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class OuterClass{
int x = 10;

class InnerClass{
int y = 5;
}
}

public class Main1 {
public static void main(String[] args) {
OuterClass myOuter=new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}

Abstract

Abstract class

Abstraction can be achieved with either abstract classes or interface.

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

  • 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//abstract class
abstract class Animal{
//abstract method
public abstract void animalSound();

//regular method
public void sleep() {
System.out.println("zzz");
}
}

//SubClass
class Pig extends Animal{

@Override
public void animalSound() {
// TODO Auto-generated method stub
System.out.println("wee wee");
}

}


public class Main3 {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}

Interface

An interface is a completely “abstract class“ that is used to group related methods with empty bodies. There are not variables in the interface only constants.

To access the interface methods, the interface must be “implemented” by another class with the implements keyword (instead of extends).The body of the interface method is provided by the “implement” class:

1
2
3
4
5
interface A{
int a=0;//constant
public abstract void f1();//public abstract can be omitted
void f2();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
interface Animal{
int MAX=100;
//equal to
//public static final int MAX=100;
//the method in interface has not body
public void animalSound();
public void run();
}

class Pig implements Animal{

@Override
public void animalSound() {
// TODO Auto-generated method stub
System.out.println("wee wee");
}

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("The pig is running");
}

}

public class Main4 {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.run();
}

}

Multiple Interfaces

To implement multiple Interfaces, separate them with a comma:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

interface FirstInterface{
public void myMethod();
}

interface SecondInterface{
public void myOtherMethod();
}

class MyClass implements FirstInterface, SecondInterface{

@Override
public void myOtherMethod() {
// TODO Auto-generated method stub
System.out.println("Some other text...");
}

@Override
public void myMethod() {
// TODO Auto-generated method stub
System.out.println("Some text");

}

}

public class Main5 {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myMethod();
myClass.myOtherMethod();
}
}

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Outer_Demo{
int num;

//inner class
private class Inner_Demo{
public void print() {
System.out.println("This is an inner class");
}
}

void display_Inner() {
Inner_Demo inner=new Inner_Demo();
inner.print();
}

}
public class MyClass {

public static void main(String[] args) {
// TODO Auto-generated method stub
Outer_Demo o=new Outer_Demo();
o.display_Inner();
}

}

To instantiate a inner class, initially we have to instantiate the outer class.

We need to instantiate inside the outer class and new the object inside the outer object.

1
2
Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();

File Handing

Create a file

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or directory name:

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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.*;
public class MyFile {
public static void main(String args[]) {

try {
File myObj=new File("filename.txt");
if(myObj.createNewFile()) {
System.out.println("File created: "+myObj.getName());
}else {
System.out.println("The file already exists");
}
}catch(IOException e){
System.out.println("An error occured");
e.printStackTrace();
}
}
}

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. If the file isn’t exists, it will be created.

Note that when you are done writing to the file, you should close it with the close() method:

1
2
3
4
5
6
7
8
9
try {
FileWriter myWriter=new FileWriter("filename.txt");
myWriter.write("File in java is fun enough");
myWriter.close();
System.out.println("Sucessfully wrote to the file");
}catch(IOException e) {
System.out.println("An error occurred");
e.printStackTrace();
}

Read Files

In the following example, we use the Scanner class to read the contents of the text file we created,

After we read the file, we should close the reader myReader.close();

1
2
3
4
5
6
7
8
9
10
11
12
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}

Delete Files

To delete a file in Java, use the delete() method:

1
2
3
4
5
6
7
File myObj=new File("Filename.txt");
if(myObj.delete()) {
System.out.println("Successfully delete the file");
}
else {
System.out.println("Failed to delete the file");
}

Java Exceptions

When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

1
2
3
4
5
6
7
8
9
10
11
12
public class Excpetions {
public static void main(String[] args) {

try {
int[] arr= {1, 2, 3, 4};
System.out.println(arr[10]);
}catch (Exception e) {
System.out.println("Someting worng");
}
}
}