Java Programming

Quick Links;

1. How to start JavaFx Project

How to install Java   https://s08kzivyri.vmaker.com/record/CdIy2tyin1BrtFeg

java codes;

======1. How to find a prime number;======================

get number and find modulus with each i number from 1 to given number 

num%i ; where i=1;i<num;i++ ;

if num%i==0; then the number is composite; else it a prime.


import java.util.*;
class Example{
    public static String isPrime(int num){
        boolean isPrime=true;
        for(int j=2; j<num; j++){
            if(num%j==0){
                isPrime=false;
                break;
            }
        }
return isPrime ? " prime ": " Not Prime";
 }
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.print("Input a number : ");
        int num = input.nextInt();
        System.out.print(num + isPrime(num)); 
 }
}

 


=====How to find prime number using two loops L1 and L2 =========

class Example{
public static void main(String args[]){
L1: for(int i=3; i<=100; i++){    
// create loop L1: and increase i values by 1
        L2:for(int j=2; j<i; j++){
//  create loop L2: and increase j from 2 to i-1;
                if(i%j==0){
// if i can devide by j
                    continue L1;
// continue loop L1
                }
            }
        System.out.println(i);
        }
    }
}

=======================================================

 class Example{
public static void main(String args[]){
    int num=43;
    int count=0;
    for(int j=2; j<num; j++){
// devide number from 2 to 42,
        if(num%j!=0){
//check wether reminder is  not equal to zero
        count++;    
// count number of this kind of cycles
        }
    }
        if(count==num-2){
// if all numbers devide with reminders
System.out.println(num+" is a primne number");
        }
    }

========= How to find a factorial using java methods================

import java.util.*;
class Example{
    public static int findFactorial(int num){
        if( num>0){
        return num*findFactorial(num-1);}
        else{
            return 1;}
        }
    public static void main ( String args[]){
    Scanner input = new Scanner (System.in);
    System.out.print("Insert a number to find its factorial : ");
    int number = input.nextInt();
    System.out.print("Factrial of "+ number + "!   =" + findFactorial(number));
        }
}

 

    

============= Reverse a given string =========================

import java.util.*;
public class Example{
public static String reverse (String str){
    char ch[]=str.toCharArray(); 
    String rev= "";
    for ( int i=ch.length-1;i>=0;i--){
        rev+=ch[i];
    }
    return rev;
}
public static void main(String args[]){
    String str = "Asanka";
    System.out.println(reverse(str));
    }
}



How to alternate Array

import java.util.*;

class Example{

    public static int[] ar={34,12,61,29,59,94,24,58};

    

    public static void main(String args[]){

        System.out.println(Arrays.toString(ar)); //[34,12,61,29,59,94,24,58]

        System.out.println("Length : "+ar.length); //8

    

        add(99);

        System.out.println(Arrays.toString(ar));//[34,12,61,29,59,94,24,58,99]

        System.out.println("Length : "+ar.length); //9

        

        add(55,4); //add(int data, int index)

        System.out.println(Arrays.toString(ar));//[34,12,61,29,55,59,94,24,58,99]

        System.out.println("Length : "+ar.length); //10

        

        remove(4); //remove(index)

        System.out.println(Arrays.toString(ar));//[34,12,61,29,59,94,24,58,99]

        System.out.println("Length : "+ar.length); //9

        

add(new int[]{10,20,30,40},4); //add(int[] arrayElement, int index)

        System.out.println(Arrays.toString(ar));//[34,12,61,29,10,20,30,40,59,94,24,58,99]

        System.out.println("Length : "+ar.length); //13

        

        remove(4,7); //remove(int startIndex, int endIndex)

        System.out.println(Arrays.toString(ar));//[34,12,61,29,59,94,24,58,99]

        System.out.println("Length : "+ar.length); //9

    }

    public static void add(int data){ //add to the last

        int[] temp=new int[ar.length+1];

        for (int i = 0; i < ar.length; i++){

            temp[i]=ar[i];

        }

        ar=temp;

        ar[ar.length-1]=99;

    }

    //overload method add

    public static void add(int data, int index){ //add to the index

        if(index>=0 && index<ar.length){

            int[] temp=new int[ar.length+1];

            for (int i = 0; i < ar.length; i++){

                temp[i]=ar[i];

            }

            for (int i = temp.length-1; i >index; i--){

                temp[i]=temp[i-1];

            }

            temp[index]=data;

            ar=temp;

        }else{

            System.out.println("Index error");

        }

    }

    

    // remove int

    public static void remove(int index){

int [] temp = new int [ar.length-1];

for (int i = 0; i < index; i++) {

temp[i]=ar[i];

}

for (int i = index ;i<temp.length; i++) {

temp[i]=ar[i+1];

}

ar=temp;

}

// add array

public static void add(int [] addAr,int index){

int[] temp = new int [(ar.length+addAr.length)];

for (int i = 0; i < index; i++) {

temp[i]=ar[i];

}

for (int i = index; i < (addAr.length+index-1); i++) {

temp[i]=addAr[i-index];

}

for (int i = (addAr.length+index-1); i <(ar.length+addAr.length); i++) {

temp[i]=ar[i-(addAr.length+index-1)];

}

ar=temp;

}

public static void remove(int index1, int index2){

int [] temp = new int [ar.length-(index2-index1+1)];

for (int i = 0; i < index1; i++){

temp[i]=ar[i];

}

for (int i = index2+1; i < ar.length; i++) {

temp[i-index1] = ar[i];

}

ar=temp;

}

}

==============Java Interface // Calculators// ==================================
 
Simple calculator using extends JFrane implements ActionListner
 
 
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

class Calculator extends JFrame implements ActionListener  //
{
    private JPanel buttonPanel;
    private JPanel inputOutputPanel;
    private JTextField info;
    private boolean editable = true;

    public Calculator()
    {
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4,4,5,5));
        //for padding
        buttonPanel.setBorder(new EmptyBorder(10,10,10,10));

        inputOutputPanel = new JPanel();
        inputOutputPanel.setLayout(new FlowLayout());

        setTitle("Calculator using Java");
        setSize(400,320);
        setResizable(false);
        
        info = new JTextField();
        info.setFont(new Font("SansSerif", Font.PLAIN, 16));
        info.setBackground(Color.white);
        info.setBorder(BorderFactory.createLineBorder(Color.black));
        info.setPreferredSize(new Dimension(180, 25));
        info.addActionListener(this);
        inputOutputPanel.add(info);
        contentPane.add(inputOutputPanel);

        //buttons in calculator
        String buttons[] = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2","3","-","0",".","=", "+",};
        //adding buttons for buttons array
        for (String i : buttons)
        {
            JButton button = new JButton(i);
            button.addActionListener(this);
            buttonPanel.add(button);
        }

        contentPane.add(buttonPanel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public void actionPerformed(ActionEvent event)
    {
        //source is from button
        if (event.getSource() instanceof JButton)
        {
            JButton clickedButton = (JButton) event.getSource();
            //if = is clicked then result will be displayed
            if(clickedButton.getText().equals("="))
            {
                addOutput();
            }
            //else we will take input
            else
            {
                addInput(clickedButton.getText());
            }
        }
        //source is from JTextField
        else
        {
            addOutput();
        }
    }

    public void addInput(String line)
    {
        //appending pressed keys to TextField
        //editable will be false if result is displayed
        if(editable)
        {
            info.setText(info.getText()+line);
        }
        //result is on the screen
        //editable is false
        //no appending
        //we will add the text
        else
        {
            info.setText(line);
            editable = true;
        }
    }
    public void addOutput()
    {
        double output = 0;

        //converting string into expression
        try
        {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            info.setText(engine.eval(info.getText()).toString());
        }
        catch(ScriptException e)
        {
            info.setText("Syntax error");
        }
        editable = false;
    }

    //main method
    public static void main (String [] args)
    {
        Calculator calculator = new Calculator();
        calculator.setVisible(true);
    }
}
=================Methods Overriding and Overloading ==========================
overloading==> Same method name but different parameters
overriding  ==> Same method name and same parameter..(Same Signature)
 
=================Dynamic Methods Dispatch ==================================
Here vehicle object create in and compile in Vehicle class but run in car class; This is called Dynamic Method Dispatch; This is happen due to method overriding===> Same signature Methods in Super Class and sub Classes...

class Vehicle{
    public void park(){
        System.out.println("Vehicle Parking..");
    }
}
class Car extends Vehicle{
    public void park(){ //Same name, same parameter list==>Method Overriding
        System.out.println("Car Parking..");
    }    
}

class Demo{
    public static void main(String args[]){   
        Vehicle v1=new Car();
        v1.park(); //(Car Parking...) Compile from Vehicle Class but Run from Car Class
    }
}

================= Polymorphism ============================================
 
class Vehicle{  // vehicle Super class
    public void park(){
        System.out.println("Vehicle Parking..");
    }
}
class Car extends Vehicle{ // Car class inherit from Vehicle super class
    //Same name, same parameter list==>Method Overriding
    //if same name different parameter ==> Methods Overloading
    public void park(){
        System.out.println("Car Parking..");
    }       
}

class Van extends Vehicle {
    public void park (){
        System.out.println("Van Parking..");
        }
    }

class Bus extends Vehicle{
    public void park(){
        System.out.println("Bus Parking .. ");
        }
    }
    
class Demo{
    public static void main(String args[]){   
        //create Vehicle object array
        Vehicle [] vehicleArray = {new Car(),new Van(), new Car(), new Bus()};
        for(Vehicle v1: vehicleArray){  // For Each loop to create V1 object
            v1.park(); // single interface many output form ==> polymorphism
            }    
    }
}



No comments:

Search This Blog