Trending February 2024 # Java Program To Get Year From Date # Suggested March 2024 # Top 2 Popular

You are reading the article Java Program To Get Year From Date updated in February 2024 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Java Program To Get Year From Date

In our day to day life, there is a huge data being generated in this real world. Among the information generated, Dates are generally used for various things such as scheduling an appointment, planning for day-to-day activities. While working with dates in programming, extracting the year from a specific date can be a common task. We can extract the Year from a particular Date using different in-built functions in Java programming language. In this article we will be discussing different approaches for extracting year from a particular date.

Example Input: "13-07-2000" Output: 2000 Example Input: "1997/07/13" Output: 1997 Approaches

Using LocalDate Class.

Using String.split() method.

Using Calender Class.

Using SimpleDateFormat Class.

Algorithm

Write a custom method in the Main class to extract Year from date.

Use different inbuilt functions provided by java in the custom functions to extract date.

Print the Year extracted from date.

We will now discuss each approach in detail for extraction of year from date and implement code in java programming language.

Approach 1: Using LocalDate Class

In this approach, we will use the LocalDate class from the chúng tôi chúng tôi method ‘getYear()’ from LocalDate. getYear() method generally returns an integer as output.

Syntax

The following syntax refers to the usage of getYear() method.

int variable = DateObject.getYear();

Here a simple code snippet using the above syntax:

LocalDate currentDate = LocalDate.parse("2000-07-13"); int year = currentDate.getYear(); System.out.println(year); Example

In this program we will import the LocalDate class of the chúng tôi package. Then we need to parse the string into date using parse() method. The parse() method accepts date in ‘yyyy-mm–dd’ format and it converts a string into local date. Once we get date we can extract year using getYear() method.

import java.util.*; import java.time.LocalDate; public class Main { public static void getYearFromDate(String date) { LocalDate inputDate = LocalDate.parse(date); int year = inputDate.getYear(); System.out.println("Year extracted from date is : " + year); } public static void main(String args[]) { String date = "2000-07-13"; getYearFromDate(date); } } Output Year extracted from date is : 2000

Time Complexity: O(1) Auxiliary Space: O(1)

Approach 2: Using String.split() method

In this approach, we will use the split() method from the String class. This method is used to divide a string into tokens based on a delimiter (the symbol which is using to divide the string into tokens).

Syntax

The following syntax refers to the usage of split() chúng tôi takes a delimiter as an input and give array of string tokens as output.

String array_variable [] = String_Variable.split(“delimiter”);

Here is a simple code example demonstrating the above syntax:

date = '13-07-2000'; String tokens[] = date.split("-"); System.out.println(tokens[2]); Example

In the above program, a string is declared and passed to extractYear() function. This function generally uses the split() method of String class. The split() method generally takes a delimiter(in the above program it is “-”) and splits the string into an array of Strings .As year is the 3rd token in the date, we print tokens[2] which gives the desired output.

import java.util.*; public class Main { public static void extractYear(String date) { String tokens[] = date.split("-"); String year = tokens[2]; System.out.println("Extracted Year from Date: " + year); } public static void main(String args[]) { String date = "13-07-2000"; extractYear(date); } } Output Extracted Year from Date: 2000

Time Complexity: O(1) Auxiliary Space: O(1)

Approach 3: Using Calendar Class

In this approach, we will use the Calendar class from the util package. We in this example use chúng tôi which extracts Year in a particular date using Calendar object.

Syntax

The following syntax refers to the usage of get() method of Calender class . It returns a integer value specified as a field_parameter.

int var_name = CalenderObject.get(field_parameter);

Here a simple code snippet that uses the above syntax to get the year from date −

Calendar cal = Calendar.getInstance(); int Year = cal.get(Calendar.YEAR); Example

In the above example we are using Calendar class to get the year from date. We declare a calendar object and use getInstance() method of Calendar class to get current date object. We use get() method and pass chúng tôi parameter to get the year from the date.

import java.util.Calendar; public class Main { public static void getYear(Calendar cal){ int Year = cal.get(Calendar.YEAR); System.out.println("Extracted year from date : " +Year); } public static void main(String[] args) { Calendar cal = Calendar.getInstance(); getYear(cal); } } Output Extracted year from date : 2023

