Java – AppDividend https://appdividend.com Latest Code Tutorials Mon, 16 Sep 2019 09:54:30 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Java – AppDividend https://appdividend.com 32 32 Concat() In Java Example | Java String Concat() Method https://appdividend.com/2019/09/16/concat-in-java-example-java-string-concat-method/ https://appdividend.com/2019/09/16/concat-in-java-example-java-string-concat-method/#respond Mon, 16 Sep 2019 09:46:33 +0000 http://localhost/wordpress/?p=11265 Concat() In Java Example | Java String Concat() Method

Concat() In Java Example | Java String Concat() Method is today’s topic. Java string concat method is used to concatenate two or more than two strings to a single string. This method mainly appends the string at the end of the main string. For example: If we have two strings, “Hello” and “World” and we […]

The post Concat() In Java Example | Java String Concat() Method appeared first on AppDividend.

]]>
Concat() In Java Example | Java String Concat() Method

Concat() In Java Example | Java String Concat() Method is today’s topic. Java string concat method is used to concatenate two or more than two strings to a single string. This method mainly appends the string at the end of the main string. For example: If we have two strings, “Hello” and “World” and we want to concatenate them, then the result will be HelloWorld.”

Concat() In Java Example

In Java language, the string concatenation forms the new string that is a combination of the multiple strings. There are two ways to concat the string in Java:

  1. By + (string concatenation) operator
  2. By concat() method

Java String concat() method concatenates one string to an end of another string. The concat() method returns a string with the value of the string passed into the method, appended to the end of the string.

Syntax

public String concat(String str)

Here str is the string to be concatenated at the end of the first string.

The method returns a single string by concatenating more than one strings.

Example Of String Concatenation

Concatenate two strings

See the following code.

class Concat {
	public static void main(String args[]) {
		String s1 = "Hello everyone ";
		String s2 = "welcome to AppDividend";
		// We are using concat()
		s1 = s1.concat(s2); // will append s2 at the end of s1
		System.out.println(s1);
	}
}

See the output.

Concat() In Java Example

Concatenate more than two strings

See the following code.

class Concat {
	public static void main(String args[]) {
		String s1 = "Hello everyone ";
		String s2 = "welcome to";
		// We are using concat()
		// will append s2 at the end of s1 and then AppDividend
		s1 = s1.concat(s2).concat(" AppDividend");
		System.out.println(s1);
	}
}

See the output.

Java String Concat() Method

Java String Concat() Method Program

See the following code.

public class ConcatEx {
	public static void main(String[] args) {
		String str1 = "Hello";
		String str2 = "AppDividend";
		String str3 = "Reader";
		
                // Concatenating Space among strings
		String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
		System.out.println(str4);
		
                // Concatenating Special Chars
		String str5 = str1.concat("!!!");
		System.out.println(str5);
		String str6 = str1.concat("@").concat(str2);
		System.out.println(str6);
	}
}

See the output.

Hello AppDividend Reader
Hello!!!
Hello@AppDividend

Finally, Concat() In Java Example | Java String Concat() Method is over.

Recommended Posts

Java Method Overloading Example

Wrapper Class in Java Tutorial

Java Object Class Tutorial With Example

this keyword in Java Tutorial With Example

Runnable Interface in Java Example

The post Concat() In Java Example | Java String Concat() Method appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/16/concat-in-java-example-java-string-concat-method/feed/ 0
charAt() In Java Example | Java String charAt() Method https://appdividend.com/2019/09/16/charat-in-java-example-java-string-charat-method/ https://appdividend.com/2019/09/16/charat-in-java-example-java-string-charat-method/#respond Mon, 16 Sep 2019 08:51:58 +0000 http://localhost/wordpress/?p=11252 charAt() In Java Example | Java String charAt() Method

charAt() In Java Example | Java String charAt() Method is today’s topic. Java charAt() is a method of string which helps us find the position of any character in the string. The index that we have to put should be in between 0 to (length_of_string – 1). For example, s.charAt(0) would return the first character […]

The post charAt() In Java Example | Java String charAt() Method appeared first on AppDividend.

]]>
charAt() In Java Example | Java String charAt() Method

charAt() In Java Example | Java String charAt() Method is today’s topic. Java charAt() is a method of string which helps us find the position of any character in the string. The index that we have to put should be in between 0 to (length_of_string – 1). For example, s.charAt(0) would return the first character of a string represented by instance s. Java String charAt method throws an IndexOutOfBoundsException if an index value passed in a charAt() method is less than 0 or greater than or equal to a length of the string (index<0|| index>=length()).

charAt() In Java Example

The java.lang.String.charAt() method returns a char value at a specified index. An index ranges from 0 to length() – 1. The first char value of a sequence is at index 0, the next at index 1, and so on, as for array indexing.

Syntax:

character = string_name.charAt(index_position)

So, there is one parameter in charAt() which is the index of string.

Various Example of charAt()

Find character of at any given index:

In this method, we are going to find the position of any character in the string.

class CharAt {
	public static void main(String args[]) {
		String str = "Welcome to AppDividend";
		// This will return the first char of the string
		char ch1 = str.charAt(0);
		// This will return the 7th char of the string
		char ch2 = str.charAt(6);
		// This will return the 12th char of the string
		char ch3 = str.charAt(11);
		System.out.println("Character at 0 index is: " + ch1);
		System.out.println("Character at 7th index is: " + ch2);
		System.out.println("Character at 12th index is: " + ch3);
	}
}

See the following output.

 

charAt() In Java

IndexOutOfBoundsException

This situation happens when we enter the wrong index position of any string. 

Suppose we have a string of length 5, so if we write charAt(10) then there is no such character at that position. So we will get IndexOutOfBoundExpection.

See the following program.

class CharAt {
	public static void main(String args[]) {
		String str = "Welcome to AppDividend";
		// here we are giving one index position which is not
		// present actuallu
		char ch = str.charAt(150);
		System.out.println(ch);
	}
}

See the output.

 

Java String charAt() Method

