Multi Threading Programming (Java)

Multi Threading Programming In Java

What is the multi threading programming that we used is Java, hear this.. Java is actually a multi-threaded programming language and by that Java can let us develop a multi-threaded program.

Do you know what a multi-threaded program is? well a multi-threaded program contains two or more than two parts. Which runs concurrently and each of that one part can handle different task (i.e codes that contains methods, constructors etc) at the same equal time. This can actually improves the optimal use of the available resource, if you have multiple CPUs.

Basically multi threading programming takes the idea of multi tasking. Which is “doing more than 1 activities at the same time”. Multi tasking in our terms it means when a multiple processes share a common process resource such as a CPU.
Continue reading Multi Threading Programming (Java)

Code Aggregation *for code reusability

What is Code Aggregation

code aggregation
Code aggregation as reusability

If there is an entity reference in a class, then you what you have is a code aggregation. Aggregation usually represents HAS-A relationship.
Consider the following situation situation.

A Worker object contains many informations such as id, name, phone number etc. It contains one more object named address, which contains its own informations such as city, state, country etc. see it as given below.

Continue reading Code Aggregation *for code reusability

Java JSpinner & Its Definition

What is Java JSpinner

Okay lads, today we’re talking about Spinner. But hey! it’s not a fidget spinner that we’re talking. Because It is a Java JSpinner and JSpinner allows the users to select a number or an object value from an already sequence using single line input.

The Syntax :
public class JSpinner extends JComponent implements Accessible  

First of all here are common constructor of Java JSpinner:

  • JSpinner() : This class is used to construct a spinner with an Integer SpinnerNumberModel and in addition of an initial value of 0 and with no minimum or maximum limits.
  • JSpinner(SpinnerModel model) : This is another one of Java JSpinner that is used to construct a spinner for a given model.
Especially relevant here are common methods ofmJava JSpinner :

 

  • void addChangeListener(ChangeListener listener) : This method is used to add another listener to the list which will be notified each time a change to the model occurs.
  • Object getValue() :While this method is used to return the current value of the model.
Finally It’s Exmpl time! :
 
import javax.swing.*;    
public class SpinnerExample {  
    public static void main(String[] args) {    
    JFrame f=new JFrame(“Not Fidget Spinner”);    
    SpinnerModel value =  
             new SpinnerNumberModel(10, //initial value  
                0, //minimum value  
                20, //maximum value  
                2); //step  
    JSpinner spinner = new JSpinner(value);   
            spinner.setBounds(100,100,50,30);    
            f.add(spinner);    
            f.setSize(300,300);    
            f.setLayout(null);    
            f.setVisible(true);     
}  
}  
 
And This will output :

ForEach() Method : Lambda Expressions & Method Reference

Definition of ForEach() Method

ForEach() Method

Due to Java 8 new features, that provides us java coders a method named forEach() to iterate the elements. forEach() method is defined in iterable and Stream interface. The collection classes which is the one that extends the iterable interface can use forEach loop to iterate elements. As a result you can pass lambda expressions as an argument in this method because it takes a single parameter which is a functional interface.

Continue reading ForEach() Method : Lambda Expressions & Method Reference

Java Split Method

What Is Java Split Method?

programming Java, Java Split Method
Programming Java

There’s a method in java that is used to “split” string into pieces, the split is based on a given regular expressions and a return char array. There are 2 type of syntax that can be used for Java Split Method, (for a fun fact java split method is available since java 1.4).

Continue reading Java Split Method

Java strictfp Keyword

strictfp may sound odd to you, because at first I do as well. But strictfp is a java keyword that will ensure your result will and always be the same on every platform if you do an operation in the floating point variable. The result of an operation in the floating point variable may differ to each and every platform you use, and by that java programming language provide the strictfp so you’ll get the same result on every platform. Also by having strictfp you have more control over floating point arithmetic.

Usable strictfp keyword syntax

The strictfp can be used methods, classes and interfaces.
class Example{
strictfp void Example(){ //strictfp applied on methods
  }
}

strictfp Example{ //strictfp applied on classes
}

strictfp interface Example{ //strictfp applied on interface
}

Unusable strictfp keyword syntax

The strictfp can not be used in abstract method, variables or constructors.
class Example{
strictfp int value = 10; //can not be used in variables i.e integer
}

class Example{
strictfp abstract void example(); //can not be used in abstract methods
}

class Example{
strictfp Example(){} // can not be used in constructors
}

Java Covariant Return Type

Howdy Mowdy People? Have you ever override a method by changing its return type? Well for y’all that is already a pro in Coding may know this type of overriding, but for those who is still  a green horn in coding, just like me :’D maybe. This kind of method overriding is called Java Covariant Return Type, which is not available until Java5 came out.