Time Complexity: O(1) Auxiliary Space: O(1)

Approach 4: Using SimpleDateFormat Class

In this approach, we will use the SimpleDateFormat class from the text package and Date class from util package. We in this example use Date class and get a date initially, we then create a SimpleDateFormat object which generally formats a date to a specified format as given in parameter.

Syntax

The following syntax refers to the usage of format() method of SimpleDateFormat class . It returns a integer value specified as a field_parameter.

int var_name = CalenderObject.get(field_parameter);

Here is an implementation of the above syntax:

Calendar cal = Calendar.getInstance(); int Year = cal.get(Calendar.YEAR); Example

In this example, we used Date and SimpleDateFormat classes. SimpleDateFormat is used to get only the date from the date object as date gives both date and time. So, we first declare a date object and then create and SimpleDateFormat object to get year by passing ‘yyyy’ parameter.format() method it is used to return a date or time using given pattern.

import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void getYear(Date date) { SimpleDateFormat getYearDate = new SimpleDateFormat("yyyy"); String year = getYearDate.format(date); System.out.println("Extracted year from date :" + year); } public static void main(String[] args) { Date date = new Date(); getYear(date); } } Output Extracted year from date :2023

Time Complexity: O(1) Auxiliary Space: O(1)

Thus, in this article we have discussed different approaches to implement a java program for extracting year from a specific date.

You're reading Java Program To Get Year From Date

Java Program To Reverse A List

What is a Reverse List?

Reverse a list is an operation of swapping or interchanging the elements position into a particular list. While you are writing a code in Java, you can easily reverse the order of a certain flow. It is a conventional way of any programming language in computer science. The reverse () method is a collection of class which reverses the position of first element to last element. Last element will earn the first position itself after the termination of the process.

A list is an interface where the class method is denoted as a signature with no definition. The class will be implemented from this by which a method gets a particular definition. Today in this article, we will learn about how to reverse a list using Java conditions with different methods.

How to Reverse a List Using Java?

In this method, we have to mention a pointer to perform the reversing process on a linked list by changing nodes.

Reverse an ArrayList in Java can be used by a class reverse method aka Collections.reverse(). In this method the list of the array will be in a linear time with a time complexity of O(n). This method accepts a List type argument to execute a program.

Sometimes when you are writing a code using Java, it’s needed to start the operation from the last element to reverse an array. By altering the position of first and last elements, it’s needed to get a grip that the process will run until the mid-elements swap their positions.

Print the array in a reverse manner, the coder needs to use a for-loop to initiate the printing operation from the end of that particular set of the data aka array. It is a conventional way to reverse a list.

There are so many interfaces in Java by which you can reverse a List but the in-place reversal is a better option to save the machine memory.

Algorithm to Reverse a List

Here is the general algorithm to reverse a linked list by using Java −

Step 1 − Create a new arraylist.

Step 2 − Put some data as input by using add(E e) API.

Step 3 − Reverse those elements of the list and use invoke reverse(List list) API.

Syntax import java.util.Collections; (the Java Package) Collections.reverse(the class_obj);

Reverse() method of class collection suggests as iereversing the elements in which they can be sorted.

There are several methods to reverse a list using Java −

Approach 1 − Reverse Array Printing Collections.reverse() method

Approach 2 − Use for loop to reverse an array

Approach 3 − In Place Method to reverse an array

Approach 4 − By Java 8 stream API

Approach 5 − By ListIterator

Reverse Array Printing By Using Collections.reverse() Method public class reverseclassArray { static void reverse(int a[], int n){ int[] b = new int[n]; int j = n; for (int i = 0; i < n; i++) { b[j - 1] = a[i]; j = j - 1; } System.out.println("Here the reversed array is:"); for (int k = 0; k < n; k++) { System.out.println(b[k]); } } public static void main(String[] args){ int [] arr12 = {101, 202, 303, 404, 505}; reverse (arr12, arr12.length); } } Output Here the reversed array is: 505 404 303 202 101 Reverse an Array Using for Loop

We can use a for loop to reverse an array. In this method a new array is injected with the existing array and by this it will be in a reverse manner.

