Java recap - Espresso Guide ☕️
Tags: java
Published: 2023-07-26 11:28:42

Hi there,

This post features the basic concepts with dumb examples for quick reference.

## Table of Contents
&nbsp;1. [How to print ?](#how-to-print-)
&nbsp;2. [How to get user input ?](#how-to-get-user-input-)
&nbsp;3. [How write a class ?](#how-write-a-class-)
&nbsp;4. [Wrapper Classes](#wrapper-classes)
&nbsp;5. [Inheritance](#inheritance)
&nbsp;6. [Method overriding](#method-overriding)
&nbsp;7. [Final and Static](#final-and-static)
&nbsp;8. [interface](#interface)
&nbsp;9. [Abstraction](#abstraction)
&nbsp;10. [Exception handling](#exception-handling)
&nbsp;11. [File handling](#file-handling)


## How to print ?
```java
public class Main {   
   public static void main(String[] args) {   
      System.out.println("Hello world");  
   }   
}  
```
you can also use 

- **System.out.print("text");** - prints with out newline at end ) 
- **System.out.printf("%d text" , 55);** - inserts value in the printed message

```java
System.out.printf("%d text" , 55); //replaces %d with 55
//similarly for char,String,boolean we have
System.out.printf("%c text" , 55);
System.out.printf("%s text" , "hi");
System.out.printf("%b text" , true);
```
-----

## How to get user input ? 

```java
import java.util.Scanner;  // Import the Scanner class

class Main {
  public static void main(String[] args) {
   Scanner myObj = new Scanner(System.in);  // Create a Scanner object
   String input = myObj.nextLine();  // Read user input
  }
}
```
-----

## How write a class ? 

_A class is a "blueprint" for creating objects_
```java
class Car {
   int noOfWheel  = 6;
}
```
We can create an object of the class by
```java
public static void main(String[] args){
   Car bmw = new Car();
}
```

Classes with constructor
```java
public class Car {
   // Instance Variables
   String name;
   int year;
   String color;

   // Constructor 
   public Car(String name,int year,String color){
      this.name = name;
      this.year = year;
      this.color = color;
   }
}
```
Now the object can be created as
```java
public static void main(String[] args)
   {
      Car bmw = new Car("bmw", 2022,"blue");       
   }
```
-----

## Wrapper Classes

Wrapper classes are reference of primitive datatypes.
Integer is the wrapper class of primitive int.
Boolean - boolean
Character - char, etc

**autoboxing** - automatic converison of primitive to wrapper
`Integer a = 123;`
**unboxing** - conversion of wrapper to primitive
`if(a == 123){} // here the java unboxes the primitive to compare the values`

-----

## Inheritance

Inheritance allows one object acquires all the properties and behaviors of a parent object.

```java
class Worker{  
 float salary=40000;  
}  
class MailMan extends Worker{  
 int bonus=10000;  
 public static void main(String args[]){  
   MailMan m=new Mailman();  //m will have all characters of Worker class in addition to its own properties.
}  
} 
```
-----

## Method overriding

Overriding the method of superclass in subclass
```java
class Vehicle{  
  void run(){System.out.println("Vehicle is running");}  //method in parent
}  

class Bike extends Vehicle{  
  void run(){System.out.println("bike is running");} // method in child
}  
```
-----

## Final and Static

Final classes cannot be inherited.
Final variable cannot be modified.
The static used to share the same variable or method of a given class. It can be accessed without an object instance.

```java
class Student{  
   String name;  
   static String college ="abc";//static variable   
}  

public class Test{  
 public static void main(String args[]){  

   Student.college = "efgh"; // the static variable can be accessed without an object. it also changes the particular variable for all objects of the class.

   Student s1 = new Student();
   s1.name = "rahul"  //object must be created to access non-static variable
 }  
} 
```
-----

## interface 

It specifies what a class has or must do.
Inhereted classes can have only one superclass while interface allows to implement methods from different interfaces.
```java
interface sayHello{  
   void hello();  
} 
interface sayHi{  
   void hi();  
}   

public class say implements sayHello , sayHi {
   @override
   void hello(){ // something };
   @override
   void hello(){ // something };
}   
```
-----

## Abstraction

The abstract keyword can be used with a class or method.
Abstract classes cannot have an object, but their subclasses can.
```java
abstract class Bike{  
  void run();  
} 
``` 
Abstract methods specifies the method name without the method body. These methods must be ovveriden in the subclass.
```java 
class Bike{  
  abstract void run();  //no method body
}

class Honda extends Bike{  
   void run(){
     System.out.println("running safely"); // override
   }   
}  
  
```
-----

## Exception handling 

Exception handling helps to avoid program intreption by catching errors.

```java
public class test{  
  public static void main(String args[]){  
   try{  
      //code that may raise exception  
   }catch(ArithmeticException e){
      //to do - in incase of exception
   }finaly{
     //to do - finaly  
  }  
} 
```
`Exeception e` catches all exeptions but,its good practice to handle each exception individually. `e.printStackTrace` prints the error details.
-----

## File handling 

File class can be used to create a file abstraction and FileReader will help with reading from files.
```java
import java.io.File;
import java.io.FileReader;
public class file {
    public static void main(String[] args) {
        File f=new File("new.txt");
        try{
        if(f.exists())
        {
            FileReader fr=new FileReader("new.txt");
            int var=0;
            var=fr.read();
            while(var!=-1){
                System.out.println((char) var);
            var=fr.read();
            }
        }
        }
        catch(Exception e){
            System.out.println("Exception catched");

        }
    }
}
```


---------------