Posts

Showing posts from October, 2018

Java Sound API Example

The Sound API is a low-level API for creating, modifying, and controlling the input and output of sound media, including both audio and MIDI (Musical Instrument Digital Interface) data. The JavaSound API provides explicit control over the capabilities normally required for sound input and output, in a framework that promotes extensibility and flexibility. The public JavaSound API consists of two main packages: javax.sound.sampled (interfaces and classes for sampled audio) javax.sound.midi (interfaces and classes for MIDI). javax.sound.sampled.spi javax.sound.midi.spi More info

Java 12 features

JDK 12 This release will be the Reference Implementation of version 12 of the Java SE Platform, as specified by  JSR 386  in the Java Community Process. Status The  development repositories  are open for bug fixes, small enhancements, and JEPs as proposed and tracked via the  JEP Process . Schedule 2018/12/13 Rampdown Phase One  (fork from main line) 2019/01/17 Rampdown Phase Two 2019/02/07 Release-Candidate Phase 2019/03/19 General Availability Features JEPs targeted to JDK 12, so far 325:  Switch Expressions (Preview) 326:  Raw String Literals (Preview) 340:  One AArch64 Port, Not Two 341:  Default CDS Archives

Java 11 features

JDK 11 is the open-source reference implementation of version 11 of the Java SE 11 Platform as specified by by  JSR 384  in the Java Community Process. JDK 11 reached  General Availability  on 25 September 2018. Production-ready binaries under the GPL are  available from Oracle ; binaries from other vendors  will follow shortly . The features and schedule of this release were proposed and tracked via the  JEP Process , as amended by the  JEP 2.0 proposal . The release was produced using the  JDK Release Process (JEP 3) . Features 181:  Nest-Based Access Control 309:  Dynamic Class-File Constants 315:  Improve Aarch64 Intrinsics 318:  Epsilon: A No-Op Garbage Collector 320:  Remove the Java EE and CORBA Modules 321:  HTTP Client (Standard) 323:  Local-Variable Syntax for Lambda Parameters 324:  Key Agreement with Curve25519 and Curve448 327:  Unicode 10 32...

PUBG mobile not responding after match end.

Java String strip() method Example

String strip() method String strip() method added in jdk 11. String strip()  Returns a string whose value is this string, with all leading and trailing white space removed. If this String object represents an empty string, or if all code points in this string are white space, then an empty string is returned. Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to and including the last code point that is not a white space. This method may be used to strip white space from the beginning and end of a string. strip method remove the extra space from both side. Java Program Example: class StripMethodExample{ public static void main(String args[]){ //with var variable var test = "     hello!   "; System.out.println(test.strip()); //with String class String test1 = "      hello!   "; System.out.println(test1.strip()); } } Output: hello! hello! ...

Java 11 : repeat method example

repeat method accept a integer parameter and repeat variable that many time. var test = " hello "; System.out.println(test.repear(3)); Output: hello   hello   hello

Java 10 : Garbage Collector

The GC interface would be defined by the existing class  CollectedHeap  which every garbage collector needs to implement. The  CollectedHeap  class would drive most aspects of interaction between the garbage collector and the rest of HotSpot (there a few utility classes needed prior to a  CollectedHeap  being instantiated). More specifically, a garbage collector implementation will have to provide: The heap, a subclass of  CollectedHeap The barrier set, a subclass of  BarrierSet , which implements the various barriers for the runtime An implementation of  CollectorPolicy An implementation of  GCInterpreterSupport , which implements the various barriers for a GC for the interpreter (using assembler instructions) An implementation of  GCC1Support , which implements the various barriers for a GC for the C1 compiler An implementation of  GCC2Support , which implements the various barriers for a GC for the C2 compiler Init...

Java 10 : 'var' variable example

'var' keyword - "var" variable introduced in Java 10 to declared any type of datatype. Example: var message= "hello"; var size = 10; var array = new String[]{"1","2","3"}; for(var i=0;i<10;i++){ } var in collection: var map = getMap(); public Map<String,String> getMap(){ Map<String,String> m=new HashMap<>(); m.put("1","1"); return m; }

Java 9 : JShell example

Image
In your command prompt, type jshell and press enter. You will see a message and then a jshell> prompt: Use  Ctrl + A  to reach the beginning of the line and  Ctrl + E  to reach the end of the line. 1) /help intro or /help help you in interacting with JShell 2) /imports java.lang.Object This imports the Object class 3) Let's declare an Employee class. class Employee{ private String empId; public String getEmpId() { return empId; } public void setEmpId ( String empId ) { this.empId = empId; } } 4) /open  loading the code from within a file. /open Test.java It will load the Test class definition and create an Test object.