Example public class Main { static void reverse_array(char char_array[], int a) { char[] dest_array = new char[a]; int j = a; for (int i = 0; i < a; i++) { dest_array[j - 1] = char_array[i]; j = j - 1; } System.out.println("Reversed array from this operation is: "); for (int r = 0; r < a; r++){ System.out.print(dest_array[r] + " "); } } public static void main(String[] args){ char [] char_array = {'I','N','D','I','A'}; System.out.println("Original array print after the operation: "); for (int s = 0; s <char_array.length; s++) { System.out.print(char_array[s] + " "); } System.out.println(); reverse_array(char_array, char_array.length); } } Output Original array print after the operation: I N D I A Reversed array from this operation is: A I D N I In Place Method to Reverse an Array

The operation can be done without using another separate type of array. Method can be followed by the swapping between the first and last data of the array.

Example public class reverseArray { static void reverse(int a[], int n){ int[] b = new int[n]; int j = n; for (int i = 0; i < n; i++) { b[j - 1] = a[i]; j = j - 1; } System.out.println("Reversed array is after the operation:"); for (int l = 0; l < n; l++) { System.out.println(b[l]); } } public static void main(String[] args){ int [] arr = {1000, 2000, 3000, 4000, 5000}; reverse(arr, arr.length); } } Output Reversed array is after the operation: 5000 4000 3000 2000 1000 By Using Java 8 Stream API

Using the stream API, create an int stream which represents the indexes of the list.

Example import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class FavFashion{ public static void main(String[] args) { clothesfavv.add("Raymond Shirt"); clothesfavv.add("Impact Pants"); clothesfavv.add("Socks of Champion"); clothesfavv.add("Shoes By Bata"); System.out.println("Before reversing the whole data:"); System.out.println(clothesfavv); System.out.println("After reversing the whole data:"); System.out.println(reverseClothesfavv); } } Output Before reversing the whole data: [Raymond Shirt, Impact Pants, Socks of Champion, Shoes By Bata] After reversing the whole data: [Shoes By Bata, Socks of Champion, Impact Pants, Raymond Shirt] By List Iterator

The Java environment has an iterator class, and can be used to iterate different collections of the data.

Example import java.util.*; public class FashionCollector{ public static void main(String[] args) { clothesstore2023.add("T-shirt Of Raymond"); clothesstore2023.add("Pants By Impact"); clothesstore2023.add("Socks Of Champion"); clothesstore2023.add("Shoes Of Bata"); while(listIterator.hasPrevious()){ String elemenString = listIterator.previous(); reverseclothesstore2023.add(elemenString); } System.out.println("Before reversing the storage data:"); System.out.println(clothesstore2023); System.out.println("After reversing the storage data:"); System.out.println(reverseclothesstore2023); } } Output Before reversing the storage data: [T-shirt Of Raymond, Pants By Impact, Socks Of Champion, Shoes Of Bata] After reversing the storage data: [Shoes Of Bata, Socks Of Champion, Pants By Impact, T-shirt Of Raymond] Conclusion

Thus, from the above discussion, we have found how to reverse a list using by using Java. After implementation of various coding methods. It’s recommended to understand those approach carefully.

While we are trying to reverse a list using Java, there are several problems we can encounter. But here is the solution by which a coder can face those problems in smart way.

Java Program To Interchange The Diagonals

In this article, we will understand how to interchange the diagonals. The matrix has a row and column arrangement of its elements. A matrix with m rows and n columns can be called as m × n matrix.

Individual entries in the matrix are called element and can be represented by a[i][j] which suggests that the element a is present in the ith row and jth column.

Below is a demonstration of the same −

Suppose our input is −

The matrix is defined as: 4 5 6 1 2 3 7 8 9

The desired output would be −

The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7 Algorithm Step 1 - START Step 2 - Declare an integer matrix namely input_matrix, and two integer value namely matrix_size and temp. Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using multiple for-loops and swap the required elements of the matrix using a temporary variable. Step 5 - Display the result Step 5 - Stop Example 1

Here, we bind all the operations together under the ‘main’ function.