Print all characters of a string using charAt()

In this example, we print all the characters of a given string using charAt().

class CharAt {
	public static void main(String args[]) {
		String str = "Welcome to Appdividend";
		System.out.println("All the characters of the string are: ");
		for (int i = 0; i <= str.length() - 1; i++) {
			System.out.print(str.charAt(i) + " ");
		}
	}
}

See the output.

 

Print all characters of a string using charAt()

Count the occurrence of a character

In this example, we will use a charAt() method to count the occurrence of the particular character in the given string. Here we have the string, and we are counting the occurrence of character ‘B’ in the string.

public class JavaExample {
	public static void main(String[] args) {
		String str = "BeginnersBook";

		// initialized the counter to 0
		int counter = 0;

		for (int i = 0; i <= str.length() - 1; i++) {
			if (str.charAt(i) == 'B') {
				// increasing the counter value at each occurrence of 'B'
				counter++;
			}
		}
		System.out.println("Char 'B' occurred " + counter + " times in the string");
	}
}

Finally, charAt() In Java Example | Java String charAt() Method is over.

Recommended Posts

Transient Keyword In Java

Java Inner Class Tutorial

Serialization and Deserialization in Java Tutorial

Java File Class Tutorial

StringBuilder Class in Java Example

The post charAt() In Java Example | Java String charAt() Method appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/16/charat-in-java-example-java-string-charat-method/feed/ 0
Transient Keyword In Java Example | Java Transient Keyword Tutorial https://appdividend.com/2019/09/12/transient-keyword-in-java-example-java-transient-keyword-tutorial/ https://appdividend.com/2019/09/12/transient-keyword-in-java-example-java-transient-keyword-tutorial/#respond Thu, 12 Sep 2019 05:59:54 +0000 http://localhost/wordpress/?p=11122 Transient Keyword In Java Example | Java Transient Keyword Tutorial

Transient Keyword In Java Example | Java Transient Keyword Tutorial is today’s topic. In Java, we have a keyword ‘transient’ which is used to ignore the mentioned variables form getting serialized. What this means is that, when we write our data in a file, then there may be some data that we do not want […]

The post Transient Keyword In Java Example | Java Transient Keyword Tutorial appeared first on AppDividend.

]]>
Transient Keyword In Java Example | Java Transient Keyword Tutorial

Transient Keyword In Java Example | Java Transient Keyword Tutorial is today’s topic. In Java, we have a keyword ‘transient’ which is used to ignore the mentioned variables form getting serialized. What this means is that, when we write our data in a file, then there may be some data that we do not want to be written in the file. So, while writing the object in a file, the data members of that object which are declared as transient will be ignored by the compiler. But some value must be stored at the place of that variable or else that may create problem while reading the object from the file. So, what the compiler does is that it ignores the actual value of that variable, and the default value assigned to that variable will be stored in the file.

Transient Keyword In Java

The modifier transient in java can be applied to the field members of the class to turn off serialization on these field members. Every field marked as a transient will not be serialized.

You use a transient keyword to indicate to the java virtual machine that the transient variable is not part of a persistent state of the object.

The transient keyword plays a vital role to meet the security constraints. There are numerous real-life examples where we don’t want to store the private data in the file.

Another usecase of transient keyword is not to serialize a variable whose value can be calculated based on other serialized objects or system such as an age of a person, current date, etc.

Important points to note

The transient keyword is used during serialization.

It is used for the variables which we do not want to serialize.

To make your variable transient, your class must implement the Serializable interface.

Using the transient keyword with the variables which are static or final is of no use. However, an error is not thrown by the compiler in such cases.

It helps maintain the privacy of confidential data.

For example, refer to the following program code.

import java.io.*;

class Login_Details implements Serializable {
    String name;
    int age;
    String email;
    transient String password;

    public Login_Details(String name, int age, String email, String password) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.password = password;
    }
}

public class Transient1 {
    public static void main(String[] args) throws Exception {
        Login_Details obj = new Login_Details("Harry", 18, "harry123@xyz.com", "TRANSIENT");
        FileOutputStream login_details = new FileOutputStream("login_details.txt");
        ObjectOutputStream out = new ObjectOutputStream(login_details);
        out.writeObject(obj);
        out.flush();
        out.close();
        login_details.close();
        System.out.println("Details saved");
    }
}

See the output.

 

 

Transient Keyword In Java Example

Transient Keyword

See the other program.

import java.io.*;

public class Transient2 {
    public static void main(String[] args) throws Exception {
        ObjectInputStream in = new ObjectInputStream((new FileInputStream("login_details.txt")));
        Login_Details obj = (Login_Details) in.readObject();
        System.out.println("NAME: " + obj.name);
        System.out.println("AGE: " + obj.age);
        System.out.println("EMAIL: " + obj.email);
        System.out.println("PASSWORD: " + obj.password);
    }
}

See the output.

 

Transient

Transient with final

I am talking about the use of transient with a final keyword correctly because it behaves differently in different situations which are not generally the case with other keywords in Java.

For making this concept practical, I have modified the Employee class as below:

private String           firstName;
private String           lastName;

public final transient String confidentialInfo = "confidential";

public final transient Logger logger = Logger.getLogger("data");

Finally, Transient Keyword In Java Example | Java Transient Keyword Tutorial is over.

Recommended Posts

Java Set Example | Set Example In Java Tutorial

Java Continue Statement Example | Continue Statement Tutorial

Java BufferedReader Class Tutorial With Example

Java Vector Class Tutorial With Example From Scratch

Java Anonymous Inner Class Tutorial With Example

The post Transient Keyword In Java Example | Java Transient Keyword Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/12/transient-keyword-in-java-example-java-transient-keyword-tutorial/feed/ 0
Java Set Example | Set Example In Java Tutorial https://appdividend.com/2019/09/11/java-set-example-set-example-in-java-tutorial/ https://appdividend.com/2019/09/11/java-set-example-set-example-in-java-tutorial/#respond Wed, 11 Sep 2019 11:15:59 +0000 http://localhost/wordpress/?p=11110 Java Set Example | Set Example In Java Tutorial