Java 9 : Unified logging for JVM

Image
Java 9 implemented JEP 158: Unified JVM Logging, which requested to introduce a common logging system for all the components of the JVM. The main components of JVM include the following: Class loader Runtime data area        Stack area        Method area        Heap area        PC registers        Native method stack Execution engine           Interpreter           The JIT compiler           Garbage collection           Native method interface JNI           Native method library

Java 9 : HTTP POST request example

1. Create an instance of HttpClient using its HttpClient.Builder builder: HttpClient client = HttpClient.newBuilder().build(); 2. Create the required data to be passed into the request body: Map<String, String> requestBody = Map.of("key1", "value1", "key2", "value2"); 3. Create a HttpRequest object with the request method as POST and by providing the request body data as String. We make use of Jackson's ObjectMapper to convert the request body, Map<String, String>, into a plain JSON String and then make use of HttpRequest.BodyProcessor to process the String request body: ObjectMapper mapper = new ObjectMapper(); HttpRequest request = HttpRequest .newBuilder(new URI("http://httpbin.org/post")).POST( HttpRequest.BodyProcessor.fromString( mapper.writeValueAsString(requestBody))) .version(HttpClient.Version.HTTP_1_1).build(); 4. The request is sent and the response is obtained by using the send(HttpRequ...

Java 9 : HTTP GET request example

Using the JDK 9 HTTP Client API to make a GET request to the URL Package jdk.incubator.http.HttpClient jdk.incubator.http.HttpRequest java.net.URI HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder(new URI("http://java.com")).GET().version(HttpClient.Version.HTTP_1_1).build(); HttpResponse<String> response = client.send(request,HttpResponse.BodyHandler.asString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); Print the status code and the response body.

Producing and consuming JSON or XML in Java REST Services with Jersey

Maven dependencies <dependencies>   <dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-bundle</artifactId>  <version>1.19.3</version>  </dependency>  <dependency>     <groupId>com.sun.jersey</groupId>     <artifactId>jersey-json</artifactId>     <version>1.17.1</version> </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>  <artifactId>jackson-mapper-asl</artifactId>  <version>1.9.10</version>  </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>  <artifactId>jackson-core-asl</artifactId>  <version>1.9.10</version>  </dependency>  <dependency>  <groupId>org.codehaus.jackson</groupId>...

Java - Stream Operations and Pipelines

java.util.stream  This package allows you to have a declarative presentation of the procedures that can be subsequently applied to the data, also in parallel; these procedures are presented as streams, which are objects of the Stream interface. For better transition from the traditional collections to streams, two default methods (stream() and parallelStream()) were added to the java.util.Collection interface along with the addition of new factory methods of stream generation to the Stream interface. This approach takes advantage of the power of composition, discussed in one of the previous chapters. Together with other design principles--encapsulation, interface, and polymorphism--it facilitates a highly extensible and flexible design, while lambda expressions allow you to implement it in a concise and succinct manner. Today, when the machine learning requirements of massive data processing and the fine-tuning of operations have become ubiquitous, these new features...

Java 9 : functional programming

Functional programming--the ability to treat a certain piece of functionality as an object and to pass it as a parameter or the return value of a method--is a feature present in many programming languages. It avoids the changing of an object state and mutable data. The result of a function depends only on the input data, no matter how many times it is called. This style makes the outcome more predictable, which is the most attractive aspect of functional programming. Its introduction to Java also allows you to improve parallel programming capabilities in Java 8 by shifting the responsibility of parallelism from the client code to the library. Before this, in order to process elements of Java collections, the client code had to acquire an iterator from the collection and organize the processing of the collection.