public class InterchangeDiagonals {    public static int matrix_size = 3;    public static void main (String[] args) {       int input_matrix[][] = {          {4, 5, 6},          {1, 2, 3},          {7, 8, 9}       };       System.out.println("The matrix is defined as: ");       for (int i = 0; i < matrix_size; i++) {          for (int j = 0; j < matrix_size; j++) {             System.out.print(input_matrix[i][j] + " ");          }          System.out.println();       }       for (int i = 0; i < matrix_size; ++i)          if (i != matrix_size / 2) {             int temp = input_matrix[i][i];             input_matrix[i][i] = input_matrix[i][matrix_size - i - 1];             input_matrix[i][matrix_size - i - 1] = temp;          }          System.out.println("nThe matrix after interchanging the elements: ");          for (int i = 0; i < matrix_size; ++i) {             for (int j = 0; j < matrix_size; ++j)                System.out.print(input_matrix[i][j]+" ");             System.out.println();          }       } } Output The matrix is defined as: 4 5 6 1 2 3 7 8 9 The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7 Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class InterchangeDiagonals {    public static int matrix_size = 3;    static void interchange_diagonals(int input_matrix[][]) {       for (int i = 0; i < matrix_size; ++i)       if (i != matrix_size / 2) {          int temp = input_matrix[i][i];          input_matrix[i][i] = input_matrix[i][matrix_size - i - 1];          input_matrix[i][matrix_size - i - 1] = temp;       }       System.out.println("nThe matrix after interchanging the elements: ");       for (int i = 0; i < matrix_size; ++i) {          for (int j = 0; j < matrix_size; ++j)          System.out.print(input_matrix[i][j]+" ");          System.out.println();       }    }    public static void main (String[] args) {       int input_matrix[][] = {          {4, 5, 6},          {1, 2, 3},          {7, 8, 9}       };       System.out.println("The matrix is defined as: ");       for (int i = 0; i < matrix_size; i++) {          for (int j = 0; j < matrix_size; j++) {             System.out.print(input_matrix[i][j] + " ");          }          System.out.println();       }       interchange_diagonals(input_matrix);    } } Output The matrix is defined as: 4 5 6 1 2 3 7 8 9 The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7

How To Get Particular Date Records From Time Stamp In Android Sqlite?

   android:layout_width = “match_parent”    android:layout_height = “match_parent”    tools:context = “.MainActivity”    <EditText       android:id = “@+id/name”       android:layout_width = “match_parent”       android:hint = “Enter Name”    <EditText       android:id = “@+id/salary”       android:layout_width = “match_parent”       android:inputType = “numberDecimal”       android:hint = “Enter Salary”    <LinearLayout       android:layout_width = “wrap_content”       <Button          android:id = “@+id/save”          android:text = “Save”          android:layout_width = “wrap_content”       <Button          android:id = “@+id/refresh”          android:text = “Refresh”          android:layout_width = “wrap_content”       <Button          android:id = “@+id/udate”          android:text = “Update”          android:layout_width = “wrap_content”       <Button          android:id = “@+id/Delete”          android:text = “DeleteALL”          android:layout_width = “wrap_content”    <ListView       android:id = “@+id/listView”       android:layout_width = “match_parent” import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity {    Button save, refresh;    EditText name, salary;    private ListView listView;    @Override    protected void onCreate(Bundle readdInstanceState) {       super.onCreate(readdInstanceState);       setContentView(R.layout.activity_main);       final DatabaseHelper helper = new DatabaseHelper(this);       final ArrayList array_list = helper.getAllCotacts();       name = findViewById(R.id.name);       salary = findViewById(R.id.salary);       listView = findViewById(R.id.listView);       final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,       android.R.layout.simple_list_item_1, array_list);       listView.setAdapter(arrayAdapter);          @Override             if (helper.delete()) {                Toast.makeText(MainActivity.this, “Deleted”, Toast.LENGTH_LONG).show();             } else {                Toast.makeText(MainActivity.this, “NOT Deleted”, Toast.LENGTH_LONG).show();             }          }       });          @Override             if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {                if (helper.update(name.getText().toString(), salary.getText().toString())) {                   Toast.makeText(MainActivity.this, “Updated”, Toast.LENGTH_LONG).show();                } else {                   Toast.makeText(MainActivity.this, “NOT Updated”, Toast.LENGTH_LONG).show();                }             } else {                name.setError(“Enter NAME”);                salary.setError(“Enter Salary”);             }          }       });          @Override             array_list.clear();             array_list.addAll(helper.getAllCotacts());             arrayAdapter.notifyDataSetChanged();             listView.invalidateViews();             listView.refreshDrawableState();          }       });          @Override             if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {                if (helper.insert(name.getText().toString(), salary.getText().toString())) {                   Toast.makeText(MainActivity.this, “Inserted”, Toast.LENGTH_LONG).show();                } else {                   Toast.makeText(MainActivity.this, “NOT Inserted”, Toast.LENGTH_LONG).show();                }             } else {                name.setError(“Enter NAME”);                salary.setError(“Enter Salary”);             }          }       });    } }