Java Set Example | Set Example In Java Tutorial is today’s topic. In Java, Set is a collection of objects that contains no duplicate values. The following are the key features of a set. Set is the interface which extends Collection. It is the unordered collection of objects in which duplicate values cannot be stored. […]

The post Java Set Example | Set Example In Java Tutorial appeared first on AppDividend.

]]>
Java Set Example | Set Example In Java Tutorial

Java Set Example | Set Example In Java Tutorial is today’s topic. In Java, Set is a collection of objects that contains no duplicate values. The following are the key features of a set. Set is the interface which extends Collection. It is the unordered collection of objects in which duplicate values cannot be stored. Set is implemented by the HashSet, LinkedHashSet or TreeSet (sorted representation). 

Java Set Example

Set has various methods to add, remove clear, size, etc. to enhance the usage of an interface. Set also adds the stronger contract on a behavior of the equals and hashCode operations, allowing the Set instances to be compared meaningfully even if their implementation types differ.

Features of Set in Java

A Set is an interface which extends the Collection interface. An Interface is the collection of abstract methods. A class in java implements the interface to inherit and define these abstract methods of the interface.)

The Set contains all unique values. I.e., The duplicate values cannot be stored in the Set. If you try to add any value into the set that is already present in it, it will simply skip adding those values again and will retain only one unique element as its every element. 

The Set interface is implemented by the following classes: HashSet, TreeSet, etc. 

What this means is that the HashSet class, the TreeSet class (and all the other capable classes) implement the interface Set and inherit its abstract members and now they can define these members in their body. Through this, these classes can implement the set properties and the collection properties. 

When the HashSet Class implements the Set, then we get our values in an unordered manner because the HashSet stores the values in the hashtable and while displaying the value, it shows the values according to the locations (nearest) in which they are stored.

See the code example.

import java.sql.SQLOutput;
import java.util.HashSet;
import java.util.Set;

public class Set_Demo1 {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<String>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

Features of Set

 

 

Here, you can see that the fruits displayed on the output are neither in the order in which they were entered nor they are in ascending or descending order (according to lexical order).

Is the TreeSet is implementing the Set, then you get the output in ascending order because, in the Background of the TreeSet class, it follows such algorithm which sorts the values in ascending order while storing them? See the following code.

import java.util.Set;
import java.util.TreeSet;

public class Set_Demo2 {
    public static void main(String[] args) {
        Set<String> fruits = new TreeSet<String>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

 

Features of Set

Here, you can see that the fruits displayed in the output are in ascending order according to their first letters.

A set follows all the properties of collections, but it also has some surplus features which makes it unique. The following are the key features which make a set different from other Collections.

  1. No duplicate elements.
  2. The mathematical sets can be well implemented using The Java Set. Operations like Set Union, Set6 Intersection and Set Difference can easily be performed using readymade methods, i.e. addAll() , retainAll() and removeAll(). 

The other properties of a set remain the same as all the rest of the Collections such as the Lists.

import java.util.Set;
import java.util.TreeSet;

public class SetDemo {
    public static void main(String[] args) {

        Set<Integer> setA = new TreeSet<Integer>();
        Set<Integer> setB = new TreeSet<Integer>();

        for (int i = 0; i < 20; i += 2)
            setA.add(i); // Numbers divisible by 2

        for (int i = 0; i < 20; i += 3)
            setB.add(i); // Numbers divisible by 3

        // Union of setA and setB
        Set<Integer> A_union_B = new TreeSet<>(setA);
        A_union_B.addAll(setB);
        System.out.println("Numbers Divisible by either 2 or 3 or both are: " + A_union_B);

        // Intersection of setA and setB
        Set<Integer> A_intersects_B = new TreeSet<>(setA);
        A_intersects_B.retainAll(setB);
        System.out.println("Numbers Divisible by both 2 and 3 are: " + A_intersects_B);

        // Difference of setA and setB
        Set<Integer> A_minus_B = new TreeSet<>(setA);
        A_minus_B.removeAll(setB);
        System.out.println("Numbers Divisible by 2 but not 3 are: " + A_minus_B);

        Set<Integer> B_minus_A = new TreeSet<>(setB);
        B_minus_A.removeAll(setA);
        System.out.println("Numbers Divisible by 3 but not 2 are: " + B_minus_A);
    }
}

See the output.

 

Set Example In Java Tutorial

Java Set Methods

Sr.No. Method & Description
1 add( )

It adds an object to the collection.

2 clear( )

It removes all objects from the collection.

3 contains( )

It returns true if a specified object is an element within the collection.

4 isEmpty( )

It returns true if the collection has no elements.

5 iterator( )

It returns the Iterator object for a collection, which may be used to retrieve the object.

6 remove( )

It removes the specified object from a collection.

7 size( )

It returns a number of elements in the collection.

Finally, the Java Set Example | Set Example In Java Tutorial is over.

Recommended Posts

Thread Pools In Java Example

Java List Interface Example

Java Merge Sort Program

Insertion Sort In Java Example

For-each Loop In Java Example

The post Java Set Example | Set Example In Java Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/11/java-set-example-set-example-in-java-tutorial/feed/ 0
Thread Pools In Java Example | Java Thread Pools Tutorial https://appdividend.com/2019/09/11/thread-pools-in-java-example-java-thread-pools-tutorial/ https://appdividend.com/2019/09/11/thread-pools-in-java-example-java-thread-pools-tutorial/#respond Wed, 11 Sep 2019 10:03:20 +0000 http://localhost/wordpress/?p=11097 Thread Pools In Java Example | Java Thread Pools Tutorial

Thread Pools In Java Example | Java Thread Pools Tutorial is today’s topic. It is an exciting topic of Java-related to multithreading that is to perform multiple tasks at the same time. Database and web server like Server Programs execute requests from various clients every day and the approach through which we can build new […]

The post Thread Pools In Java Example | Java Thread Pools Tutorial appeared first on AppDividend.

]]>
Thread Pools In Java Example | Java Thread Pools Tutorial

Thread Pools In Java Example | Java Thread Pools Tutorial is today’s topic. It is an exciting topic of Java-related to multithreading that is to perform multiple tasks at the same time. Database and web server like Server Programs execute requests from various clients every day and the approach through which we can build new thread whenever a request arrives. But things have a drawback, and its disadvantage is that at every request our server spends too much time and resources also used and as there are too many threads which are actively running this will directly result in memory out of reach. So to overcome this problem, we have to limit the number of threads which are actively running.

Thread Pools In Java

See the following figure.

 

Thread Pools In Java Example

Now the question in your mind is what thread pools are?

Thread pools are the ones who use the previous threads to perform current tasks through this we can solve our problem of resource thrashing and memory wasting.

It also saves the time of thread creation and hence in this way the response is very nice 

Threads are mapped to system-level- threads in Java which are directly refer to operating system resources.

Executors, Executor and executor service

Java provides an executor framework centered around the Executor interface. Its sub-interface that is executor services and the class names thread pool executor, implementing both the interfaces.

With the help of executor, we can handle the running object and send them to the executor to execute these things.

They don’t focus on the thread mechanics, but the main focus is on the task performance by the threads. The threads which will run are running sequentially not in a random manner.

ThreadPoolExecutor

Since Java 5, a Java concurrency API provides the mechanism Executor framework. This is around the Executor interface, its a sub-interface ExecutorService, and a ThreadPoolExecutor class that implements both of the interfaces.

ThreadPoolExecutor separates a task creation and its execution. With the ThreadPoolExecutor, you only have to implement the Runnable objects and send them to an executor. It is responsible for their execution, instantiation, and running with the necessary threads.

It goes beyond that and improves performance using the pool of threads. When you send the task to the executor, it tries to use the pooled thread for the execution of the task, to avoid continuous spawning of threads.

Methods of Executor thread Pool

#newFixedThreadPool(int)

A fixed-size thread pool has been generated.

#newCachedThreadPool()

Create a thread pool that creates a new thread.

#newSingleThreadExecutor()

When available. Create a single thread.

In a fixed thread pool, if the threads are not free and the tasks are pending, then they stand in a queue and wait for their turn.

Risks generated in ThreadPool

