Let's write program with Java (Miscellaneous) - Part 4
Credit: Analytics Insight

Let's write program with Java (Miscellaneous) - Part 4

*** Previous Part ***Let's write program with Java (Object Oriented Programing) - Part 3

Basic Syntax of Java:

I try to keep the things simple enough as much as possible. Without any outside discussion I only mention the main focus point. So lets start..

Enum:

An enum is a special type of class in Java that represents a group of constants. Enums are used to create fixed sets of constants that are used in a program. They make code more readable and less error-prone because they provide a set of named values that can be used instead of hard-coded values.

public enum Direction {
  NORTH,
  EAST,
  SOUTH,
  WEST
}


//Using an enum in a switch statement:
Direction direction = Direction.NORTH;
switch(direction) {
  case NORTH:
    System.out.println("Going North");
    break;
  case EAST:
    System.out.println("Going East");
    break;
  case SOUTH:
    System.out.println("Going South");
    break;
  case WEST:
    System.out.println("Going West");
    break;
}

In Java one of the advantages of enums is that you can define custom values for each constant. Here's an example of how to do that:

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), XLARGE("XL");
    
    private final String abbreviation;
    
    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }
    
    public String getAbbreviation() {
        return abbreviation;
    }
}

Size size = Size.MEDIUM;
System.out.println("Size: " + size);
System.out.println("Abbreviation: " + size.getAbbreviation());

Annotation:

Annotations are a way to add metadata to Java code. They can be added to classes, methods, variables, and parameters. Annotations are used for a variety of purposes, such as documentation, code analysis, and code generation. Java provides several built-in annotations, and developers can also create their own custom annotations. Java annotations starts with '@'.

@Deprecated
public class OldClass {
  // code here
}

public @interface MyAnnotation {
    String value() default "default value";
}

//Usage of a custom annotation:
@MyAnnotation(value = "custom value")
public class MyClass {
  // code here
}

Exception Handling:

Java exception handling is the process of catching and handling errors that occur during program execution. When an exception occurs, it is thrown by the program and can be caught and handled by a try-catch block. Java provides a hierarchy of exception classes that can be used to catch different types of exceptions. There can be single or multiple catch block under a try statement. Also after try-catch we can have a finally block which will be executed last.

try {
  // code that may throw an exception
} catch (ExceptionType1 e) {
  // handle exception type 1
} catch (ExceptionType2 e) {
  // handle exception type 2
} finally {
  // code that will always execute, regardless of whether an exception was thrown or caught
}

When we are working with resources or files than java try-catch with resources feature ensures that after all the work automatically closes any resources that are opened in the try block, whether or not an exception occurs.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.err.println("Error reading file: " + e.getMessage());
}

Multi threading:

Multi-threading is the process of running multiple threads of execution concurrently within a single program. In Java, multi-threading is achieved by extending the Thread class or implementing the Runnable interface. Multi-threading is used to improve the performance of a program and to execute multiple tasks simultaneously.

class MyThread extends Thread {
  public void run() {
    // code to be executed in this thread
  }
}


//Starting a thread:
MyThread t = new MyThread();
t.start();


//Using the Runnable interface:
class MyRunnable implements Runnable {
  public void run() {
    // code to be executed in this thread
  }
}


//Starting a thread using the Runnable interface:
Thread t = new Thread(new MyRunnable());
t.start();

Lambda Expression:

Lambda expressions are a shorthand way to define anonymous functions in Java. They can be used to create functional interfaces, which are interfaces that have only one abstract method. Lambda expressions are used to write more concise and readable code, especially when working with streams and collections. It can be single as well as multiline too. It declare with 0 or more parameters followed by '->' and body.

//Using a lambda expression to define a Comparator for sorting strings by length
// comparator lambda: (s1, s2) -> s1.length() - s2.length()

List<String> strings = Arrays.asList("apple", "banana", "orange", "kiwi");
Collections.sort(strings, (s1, s2) -> s1.length() - s2.length());
System.out.println(strings);

Hello Saiful... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any

要查看或添加评论,请登录

Saiful Islam Rasel的更多文章

社区洞察

其他会员也浏览了