Available method in java

Java 8 method reference example

In Java 8, we can refer a method from class or object using class::methodName type syntax. Let’s learn about different types of available method references in java 8.

Table of Contents 1. Types of Method References 2. Reference to static method - Class::staticMethodName 3. Reference to instance method from instance - ClassInstance::instanceMethodName 4. Reference to instance method from class type - Class::instanceMethodName 5. Reference to constructor - Class::new

1. Types of method references

Java 8 allows four types of method references.

Method Reference Description Method reference example
Reference to static method Used to refer static methods from a class Math::max equivalent to Math.max(x,y)
Reference to instance method from instance Refer to an instance method using a reference to the supplied object System.out::println equivalent to System.out.println(x)
Reference to instance method from class type Invoke the instance method on a reference to an object supplied by the context String::length equivalent to str.length()
Reference to constructor Reference to a constructor ArrayList::new equivalent to new ArrayList()

2. Method reference to static method – Class::staticMethodName

An example to use Math.max() which is static method.

List integers = Arrays.asList(1,12,433,5); Optional max = integers.stream().reduce( Math::max ); max.ifPresent(value -> System.out.println(value));

3. Method reference to instance method from instance – ClassInstance::instanceMethodName

In above example, we use System.out.println(value) to print the max value found. We can use System.out::println to print the value.

List integers = Arrays.asList(1,12,433,5); Optional max = integers.stream().reduce( Math::max ); max.ifPresent( System.out::println );

4. Method reference to instance method from class type – Class::instanceMethodName

In this example, s1.compareTo(s2) is referred as String::compareTo .

List strings = Arrays .asList("how", "to", "do", "in", "java", "dot", "com"); List sorted = strings .stream() .sorted((s1, s2) -> s1.compareTo(s2)) .collect(Collectors.toList()); System.out.println(sorted); List sortedAlt = strings .stream() .sorted(String::compareTo) .collect(Collectors.toList()); System.out.println(sortedAlt);
[com, do, dot, how, in, java, to] [com, do, dot, how, in, java, to]

5. Reference to constructor – Class::new

The first method can be updated to create a list of integers from 1 to 100. Using lambda expression is rather easy. To create a new instance of ArrayList , we have use ArrayList::new .

List integers = IntStream .range(1, 100) .boxed() .collect(Collectors.toCollection( ArrayList::new )); Optional max = integers.stream().reduce(Math::max); max.ifPresent(System.out::println);

That’s 4 type of method references in java 8 lambda enhancements.

Источник

Java.io.FileInputStream.available() Method

The java.io.FileInputStream.available() method returns number of remaining bytes that can be read from this input stream without blocking by the next method call for this input stream. The next method call can also be the another thread.

Declaration

Following is the declaration for java.io.FileInputStream.available() method −

Parameters

Return Value

The methods returns and estimated of the number of remaining bytes that can be read from this input stream without blocking.

Exception

IOException − If the file input stream has been closed by calling close or any I/O error occurs.

Example

The following example shows the usage of java.io.FileInputStream.available() method.

package com.tutorialspoint; import java.io.IOException; import java.io.FileInputStream; public class FileInputStreamDemo < public static void main(String[] args) throws IOException < FileInputStream fis = null; int available = 0; int i = 0; try < // create new file input stream fis = new FileInputStream("C://test.txt"); // read till the end of the stream while((i = fis.read())!=-1) < // available bytes available = fis.available(); // convert integer to character char c = (char)i; // prints System.out.print("Available: "+available); System.out.println("; Read: "+c); >> catch(Exception ex) < // if an I/O error occurs ex.printStackTrace(); >finally < // releases all system resources from the streams if(fis!=null) < fis.close(); >> > >

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program −

Читайте также:  Java native static methods

Let us compile and run the above program, this will produce the following result −

Available: 5; Read: A Available: 4; Read: B Available: 3; Read: C Available: 2; Read: D Available: 1; Read: E Available: 0; Read: F

Источник

Method In Java

Method In Java: Welcome to another new core Java tutorial series post. In this article, we will learn about Java methods in detail, like how we can define the Java method & how we can use the Java method in your Java program with the help of real-time examples.

Java is a widely used object-oriented programming language that has gained immense popularity due to its robustness, platform independence, and security features. Java supports various programming paradigms, including procedural, functional, and object-oriented programming.

Java’s object-oriented programming approach is based on principles of abstraction, encapsulation, inheritance, and polymorphism. One of the key aspects of Java programming is its support for methods, which are a fundamental building block of any Java program.

In Java, a method is a block of code that performs a specific task and can be called by other program parts. Methods in Java are used for code reusability, modularization, and abstraction.

In this article, we will explore the basics of methods in Java, how to define them, call them, and use them in a Java program. We will also discuss different types of methods, method parameters, and return values.

Define Method In Java

In Java, a method is a block of code that performs a specific task and can be called by other parts of a Java program. Methods are a fundamental building block of Java programming and are used for code reusability, modularization, and abstraction.

The methods consist of a method signature and a method body. The method signature includes the method’s name, return type, and parameters, while the method body contains the code that performs the specific task.

When a method is called, the program executes the code in the method body, and the method may return a value or not, depending on the return type. Methods in Java can be defined inside a class and accessed only by objects of that class or by the class itself.

They can also be defined with different access modifiers, such as public, private, and protected, which control their accessibility from other parts of the program.

Type Of Method In Java