  1. Deadlock: It occurs in multithreading, and thread pool introduces another case of deadlock, one case is the threads waiting in the queue due to the unavailability of threads.
  2. Thread Leakage: Thread Leakage occurs when the threads are removed from the pool so that the task can be performed, but in that procedure, if the thread does not return to the pool this will cause thread leakage.
  3. The thrashing of resources: As we know if there are more demands in comparison to the possible things then there is starvation problem same occur with the thread if there are more threads in comparison to the actual optimize level then there is the problem of starvation.

Now you are thinking about what will be the size of the thread pool

The answer is that it depends on your processor and the nature of the tasks you are giving to your processor. For N-type processor system, we can generally take maximum efficiency is of N or N+1 thread pool. It is a fantastic application which we can use to handle our server.

See the following programming example.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class Thread {
  public static void main(String[] args) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    Runnable task = () -> {
      System.out.println("Executing Task At " + System.nanoTime());
    };

    System.out.println("Submitting task at " + System.nanoTime() + " to be executed after 10 seconds.");
    scheduledExecutorService.schedule(task, 10, TimeUnit.SECONDS);

    scheduledExecutorService.shutdown();
  }
}

See the output.

 

Java Thread Pools Tutorial

Custom thread pool implementation in Java

Java has a very robust thread pool functionality through the Executor framework. And you should not be creating your custom thread pool without an executor. I will vehemently discourage any such attempt.

Also, note that incorrect pooling or queue handling can result in deadlocks or resource thrashing as well. You can certainly avoid these problems with the Executor framework, which is well tested by the Java community.

Finally, Thread Pools In Java Example | Java Thread Pools Tutorial is over.

Recommended Posts

Deadlock in Java Example | Java Deadlock Tutorial

ConcurrentHashMap in Java Example | Java ConcurrentHashMap Tutorial

Java instanceof Operator Example | instanceof In Java

Java Operators Example | Operators In Java Tutorial

Immutable Class In Java Example

The post Thread Pools In Java Example | Java Thread Pools Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/11/thread-pools-in-java-example-java-thread-pools-tutorial/feed/ 0
Math class in Java Example | Java Math Class Tutorial https://appdividend.com/2019/09/11/math-class-in-java-example-java-math-class-tutorial/ https://appdividend.com/2019/09/11/math-class-in-java-example-java-math-class-tutorial/#respond Wed, 11 Sep 2019 08:04:16 +0000 http://localhost/wordpress/?p=11035 Math class in Java Example | Java Math Class Tutorial

Math class in Java Example | Java Math Class Tutorial is today’s topic. Several times we need to perform some mathematical functions in our program. Sometimes we can create separate methods for the same, but while making large and complex problems, we do not have time for doing so. So, to implement these functions in […]

The post Math class in Java Example | Java Math Class Tutorial appeared first on AppDividend.

]]>
Math class in Java Example | Java Math Class Tutorial

Math class in Java Example | Java Math Class Tutorial is today’s topic. Several times we need to perform some mathematical functions in our program. Sometimes we can create separate methods for the same, but while making large and complex problems, we do not have time for doing so. So, to implement these functions in our program, we can use the methods already defined in the Math class (which is present inside the java.lang.Math package).

Math class in Java

Using the Math class, we can implement methods like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs(), pow(), floor(), ciel(), round() etc. 

Importing Math Class

If we want to import Math class in java, we have to write the following code.

java.lang.math

Various Methods in Math Class

The following are the methods which you can directly implement in your program code using the Math class.