Here ok, let me just show you a simple presentation of this Covariant Type :

public class A{  
A get(){return this;}  
}  
  
class B extends A{  
B get(){return this;}  
void message(){System.out.println(“Craftingez6 covariant return type“);}  
  
public static void main(String args[]){  
new B().get().message();  
}  
}  

This will output :

Craftingez6 covariant return type

Well as you can see, the return type of get() method A class is A, but then… the return type of B class is.. B. Both of this class have a different return type but both of them is tied in a method overriding, B overriding A.This thing/process/phenomenon is called Covariant return type.

There we go I’ve explaing it. See you!

Conclusions

  • Method overriding is called Java Covariant Return Type
  • Both of this class have a different return type but both of them is tied in a method overriding, B overriding A

Java SE 8 Lambda Expressions

Lambda expression is one of a lot of new and important feature of Java which specifically it’s Java SE 8. This feature (lambda Expressions) will provide one clear and concise way to represent interface method using an expression. The method is very useful in the collection library in so much way. Before the lambda expression, using an anonymous inner class was the only way and option for a coder to implement the method.

The new Java SE 8 feature Lambda expression provides coders an implementation of a functional interface. Functional Interface is an interface that has only one abstract method. Java provides an annotations @FunctionalInterface, which is used to declare an interface as a functional interface. 

Reason To Lambda Expressions:

  1. To do less coding.
  2. To have the implementation of Functional Interface 

Lambda Expression Syntax :

(argument-list) -> {body}  

Below I will tell you the components that built Lambda Expression:

  1. Body: Body Components contains statements  .etc for the lambda expression.
  2. Argument-list: An Argument-list you could fill it empty or filled as well.
  3. Arrow-token: The arrow token functionality is to link the arguments-list and body of statements.


Here is an Example without Lambda Expression in Interface:

    interface Colourable{ 
        public void colour(); 
    } 
    public class LambdaExpressionExample { 
        public static void main(String[] args) { 
            int width=7; 
     
            //without lambda we used anonymous inner class

            Colourable c=new Colourable(){ 
                public void draw(){System.out.println(“Drawing “+width);} 
            }; 
            c.colour(); 
        } 
    }  


Then compare it to the one that uses lambda Expression:

  @FunctionalInterface  //It’s optional 
    interface Colourable{ 
        public void colour(); 
    } 
     
    public class LambdaExpressionExample { 
        public static void main(String[] args) { 
            int width=7; 
             
            //with lambda  (less coding)
            Colourable c2=()->{ 
                System.out.println(“Drawing “+width); 
            }; 
            c2.colour(); 
        } 
    } 

  
 Conclusions :


How To Play MP3 Files in Java Eclipse

How is it going coders? for today Tutor… I’m gonna tell y’all how to Play MP3 files in Java Program. Just like always for todays example I’m using Eclipse, you could use it or any other IDE that suites you. For todays program I’m using MP3 files, so thats not too hard to find.

 First of all you need to have your MP3 files inside your source folder like this :

Just look at that “Mfg” MP3 files that I have inside my source folder for “MainMP3” Program.
Now for the coding Spices :


Wait!!! Before all of that You need to Download JLayer Here :  JLayer
And add it to your program Build Path using “Add External JARs” :

//1st now well import the important classes
//(notice that there is a class/package named javazoom.jl…)

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

//2nd we create our method inside our class
public class MainMP2 {
 

//here we create the main method

    public static void main(String[] args){
       
        try{
        FileInputStream fileInputStream = new FileInputStream(“Mfg.mp3”);
 //here we find our sound file
        Player player = new Player(fileInputStream);
        player.play();
        System.out.println(“Song is Playing”);
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(JavaLayerException e){
            e.printStackTrace();
        }
       
    }
   
}

Well since I can’t tell you how it sounds in here, you can go and check my Youtube Channel for the Voice explanation : MP3 Files in Java Eclipse Check it out!! and subscribe

JButton with ActionListener (Count!!!)

How is it going everybody? Pheww… Its been quite too long since my last article Ha! Now I’m back in shape with another new article. Today’s article is about a Button, well I’m feeling a little bit itchy about Button because I hasn’t made an interactive button (ActionListener). So today’s all about adding an ActionListener to a Button.

Okay so if you doesn’t know how to create a Button in Java, check out This article on how to create Button in Java : Button 

This is the code of a JButton :

 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {
    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);
      
    }  
}

First here is the code that implements ActionListener :

button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;

       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}

That’s it, now you just need to implement it to your original Button code :


 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {

    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);

        button.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;
       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}
      
    }  
}


That is a button that will count (increments (++) ) the number 5 by 1 and would go on while the number is still smaller (<) than 20.