java 9 : Modular Programming

Modular programming enables one to organize code into independent, cohesive modules, which can be combined together to achieve the desired functionality. This allows in creating code that is: More cohesive because the modules are built with a specific purpose, so the code that resides there tends to cater to that specific purpose. Encapsulated because modules can interact with only those APIs that have been made available by the other modules. Reliable because the discoverability is based on the modules and not on the individual types. This means that if a module is not present, then the dependent module cannot be executed until it is discoverable by the dependent module. This helps in preventing runtime errors. Loosely coupled. If you use service interfaces, then the module interface and the service interface implementation can be loosely coupled. So, the thought process in designing and organizing the code will now involve identifying the modules, code, and configur...

Java 9 : HTML5 in Javadocs - HTML5 tags in the Javadoc comments

Image
Generate javadocs to HTML content using java command HTML5 provides better browser compatibility. It is also more mobile-friendly than its predecessor, HTML4. But to take advantage of HTML5, one has to specify the html5 parameter during Javadoc generation. Otherwise, only HTM4-style comments will continue to be supported. Here is an example of the HTML5 tags used for Javadoc comments: /** <h2>Returns the weight of the car.</h2> <article> <h3>If life would be often that easy</h3> <p> Do you include unit of measurement into the method name or not? </p> <p> The new signature demonstrates extensible design of an interface. </p> </article> <aside> <p> A few other examples could be found <a href="http://www.nicksamoylov.com/cat/programming/">here</a>. </p> </aside> * @param weightUnit - an element of the enum Car.WeightUnit * @return the weight of the car in the ...

Java 9 : jmod

JMOD is a new format for packaging your modules. This format allows including native code, configuration files, and other data that do not fit into JAR files. The JDK modules have been packaged as JMOD files. The jmod command-line tool allows create, list, describe, and hash JMOD files: create: This is used to create a new jmod file list: This is used to list the contents of a jmod file describe: This is used to describe module details hash: This is used to record hashes of tied modules

Java 9 : jlink

This tool is used to select modules and create a smaller runtime image with the selected modules. $> jlink --module-path mods/:$JAVA_HOME/jmods/ --add-modules com.packt --output img Looking at the contents of the img folder, we should find that it has the bin, conf, include, and lib directories.

Java 9 : jdeps

This tool analyses your code base specified by the path to the .class file, directory, or  JAR, lists the package-wise dependency of your application, and also lists the JDK module in which the package exists. This helps in identifying the JDK modules that the application depends on and is the first step in migrating to modular applications. We can run the tool on our HelloWorldXml example written earlier and see what jdeps provides: $> jdeps mods/com.packt/ com.packt -> java.base com.packt -> java.xml.bind com.packt -> java.io                                  java.base com.packt -> java.lang                              java.base com.packt -> javax.xml.bind                     java.xml.bind com.packt -> javax.xml.bind.annotation  ...

Java 9 : jdeprscan

This tool is used for scanning the usage of deprecated APIs in a given JAR file, classpath, or source directory. Suppose we have a simple class that makes use of the deprecated method, addItem , of the   java.awt.List  class, as follows: import java.awt.List; public class Test{ public static void main(String[] args){ List list = new List(); list.addItem("Hello"); } } Compile the preceding class and then use jdeprscan , as follows: C:Program FilesJavajdk-9bin>jdeprscan.exe -cp . Test You will notice that this tool prints out class Test uses method java/awt/List addItem (Ljava/lang/String;) deprecated, which is exactly what we expected.

Java 9 : more concurrency updates

In this update, a new class, java.util.cuncurrent.Flow , has been introduced, which has java.util.concurrent nested interfaces supporting the implementation of a publish-subscribe framework. The publish-subscribe framework enables developers to build components that can asynchronously consume a live stream of data by setting up publishers that produce the data and subscribers that consume the data via subscription, which manages them. The four new interfaces are as follows: java.util.concurrent.Flow.Publisher java.util.concurrent.Flow.Subscriber java.util.concurrent.Flow.Subscription (which acts as both and Subscriber). java.util.concurrent.Flow.Processor

Java 9 : multi-release JAR files

As of now, JAR files can contain classes that can only run on the Java version they were compiled for. To leverage the new features of the Java platform on newer versions, the library developers have to release a newer version of their library. Soon, there will be multiple versions of the library being maintained by the developers, which can be a nightmare. To overcome this limitation, the new feature of multirelease JAR files allows developers to build JAR files with different versions of class files for different Java versions. The following example makes it more clear. Here is an illustration of the current JAR files: jar root - A.class - B.class - C.class Here is how multirelease JAR files look: jar root - A.class - B.class - C.class   - META-INF      - versions         - 9              - A.class         - 10              - B...

Java 9 : jshell -- the Java shell (Read- Eval-Print Loop)

Image
You must have seen languages, such as Ruby, Scala, Groovy, Clojure, and others shipping with a tool, which is often called REPL (Read-Eval-Print-Loop). This REPL tool is extremely useful in trying out the language features. For example, in Scala, we can write a simple Hello World program as scala> println("Hello World"); Some of the advantages of the JShell REPL are as follows: Help language learners to quickly try out the language features Help experienced developers to quickly prototype and experiment before adopting it in their main code base Java developers can now boast of an REPL Let's quickly spawn our command prompts/terminals and run the JShell command, as shown in the following image:

Java 9 : milling project coin

In Java SE 7, _ were introduced as part of the numbers, whereby a large number could be conveniently written by introducing _ between the digits. This helped in increasing the readability of the number, for example: Integer large_Number = 123_123_123; System.out.println(large_Number); In Java SE 8, the use of _ in the variable names, as shown earlier, resulted in a warning, but in Java SE 9, this use results in an error, which means that the variables can no longer have _ in their names. The other changed part of this JEP is to support private methods in interfaces. Java started with interfaces with absolutely no method implementations. Then, Java SE 8 introduced default methods that allowed interfaces to have methods with implementations, called default methods. So any class implementing this interface could choose not to override the default methods and use the implementation provided in the interface. Java SE 9 is introducing private methods, wherein the default meth...

Java 9 : HTTP/2 client

Java's HTTP API has been the most primitive. Developers often resort to using third party libraries, such as Apache HTTP, RESTlet, Jersey, and so on. In addition to this, Java's HTTP API predates the HTTP/1.1 specification and is synchronous and hard to maintain. These limitations called for the need to add a new API. The new HTTP client API provides the following: A simple and concise API to deal with most HTTP requests Support for HTTP/2 specification Better performance Better security A few more enhancements Let's see a sample code to make an HTTP GET request using the new APIs. Below is the module definition defined within the file //module-info.java module newfeatures{ requires jdk.incubator.httpclient; } The following code uses the HTTP Client API, which is part of module:  jdk.incubator.httpclient import jdk.incubator.http.*; import java.net.URI; public class Http2Feature{ public static void main(String[] args) thr...

Java 9 : Process API updates

Java's Process API has been quite primitive, with support only to launch new processes, redirect the processes' output, and error streams. In this release, the updates to the Process API enable the following: Get the PID of the current JVM process and any other processes spawned by the JVM Enumerate the processes running in the system to get information such as PID, name, and resource usage Managing process trees Managing sub processes Let's look at a sample code, which prints the current PID as well as the current process information: //NewFeatures.java public class NewFeatures{ public static void main(String [] args) { ProcessHandle currentProcess = ProcessHandle.current(); System.out.println("PID: " + currentProcess.getPid()); ProcessHandle.Info currentProcessInfo = currentProcess.info(); System.out.println("Info: " + currentProcessInfo); } }

Install and maintain Cygwin without Windows admin rights

These are the steps I used: Download  setup-x86.exe  (32bit) or  setup-x86_64.exe  (64bit). Run it with the “ --no-admin ” option During installation select the “wget” package Create /usr/local/bin/ cygwin-setup.sh  (for 32bit omit the “_64”): #! /bin/sh rm setup-x86_64.exe wget http://cygwin.com/setup-x86_64.exe chmod u+x setup-x86_64.exe run ./setup-x86_64.exe --no-admin Make the script executable: chmod ugo+x /usr/local/bin/ cygwin-setup.sh Create a copy of the Cygwin terminal shortcut, rename it “Cygwin setup” Edit the shortcut target, replace mintty.exe -i / Cygwin-Terminal.ico - with mintty.exe -i / Cygwin-Terminal.ico /bin/bash -l -c ' cygwin-setup.sh ' Whenever you want to run the Cygwin installer to install or remove packages, you can just execute the shortcut or run  cygwin-setup.sh  from the Cygwin command prompt. Alternatively, you could also use the pure command-line tool apt-cyg.

java 8 map initialization

Java 8 has a number of features that can be used to create and initialize maps. Take a look at this method:            protected static Map<Integer, String> stdJava8() {         return Collections.unmodifiableMap(Stream.of(                 new SimpleEntry<>(0, "zero"),                 new SimpleEntry<>(1, "one"),                 new SimpleEntry<>(2, "two"),                 new SimpleEntry<>(3, "three"),                 new SimpleEntry<>(4, "four"),                 new SimpleEntry<>(5, "five"),                 new SimpleEntry<>(6, "six"),                 new SimpleEntry<...

Torrent Tracker List May 2020 (200+ Trackers) to Increase Download Speed

This summary is not available. Please click here to view the post.

Throwing egg from building problem

You have unlimited egg and 100 floor building. If you throw an egg from a floor, If an egg doesn't break when dropped from some floor then try from  others floor. You have to find a exact floor from where if you throw an egg it will break, with minimum try.

Search a word in a grid

Given a 2D arrays of alphabet, search a word in that grid Example: [[A, A, A, R,T],  [M, A, O, R,W],  [C, T, L, R, L],  [Q, A, L, X, C],  [A, P, T, X, L]] Search " CAT ", shortest path Found in "(0,2)", "(1,1)", "(1,2)"

Intellij shortcuts keys : Rename

Intellij shortcuts keys for Rename Press key :  Shift + F6

Intellij shortcuts keys : Recent File popup

Intellij shortcuts keys : Recent File popup Ctrl + E

Intellij shortcuts keys : Shrink selection

Intellij shortcuts keys : Shrink selection Ctrl + Shift + W

Intellij shortcuts keys : Extend selection

Intellij shortcuts keys : Extend selection Ctrl + W

How to Debugging Stream Pipelines in IDE (intellij and Eclipse)

Intellij shortcuts keys : Synchronize

Intellij shortcuts keys : Synchronize Press Key :    Ctrl + Alt + Y  

Intellij shortcuts keys : Save All

Intellij shortcuts keys : Save All Press Key :  Ctrl + s 

Intellij shortcuts keys : open corresponding tool windows

Intellij shortcuts keys : open corresponding tool windows Press Key :  Alt + #[0-9]

write a program to check if strings are rotations of each other or not

check number is power of 2 or not

given n=200 Check this number is power of two or not Solution: 1 |  01 2 |  10 3 |  011 4 |  100 5 |  101 6 |  110 7 |  0111 8 |  1000 Check the binary digit of the number with power  if we do n&n-1, Result will be 0 so, n&n-1 result is not 0, then that number not a power of two

Intellij shortcuts keys - Parameter Info

Intellij shortcuts keys - Parameter Info Ctrl + P

Intellij shortcuts keys - Generate Code

Intellij shortcuts keys - Generate Code Alt + Ins 

Intellij shortcuts keys - Show intention actions and Quick fixes

Intellij shortcuts keys - Show intention actions and Quick fixes Alt + Enter

Intellij shortcuts keys - Search Every where

Intellij shortcuts keys for search any where Double Shift 

Intellij shortcuts keys - Smart Code completion

Intellij IDEA shortcuts keys for Smart Code completion  Ctrl + Shift + Space

How to configure proxy in PyCharm

Open PyCharm, go to File then Settings. Click at HTTP Proxy under the IDE Settings. Click and enable the Use HTTP proxy check box. Fill in the IP address or Hostname of the proxy server you want to connect to and enter the port number which is being used by the proxy server. Fill in the Login user name and enter the password for the proxy server. Click Apply then Ok to close the dialog box