Method Working Description
Math.max() It takes two values as inputs and returns the maximum of two values.
Math.min() It takes two values as inputs and returns the minimum of two values.
Math.abs() It will take one value as input and return the absolute value for it.
Math.round() It is used to round-of the decimal numbers to the nearest integer value.
Math.sqrt() It takes one argument as input and returns the square root of that number.
Math.cbrt() It takes one argument as input and returns the cube root of that number.
Math.atan() It is used to return a trigonometric Arc Tangent value of the given value
Math.hypot() This method takes two double values as the arguments and returns sqrt(x2+y2) without any intermediate overflow or underflow.
Math.ceil() It is used in case of decimal or fraction values to find the smallest integer value that is greater than or equal to an argument passed to it.
Math.floor() It is also used in case of decimal or fraction values but to find the largest integer value that is lesser than or equal to the argument passed to it.
Math.getExponent() It is used to return an unbiased exponent used in the representation of a value.
Math.log() It takes a double value as input and returns the natural logarithm of that double value.
Math.log10() It takes a double value as input and is used to return the base 10 logarithm of that double value.
Math.log1p() It takes a double value as input and returns the natural logarithm of that double value.
Math.exp() It returns ‘e’ raised to the power of a double value, which is also known as the exponential of the number, where ‘e’ is Euler’s number, and it is approximately equal to 2.71828.
Math.expm1() It returns ‘e’ raised to the power of a double value, which is also known as the exponential of the number subtracted one from it.
Math.sin() It takes one double value as its argument and returns the trigonometric Sine value of a Given double value.
Math.cos() It takes one double value as its argument and returns the trigonometric Cosine value of a Given double value.
Math.tan() It takes one double value as its argument and returns a trigonometric Tangent value of the given double value.
Math.asin() It is used to return a trigonometric Arc Sine value of the given value.
Math.acos() It is used to return a trigonometric Arc Cosine value of the given value.
Math.sinh() It takes one double value as its argument and returns the hyperbolic Sine value of a Given double value.
Math.cosh() It takes one double value as its argument and returns the hyperbolic Cosine value of a Given double value.
Math.tanh() It takes one double value as its argument and returns the hyperbolic Tangent value of a Given double value.

The following program code is an example that implements some of the methods of the Math class in Java:

import java.lang.Math;

public class MathDemo {
    public static void main(String[] args) {

        double a1= 4;
        double a2= 100;
        double a3= -58;
        double a4= 60;

        System.out.println("Square root of a1= "+ Math.sqrt(a1));
        System.out.println("Square root of a2= "+ Math.sqrt(a2));

        System.out.println("Cube root of a4 "+ Math.cbrt(a4));

        System.out.println("Maximum of a1 and a4= "+ Math.max(a1,a4));
        System.out.println("Minimum of a2 and a3= "+ Math.min(a2,a3));

        System.out.println("The absolute value for a3= "+ Math.abs(a3));
	
	System.out.println("The 3rd Power value for a1= "+ Math.pow(a3,3));
	System.out.println("Log value of a1 is = "+ Math.log(a1));
	System.out.println("Log10 value of a1 is= "+ Math.log10(a1));
	System.out.println("Exp of a1 = "+ Math.exp(a1)); //return a power of 2
	
	// Now we will calculate trigonomatry values
	//First we have convert one value to radian
	// so here we will convert a4 to radian
	
	 double a = Math.toRadians(a4);
	System.out.println("Sine value of a is: " +Math.sin(a));    
         
        System.out.println("Cosine value of a is: " +Math.cos(a));  
          
        System.out.println("Tangent value of a is: " +Math.tan(a));  
	 
	// return the trigonometric arc sine of a      
        System.out.println("Sine value of a is: " +Math.asin(a));    
          
        // return the trigonometric arc cosine value of a  
        System.out.println("Cosine value of a is: " +Math.acos(a));  
          
        // return the trigonometric arc tangent value of a  
        System.out.println("Tangent value of a is: " +Math.atan(a));  
  
        // return the hyperbolic sine of a      
        System.out.println("Sine value of a is: " +Math.sinh(a));    
          
        // return the hyperbolic cosine value of a  
        System.out.println("Cosine value of a is: " +Math.cosh(a));  
          
        // return the hyperbolic tangent value of a  
        System.out.println("Tangent value of a is: " +Math.tanh(a));  
    }
}

See the following output.

 

Math class in Java Example

Finally, Math class in Java Example | Java Math Class Tutorial is over.

Recommended Posts

Java Dictionary Class Example | Dictionary Class In Java Tutorial

Nested class In Java Example | Java Nested Class Tutorial

Java Type Casting Example | Type Casting In Java Tutorial

Java Binary Search Program | Binary Search In Java Example

equalsIgnoreCase() In Java Example | Java String equalsIgnoreCase() Method

The post Math class in Java Example | Java Math Class Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/11/math-class-in-java-example-java-math-class-tutorial/feed/ 0
Java Dictionary Class Example | Dictionary Class In Java Tutorial https://appdividend.com/2019/09/04/java-dictionary-class-example-dictionary-class-in-java-tutorial/ https://appdividend.com/2019/09/04/java-dictionary-class-example-dictionary-class-in-java-tutorial/#respond Wed, 04 Sep 2019 10:29:16 +0000 http://localhost/wordpress/?p=11038 Java Dictionary Class Example | Dictionary Class In Java Tutorial

Java Dictionary Class Example | Dictionary Class In Java Tutorial is today’s topic. In java, we have a class Dictionary which helps us to form different key-value relationships. It is an abstract class which extends the Object class and is present in the java.util package. The Dictionary class is an abstract parent of any class, […]

The post Java Dictionary Class Example | Dictionary Class In Java Tutorial appeared first on AppDividend.

]]>
Java Dictionary Class Example | Dictionary Class In Java Tutorial

Java Dictionary Class Example | Dictionary Class In Java Tutorial is today’s topic. In java, we have a class Dictionary which helps us to form different key-value relationships. It is an abstract class which extends the Object class and is present in the java.util package. The Dictionary class is an abstract parent of any class, such as the Hashtable, which maps the keys to values. Every key and every value is the object in anyone.

Java Dictionary Class