Step 4 − Add the following code to src/ DatabaseHelper.java

package com.example.andy.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.IOException; import java.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper {    public static final String DATABASE_NAME = "salaryDatabase5";    public static final String CONTACTS_TABLE_NAME = "SalaryDetails";    public DatabaseHelper(Context context) {       super(context,DATABASE_NAME,null,1);    }    @Override    public void onCreate(SQLiteDatabase db) {       try {          db.execSQL(             "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary                      text,datetime default current_timestamp )"          );       } catch (SQLiteException e) {          try {             throw new IOException(e);          } catch (IOException e1) {             e1.printStackTrace();          }       }    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {       db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);       onCreate(db);    }    public boolean insert(String s, String s1) {       SQLiteDatabase db = this.getWritableDatabase();       ContentValues contentValues = new ContentValues();       contentValues.put("name", s);       contentValues.put("salary", s1);       db.replace(CONTACTS_TABLE_NAME, null, contentValues);       return true;    }    public ArrayList getAllCotacts() {       SQLiteDatabase db = this.getReadableDatabase();       res.moveToFirst();       while(res.isAfterLast() = = false) {          array_list.add(res.getString(res.getColumnIndex("fullname")));          res.moveToNext();       }       return array_list;    }    public boolean update(String s, String s1) {       SQLiteDatabase db = this.getWritableDatabase();       db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"', "+ "salary = "+"'"+s1+"'");       return true;    }    public boolean delete() {       SQLiteDatabase db = this.getWritableDatabase();       db.execSQL("DELETE from "+CONTACTS_TABLE_NAME);       return true;    }

Golang Program To Get Characters From A String Using The Index

In Golang, there are various methods to get characters from a string with the help of an index. In this article, we are using external functions as well as by using internal functions defined in the go language.

Method 1: Using User-Defined Function

In this method, the function that we create will take the string whose character is to be determined along with the integer type index of the string and will return the character of the string present at that index.

Algorithm

Step 1 − First, we need to import the fmt package.

Step 2 − Then, create a function that will take the string whose character is to be determined as an argument along with the index.

Step 3 − Start the main() function.

Step 4 − Inside the main() initialize a variable of type string and assign a value to it.

Step 5 − Print the variable on the screen.

Step 6 − Initialize a variable of type int and assign it an index value

Step 7 − Now, call the getChar() function by passing the character as well as the index as arguments to the function.

Step 8 − Store the result obtained by the function in a variable in string format.

Step 9 − Print this value on the screen by using fmt.Println() function.

Example

In this example we will use a user defined external function to get the characters from the strings

package main import "fmt" func getChar(str string, index int) rune { return []rune(str)[index] } func main() { var str string = "Prevention is better than cure" fmt.Println("The given string is:", str) var index int = 24 var result string = string(getChar(str, index)) fmt.Println("The character at index", index, "is:", result) } Output The given string is: Prevention is better than cure The character at index 24 is: n Method 2: Using Split() Function

We will use the internal function in order to get the array of characters present in the string then by using the index we can grab the character value present at that index.

Syntax func Split(str, sep string) []string

Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.

func Index(s, substr string) int

The index() function is present in strings package and is used to get the index of the first occurrence of a given substring. The function takes two values as arguments. One is the string and other is the substring whose occurrence is to be detected. The function then returns the first occurrence of that substring in integer format.

Algorithm

Step 1 − First, we need to import the fmt and strings package.

Step 2 − Then, start the main() function. Inside the main() initialize a variable of type string and assign a value to it.