There are mainly two types of methods available in Java Based on the Creation or availability. These methods are categorized according to some attributes. Does a user define the method, or is the method available in the standard library?

Based on that, methods divided into two types, that is:

Standard Library Method In Java

The Standard Library Methods methods are nothing but the built-in methods, which are already available inside the Java standard libraries, which come with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

Читайте также:  Php двумерный массив в таблице

Some Examples of Standard Library Methods are:

  • Print(): This method is available inside the java.io.PrintSteam package. This print(“….”) method prints in the console. Whatever you will write inside the quotation marks will print inside the console.
  • Sqrt (): This method belongs to the math class. It will return the square root of the given number.

User-Defined Method In Java

A user-defined method in Java is a method that the programmer creates to perform a specific task within a Java program. Unlike built-in methods already included in Java, user-defined methods are created by the programmer and tailored to the program’s specific needs.

How To Create Method In Java?

Creating a method in Java involves defining the method’s name, return type, and parameters. The method’s name should describe the task it performs, while the return type specifies the data type it returns. The parameters are used to pass values to the method, which the method can then use to perform its task.

If we try to understand the components of a method, then we will find mainly five components in methods, and those are:

A. Modifier: By using Access Modifiers, we define the access types. That means where we can access the method. In Java, we have four different access specifiers are there:

  • Public: that means we can access the method all over the application
  • Protected means that methods are accessible within the class and in its subclasses.
  • Private: That method is accessible within the class only.
  • Default: If you do not define access specifiers to a method, Java programming language takes default as an access specifier. These methods are accessible within the class and the package.

B. Return Type: It represents what type of value that specific method will return, and sometimes it may be void also. At that time, it will not return anything.
C. Method Name: We are defining a method name with this. And by using the method name, we can access that specific method.
D. Parameter list: This Field is used to pass some values to the method. If you give more than one value to a method, then we use a comma to separate between two parameters. For Each parameter, We have to mention the data type and variable name within an unclosed parenthesis. If no parameter exists, then we have to use empty parenthesis.
E. Method Body: This is the area between two braces. Whatever operation you need to perform, those codes or statements should be written inside the braces.

Syntax of Method

Method In Java

From the above image, you can notice we have the following:

  • public static − modifier
  • int − return type
  • methodName − the name of the method
  • a, b − formal parameters
  • int a, int b − list of parameters

How to Name a Method ( Method Naming Convention )

The method name is always a single word; sometimes, the name begins with a lowercase verb followed by an adjective or noun. There is a naming convention for methods like after the first-word first letter of words should be in the capital letter. For Example softwareTestingo, findElement

Читайте также:  Php how to get current time

Note: The method must have a unique name within the class, but sometimes a class can have multiple methods with the same name but different parameters, called method overloading.

How to Call Java Method

Suppose you have defined a method, and later, you want to use that method. So, to use that method, you need to call that method. Let’s understand how to call a method.

This statement is called myMethod(), which was declared earlier.

  • While Java executes the program code, it encounters myMethod(); in the code.
  • The execution then branches to the myFunction() method and executes code inside the method’s body.
  • After the execution of the code inside the method body, the program returns to the original state and executes the next statement.

Java Method Example

package java_Basics; public class Method_Example < public static void main(String[] args) < System.out.println("Going to Call static method myMethod()"); // method call myMethod(); System.out.println("myMethod was executed successfully!"); >// method definition private static void myMethod() < System.out.println("Printing from inside myMethod()!"); >>

Various Other Method Types in Java

But if we are looking based on the purpose and functionality, we can find several types of methods in Java. Here we tried to list some of the most common types of methods in Java are:

Instance Methods: These are the most common types of methods in Java and are associated with an instance of a class. They are used to access and modify instance variables and perform specific tasks related to the object. Instance methods are defined without the static keyword and can access non-static variables and methods.

package com.softwaretestingo.Basic; class Class_Rectangle < private int length; private int width; public void setDimensions(int len, int wid) < length = len; width = wid; >public void getArea() < int area=length * width; System.out.println("The Area is: "+area); >> public class InstanceMethodEx < public static void main(String[] args) < Class_Rectangle obj=new Class_Rectangle(); obj.setDimensions(10, 20); obj.getArea(); >>

Static Methods: These methods are associated with a class rather than an instance of a class. They are used to perform tasks that do not require access to instance variables or methods. Static methods are defined using the static keyword and can only access static variables and methods.

package com.softwaretestingo.Basic; public class StaticMethodEx < //Static Variable static int a=10; //Static Method static void display() < System.out.println("The Static Value Of a Is: "+a); >public static void main(String[] args) < display(); >>

Constructors: Constructors are special methods used to initialize objects when they are created. They have the same name as the class and do not have a return type. Constructors can be overloaded, allowing a class of multiple constructors with different parameters.

package com.softwaretestingo.Basic; class cEx < String name; int id; public cEx(String name, int id) < this.name=name; this.id=id; >> public class ConstructMethodEx < public static void main(String[] args) < cEx obj=new cEx("SoftwareTestingo", 5); System.out.println("Name :" + obj.name + " and Id :" + obj.id); >>

Getter and Setter Methods: Getter methods are used to retrieve the value of an instance variable, while setter methods are used to set or modify the value of an instance variable. These methods are often used to ensure encapsulation and data hiding in object-oriented programming.

These two getters and setter methods are two different types of Instance methods.

Accessor Method (Getters)

Источник

Оцените статью