Dictionary can also be termed as a list of pair values, where the pair consists of the key and the value. The relationship of the key to the values is somewhat similar to mapping. First, we map the key with the value, and then afterward, we can again retrieve the value with the help of the key.

Declaration

If we want to declare a Dictionary in java, we have to write the below method from java.util.Dictionary.keys().

public abstract Enumeration<K> keys()

Various Methods in Dictionary Packages

The following are the various methods that are predefined inside the java.util.Dictionary package.

S.No Method Description
1. put( key, value) 

The put() method takes two arguments as shown, and is used to map the key with the value and store it in the dictionary.

Syntax: public abstract V put(K key, V value)

Parameters:
-> key
-> value

Return:
key-value pair mapped in the dictionary.

2. get()

The get() method takes the key as the argument and returns the value that is mapped to it. If no value is mapped with the given key, it simply returns null.

Syntax: public abstract V get(Object key)

Parameters:
key – key whose mapped value we want

Return:
value mapped with the argument key.

3. elements()

The elements() method is used to represent all the values present inside the Dictionary. It is usually used with loop statements as they can then represent one value at a time.

Syntax: public abstract Enumeration elements()

Return:
value enumeration in the dictionary.

4.  keys()

As the elements() method returns the enumerated values present inside the dictionary; similarly, the keys() method returns the enumerated keys present inside the dictionary.

Syntax: public abstract Enumeration keys()

Return:
The key enumeration in the dictionary.

5.  isEmpty()

The isEmpty() method returns a boolean value, which is true if there are no key-value pairs present inside the Dictionary. If even any single key-value pair resides inside the dictionary, it returns false.

Syntax: public abstract boolean isEmpty()

Return:
It returns true if there is no key-value relation in the dictionary; else false.

6. remove(key)

The remove() method takes the key as its argument, and it simply removes both the key and the value mapped with it from the dictionary.

Syntax: public abstract V remove(Object key)

Parameters:
key: a key to be removed

Return:
The key enumeration in the dictionary.

7. size()

The size() method returns the total number of key-value pairs present inside the Dictionary.

Syntax: public abstract int size()

Return:
It returns the no. of key-value pairs in the Dictionary.

 

The following program code is an example of using Dictionaries in Java.

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

public class Dict {
  public static void main(String[] args) {

    Dictionary dictionary = new Hashtable();

    // put method
    dictionary.put("Apple", "A fruit");
    dictionary.put("Ball", "A round shaped toy");
    dictionary.put("Car", "A four wheeler vehicle designed to accomodate usually four people");
    dictionary.put("Dog", "An animal with four legs and one tail");

    // get method
    System.out.println("\nApple: " + dictionary.get("Apple"));
    System.out.println("Dog: " + dictionary.get("Dog"));
    System.out.println("Elephant: " + dictionary.get("Elephant"));
    System.out.println();

    // elements method
    for (Enumeration i = dictionary.elements(); i.hasMoreElements();) {
      System.out.println("Values contained in Dictionary : " + i.nextElement());
    }
    System.out.println();

    // keys method :
    for (Enumeration k = dictionary.keys(); k.hasMoreElements();) {
      System.out.println("Keys contianed in Dictionary : " + k.nextElement());
    }

    // isEmpty method
    System.out.println("\nThe dictionary is empty? " + dictionary.isEmpty());

    // remove method :
    dictionary.remove("Dog");

    // Checking if the value is removed or not
    System.out.println("\nDog: " + dictionary.get("Dog"));

    // size method
    System.out.println("\nSize of Dictionary : " + dictionary.size());
  }
}

See the output.

 

Java Dictionary Class Example

Finally, Java Dictionary Class Example | Dictionary Class In Java Tutorial is over.

Recommended Posts

Nested class In Java Example | Java Nested Class Tutorial

Java Type Casting Example | Type Casting In Java Tutorial

Java Interface Example | Interface in Java Tutorial For Beginners

HashMap in Java Tutorial With Example

Java ArrayList Example | ArrayList in Java Tutorial

Java Scanner Class Tutorial With Example | Scanner Class in Java

Java Constructor Tutorial With Example | Constructor in Java

The post Java Dictionary Class Example | Dictionary Class In Java Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/04/java-dictionary-class-example-dictionary-class-in-java-tutorial/feed/ 0
Nested class In Java Example | Java Nested Class Tutorial https://appdividend.com/2019/08/25/nested-class-in-java-example-java-nested-class-tutorial/ https://appdividend.com/2019/08/25/nested-class-in-java-example-java-nested-class-tutorial/#respond Sun, 25 Aug 2019 14:51:25 +0000 http://localhost/wordpress/?p=10884 Nested class In Java Example | Java Nested Class Tutorial

Nested class In Java Example | Java Nested Class Tutorial is today’s topic. In java, a Nested class is defined when a class is present/define within another class. The scope of the nested class is defined within the curly bracket. In java, it is possible to define the class within another class; such classes are […]

The post Nested class In Java Example | Java Nested Class Tutorial appeared first on AppDividend.

]]>
Nested class In Java Example | Java Nested Class Tutorial

Nested class In Java Example | Java Nested Class Tutorial is today’s topic. In java, a Nested class is defined when a class is present/define within another class. The scope of the nested class is defined within the curly bracket. In java, it is possible to define the class within another class; such classes are known as nested classes.

Nested class In Java

Nested Class enable you to logically group classes that are only used in one place; thus, it increases the use of encapsulation, and create more readable and maintainable code.

#Features of nested class

  1. The nested class can access the member of the upper class, but the upper class cannot access the member of the nested class in java.
  2.  A class is also called as the member of the enclosing class.
  3.  We can declare a nested class as private, public, protected, or default.

#Syntax

See the following syntax.

class outer {
  // statements of outer class
  class inner {
    // statements of inner class
  }
} // outer close

#Types of Nested Class

  1. Non-static nested class (inner class)
  2. Static nested class

#Non-static Nested class