Step 3 − Further, print the string on the screen and assign a variable of type int and store an integer value at which the character is to be obtained.

Step 4 − Now, use the split() function present in strings package to get the array of characters of the given string.

Step 5 − Now, use the index initialized above to get the character present at that value from the array of characters and store that character in a separate variable.

Step 6 − We have now achieved the character that we wanted to get. Print the character on the screen by using fmt.Println() function.

Example 1

In this example we will use the split() function present in strings package in order to convert the characters from the string.

package main import ( "fmt" "strings" ) func main() { var str string = "Prevention is better than cure" fmt.Println("The given string is:", str) var index int = 7 chars := strings.Split(str, "") var result string = chars[index] fmt.Println("The character at index", index, "is:", result) } Output The given string is: Prevention is better than cure The character at index 7 is: i Example 2 package main import ( "fmt" "strings" ) func main() { var str string = "Prevention is better than cure" fmt.Println("The given string is:", str) var index int = 17 var result string = string(str[strings.Index(str, string(str[index]))]) fmt.Println("The character at index", index, "is:", result) } Output The given string is: Prevention is better than cure The character at index 17 is: t Conclusion

We have successfully compiled and executed a Go language Program to get characters from a string using the index along with examples. Here we have compiled three examples in the first one we are using an external function to achieve the result while in the second and third we are using library functions present in go language for the same.

Java Program To Calculate Length Of Chord Of The Circle

A circle is a round shape two-dimensional diagram which has no corners. Every circle has an origin point and every point on the circle maintains equal distance from the origin. The distance between the origin and a point in a circle is known as Radius of the circle. And similarly, if we draw a line from one edge to another edge of the circle and the origin is held in the middle of it, that line is known as diameter of the circle. Basically, the diameter is double of the length of the radius.

Chord of the circle refers to a line touching from one endpoint of circle to another end point of circle. Or simply we can say a chord refers to the line whose endpoints lie on the circle. A chord divides the circle into two parts.

As per the problem statement we have to find the length of the chord when the radius of circle and angle subtended at centre by the chord is given.

Formula to find length of chord −

Length = 2 * r * sin(a/2)

Where, ‘r’ refers to the radius of the circle and ‘a’ refers to the angle subtended at centre by the chord.

So, let’s explore.

To show you some instances − Instance-1 Let say radius (r) of circle is 3. And angle (a) subtended at centre by the chord is 60 Then by using the formula, length of the chord is 5.19. Instance-2 Let say radius (r) of circle is 4. And angle (a) subtended at centre by the chord is 50 Then by using the formula, length of the chord is 6.12. Instance-3 Let say radius (r) of circle is 4. And angle (a) subtended at centre by the chord is 40. Then by using the formula, length of the chord is 5.1. Algorithm

Step-1 − Get the radius of circle and angle at the centre subtended by the chord either by static input or by user input.

Step-2 − Find the length of the chord by using the formula.

Step-3 − Print the result.

Multiple Approaches

We have provided the solution in different approaches.

By Using Static Input Values.

By Using User Input Values.

Let’s see the program along with its output one by one.

Approach-1: By Using Static Input Value

In this approach, we initialize the radius and angle value in the program. Then by using the algorithm we can find the length of the chord.

Example public class Main { public static void main(String[] args) { double r = 4; double a = 40; double length = 2 * r * Math.sin(a * (3.14 / 180)); System.out.println("Length of Chord: "+length); } } Output Length of Chord: 5.140131589369607 Approach-2: By Using User Defined Method with Static Input Value.

In this approach, we take user input of radius and angle value in the program. Then call a user defined method by passing these values as parameters and inside the method by using the algorithm we can find the length of the chord.

Example public class Main { public static void main(String[] args) { double r = 4; double a = 40; length_of_chord(r, a); } static void length_of_chord(double r, double a) { double length = 2 * r * Math.sin(a * (3.14 / 180)); System.out.println("Length of Chord: "+length); } } Output Length of Chord: 5.140131589369607

In this article, we explored how to find the length of the chord when the radius ofcircle and angle subtended by chord to centre is given by using different approaches in Java.

Update the detailed information about Java Program To Get Year From Date on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!