A non-static nested class is also called as an inner class in which the inner class has all the rights to access the member of the outer class. The inner class can access the private, protected or default member of the outer class, but the reverse is not possible, i.e. an outer class cannot access the member of the inner class. The inner class is always created within the scope of the outer class.

It is again divided into two categories:

  1. local class
  2. anonymous class
  3. Method-local Inner Class

#Program for inner class

class outer {
  private int a = 1; // private member

  static int b = 2; // static member

  int c = 3; // non-static member

  class inner {
    void show() {
      System.out.println("private member of outer class=" + a);

      System.out.println("static member of outer class=" + b);
      System.out.println("non-static member of outer class=" + c);
    } // method close
  } // inner class close
} // outer class close

class nested {
  public static void main(String args[]) {
    outer obj = new outer();
    outer.inner obj1 = obj.new inner();
    obj1.show();
  }
}

See the output.

 

 

Nested class In Java

#Static nested class

A static nested class is a class that is defined within another class with a static modifier with the class name. As the class is defined with static modifier so it can access only the static member of the outer class but not the non-static member.

As with class methods and variables, the static nested class is associated with its outer class and like static class methods, the static nested class cannot refer directly to the instance variables or methods defined in its enclosing class. It can use them only through the object reference.

The static inner class is the nested class, which is the static member of the outer class. It can be accessed without instantiating an outer class, using other static members. Just like static members, the static nested class does not have access to the instance variables and methods of the outer class.

#Syntax

Outer classname.inner classname object_name=new outer classname.inner classname( );

#Program for static class

class outer {
  private static int a = 1;

  static int b = 2;

  int c = 3;

  static class inner {
    void show() {
      System.out.println("private member of outer class=" + a);
      System.out.println("static member of outer class=" + b);
      // System.out.println("non-static member of outer class="+c); //this statement
      // is not ligal as the innerclass is static and outerclass is non-static
    }
  }
}

class static_nested {
  public static void main(String args[]) {
    outer.inner obj = new outer.inner();
    obj.show();
  }
}

See the output.

 

Static nested class

#Difference between static and inner or non-static nested classes

  1. The static nested classes do not directly have access to the other members(non-static variables and methods) of an enclosing class because as it is static class, it needs the access to non-static members of its enclosing class through the object.
  2. Static classes cannot refer to non-static members of its enclosing class directly because of this restriction, and static nested classes are seldom used.
  3. Non-static nested classes or inner classes have access to all members(static and non-static variables and methods, including private) of its outer class and may refer to them directly in a same way that the other non-static members of the outer class do.

Finally, Nested class In Java Example | Java Nested Class Tutorial is over.

The post Nested class In Java Example | Java Nested Class Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/25/nested-class-in-java-example-java-nested-class-tutorial/feed/ 0
Java Type Casting Example | Type Casting In Java Tutorial https://appdividend.com/2019/08/19/java-type-casting-example-type-casting-in-java-tutorial/ https://appdividend.com/2019/08/19/java-type-casting-example-type-casting-in-java-tutorial/#respond Mon, 19 Aug 2019 10:52:08 +0000 http://localhost/wordpress/?p=10744 Java Type Casting Example | Type Casting In Java Tutorial

Java Type Casting Example | Type Casting In Java Tutorial is today’s topic. Suppose you want to assign the value of one data type into another variable of another data type, so there might be a case that they are not compatible with each other. To overcome this problem, we have one solution that we […]

The post Java Type Casting Example | Type Casting In Java Tutorial appeared first on AppDividend.

]]>
Java Type Casting Example | Type Casting In Java Tutorial

Java Type Casting Example | Type Casting In Java Tutorial is today’s topic. Suppose you want to assign the value of one data type into another variable of another data type, so there might be a case that they are not compatible with each other. To overcome this problem, we have one solution that we are going to learn today, called ‘Type Casting.’ In java, if both data types are compatible with each other, then it automatically has done its conversion, which is known as ‘Automatic type conversion.’

Java Type Casting

Typecasting is used to convert an object or variable of one type into another.

There are two types of typecasting in Java they are:

  1. Implicit Type Casting, known as Widening Type Casting
  2. Explicit Type Casting, also known as Narrowing Type Casting

We will learn about these two types of typecasting.

#Implicit Typecasting

This typecasting comes when the system automatically converts the data type of one variable into another if they are compatible. In other words, in this typecasting, the system only can convert lower range to a higher range.

For example, if we have one variable int x=10, and we want to convert it into long data type, we have to assign the value like this, long num=x simply. The system will automatically convert the value from int to long.

Always remember, in java we only can convert numeric type data type to another numeric type data type, means int to long or byte to int, etc. See the below chart from lower range to upper range of data type.

 

 

Implicit Typecasting

See the below programming example how the Widening or Automatic or Implicit type casting is done.

class Implicit {
	public static void main(String args[]) {
		int b = 150;
		// now we will convert it into long, and double
		long l = b;
		double d = b;
		System.out.println("Long value is " + l);
		System.out.println("Double value is " + d);
	}
}

See the following output.

 

Implicit

#Explicit Type Casting

Now suppose we have one variable which has a larger data type, let suppose in long, and we want it to be assigned to int. To do so, we have to apply explicit typecasting, also known as Narrowing Type Casting. 

Note that this is not automatic typecasting, we have to do explicit type casting manually.  To do so, we have to write code by following the below syntax.

new_operand = (new_data_type) current_operand;

For example, suppose we want to convert long x=555; to int num, so we have to write code like the following.

long x=555;
int num;
num = (int) x;

See the below diagram to know how we can apply explicit typecasting in the same type of data.

 

Explicit Type Casting

So, from the above diagram, we can see that a flow of explicit type casting is precisely the opposite of Implicit Type Casting.  Now we will see one example of explicit typecasting and how its work.

class Explicit {
	public static void main(String args[]) {
		double d = 500.4;
		long l = (long) d; // converting to Long
		int i = (int) d; // converting to int
		byte b = (byte) d; // converting to byte

		System.out.println("Vlaue in long: " + l);
		System.out.println("Value in int: " + d);
		System.out.println("Value in Byte: " + b);
	}
}

See the following output.

 

 

Explicit

From the above code, we can see that when we are going to convert the value of double to byte, its showing different value. Because the double data type has a maximum range of up to 0 to 255, so it reduced the number to modulo 256.

Also, note that you cannot convert a char value to int, because they are not compatible with each other.

While evaluating the expressions, an intermediate value may exceed the range of operands, and hence, an expression value will be promoted. Some conditions for type promotion are:

  1. Java automatically promotes the each byte, short, or char operand to int when evaluating the expression.
  2. If one operand is a long, float or double, the whole expression is promoted to long, float or double respectively.

So here, Java Type Casting Example | Type Casting In Java Tutorial is over.

The post Java Type Casting Example | Type Casting In Java Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/19/java-type-casting-example-type-casting-in-java-tutorial/feed/ 0
Java Binary Search Program | Binary Search In Java Example https://appdividend.com/2019/08/19/java-binary-search-program-binary-search-in-java-example/ https://appdividend.com/2019/08/19/java-binary-search-program-binary-search-in-java-example/#respond Mon, 19 Aug 2019 07:37:52 +0000 http://localhost/wordpress/?p=10721 Java Binary Search Program | Binary Search In Java Example

Java Binary Search Program | Binary Search In Java Example is today’s topic. We are going to learn about one of the fastest searching methods, which are Binary Search. This searching method is also known as half-interval search, logarithm search, or binary chop. Always remember, this searching method works only on a sorted array or […]

The post Java Binary Search Program | Binary Search In Java Example appeared first on AppDividend.

]]>
Java Binary Search Program | Binary Search In Java Example

Java Binary Search Program | Binary Search In Java Example is today’s topic. We are going to learn about one of the fastest searching methods, which are Binary Search. This searching method is also known as half-interval search, logarithm search, or binary chop. Always remember, this searching method works only on a sorted array or list. Binary search is used to search the key item from multiple items. Binary search is faster than a linear search.

Java Binary Search

In the case of binary search, array elements must be in ascending order. If you have an unsorted array, you can sort the array using Arrays.sort(arr) method. Binary Search works like the following.

Search the sorted array by repeatedly dividing the search interval in half.

Begin with the interval covering the whole array.

If a value of the search key is less than an element in the middle of the interval, narrow the interval to lower half.

Otherwise, narrow it to upper half. Repeatedly check until a value is found or an interval is empty.

#Procedure

The standard procedure of this search is; first, we have to take a sorted array, and then we have to compare the target value with the middle value of the sorted array.

If a target value is less than the middle value, then we will eliminate the remaining halves ( right side of the middle value ), and we will continue searching with the selected halves.

Then we will again take the middle value of the selected halves (left subarray) and compare, again we have to eliminate by comparing, and we will do so until we get our target value.

#Algorithm of Binary Search

1.   [Define variables]
     	ST = LB, LAST= UB; //LB means Lower Bound, UB= Upper Bound
     	MID = (ST+LAST)/2; //Middle Value
2.   Repeat 3 and 4 DO ST <= LAST & DATA[MID] != ITEM
3.   If ITEM < DATA[MID] then
     	LAST = MID-1
  	If not
     	ST = MID+1
4.   Set MID = INT((ST + LAST)/2)
  	[LAST repeat to 2]
5.   If DATA[MID] == ITEM then
     	LOK = MID
  	If not
     	LOK = NULL
6.   Stop

#Understanding with an Example

Let’s assume a sorted array.

Value 12 15 17 29 31 41 55
Index 0 1 2 3 4 5 6

 

Now let’s assume our target value T=17, which is at index 2. We will see how binary search will be applied in this case.

LB=0 and UB=6, so middle value will be: MID=(0+6)/2 =3, so our middle value is at position LOC= 3.

Pass1: Now, we will compare target value (T) with middle value (MID) as we can see T<MID, so we will eliminate the right subarray from index 3 to 6.

Pass2: Now, our middle value will be index 1 and target value T=17 as it is. Now we will compare MID with T, as T>MID so that we will eliminate left subarray.

Pass3: Now, our middle value and only remaining value is at index 2, that is 17. Also, we can see that our target value T is also 17. So, after comparing when we get that MID==T, we will stop and will return the location of the target value, that is LOC=2.

So, from the example, we can say that our target value is present at the index position.

#Program of Binary Search In Java

See the below program.

import java.util.*;

class Binary {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("\nEnter the length of the array:");
    int len = sc.nextInt();
    int[] arr = new int[len];
    System.out.println("Enter the elements of the array:\n");
    for (int i = 0; i < len; i++) {
      arr[i] = sc.nextInt();
    }
    System.out.println("Enter the elements you want to search:\n");
    int data = sc.nextInt();
    int UB = len - 1, LB = 0;
    int loc = BinarySearch(arr, LB, UB, data);
    if (loc >= 0)
      System.out.println("Target value is at index: " + loc);
    else
      System.out.println("Target value not found");
  }

  public static int BinarySearch(int arr[], int LB, int UB, int data) {
    int mid = (LB + UB) / 2;
    int loc = -1;
    while ((LB <= UB) && (arr[mid] != data)) {
      if (data < arr[mid])
        UB = mid - 1;
      else
        LB = mid + 1;
      mid = (LB + UB) / 2;
      if (data == arr[mid]) {
        loc = mid;
        break;
      } else
        loc = -1;
    }
    ;
    return loc;
  }
}

See the below output.

 

Java Binary Search Program

#Time complexity

The time complexity of binary search we can write as follows.

T(n) = T(n/2) + c

Above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the repetition will be following.

Theta (log n)

#Space Complexity

O(1) in case of iterative implementation. In the case of recursive implementation.

O(log n) recursion call stack space.

Finally, the Java Binary Search Program | Binary Search In Java Example is over.

The post Java Binary Search Program | Binary Search In Java Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/19/java-binary-search-program-binary-search-in-java-example/feed/ 0