Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Java Language Part 2

Java Language Part 2

Published by Jiruntanin Sidangam, 2020-10-25 07:56:28

Description: Java Language Part 2

Keywords: Java Language, Part 2,Java,Language

Search

Read the Text Version

Java Language #java

Final classes 451 Use-cases for final classes 451 Final methods 452 453 The Liskov Substitution Principle 453 Inheritance 455 Inheritance and Static Methods 455 Variable shadowing 456 Narrowing and Widening of object references 457 Programming to an interface 460 Abstract class and Interface usage: \"Is-a\" relation vs \"Has-a\" capability 463 Overriding in Inheritance 465 465 Chapter 69: InputStreams and OutputStreams 465 Syntax 465 Remarks 465 Examples 465 466 Reading InputStream into a String 467 Writing bytes to an OutputStream 467 Closing Streams 467 Copying Input Stream to Output Stream 468 Wrapping Input/Output Streams 468 470 Useful combinations 470 List of Input/Output Stream wrappers 470 470 DataInputStream Example 470 Chapter 70: Installing Java (Standard Edition) 470 471 Introduction 471 Examples 472 Setting %PATH% and %JAVA_HOME% after installing on Windows Assumptions: Setup steps Check your work Selecting an appropriate Java SE release Java release and version naming

Creating JAR and WAR files using Maven 508 Creating JAR, WAR and EAR files using Ant 508 Creating JAR, WAR and EAR files using an IDE 508 Creating JAR, WAR and EAR files using the jar command. 508 509 Introduction to Java Web Start 509 Prerequisites 509 An example JNLP file 510 Setting up the web server 510 Enabling launch via a web page 511 Launching Web Start applications from the command line 511 511 Creating an UberJAR for an application and its dependencies 512 512 Creating an UberJAR using the \"jar\" command 513 Creating an UberJAR using Maven 513 The advantages and drawbacks of UberJARs 513 Chapter 76: Java Editions, Versions, Releases and Distributions 513 513 Examples 514 Differences between Java SE JRE or Java SE JDK distributions 514 514 Java Runtime Environment 515 Java Development Kit 515 515 What is the difference between Oracle Hotspot and OpenJDK 516 Differences between Java EE, Java SE, Java ME and JavaFX 516 516 The Java Programming Language Platforms 517 Java SE 519 Java EE 519 Java ME Java FX Java SE Versions Java SE Version History Java SE Version Highlights Chapter 77: Java Floating Point Operations Introduction

Examples 519 Comparing floating point values 519 OverFlow and UnderFlow 521 Formatting the floating point values 522 Strict Adherence to the IEEE Specification 523 524 Chapter 78: Java Memory Management 524 Remarks 524 Examples 524 524 Finalization 525 Finalizers only run once 525 525 Manually triggering GC 526 Garbage collection 526 The C++ approach - new and delete 527 The Java approach - garbage collection 528 What happens when an object becomes unreachable 529 Examples of reachable and unreachable objects 529 Setting the Heap, PermGen and Stack sizes 530 Memory leaks in Java 531 Reachable objects can leak 531 Caches can be memory leaks 531 531 Chapter 79: Java Memory Model 532 Remarks 532 Examples 533 533 Motivation for the Memory Model 533 Reordering of assignments 534 Effects of memory caches 534 Proper synchronization 535 The Memory Model Happens-before relationships Actions Program Order and Synchronization Order Happens-before Order

Happens-before reasoning applied to some examples 535 Single-threaded code 535 Behavior of 'volatile' in an example with 2 threads 536 Volatile with three threads 537 538 How to avoid needing to understand the Memory Model 539 Chapter 80: Java Native Access 539 Examples 539 Introduction to JNA 539 What is JNA? 539 How can I use it? 540 Where to go now? 541 Chapter 81: Java Native Interface 541 541 Parameters 541 Remarks Examples 541 541 Calling C++ methods from Java 542 Java code 543 C++ code 543 Output 543 544 Calling Java methods from C++ (callback) 544 Java code 544 C++ code 545 Output 545 Getting the descriptor 547 Loading native libraries 547 Target file lookup 547 Chapter 82: Java Performance Tuning 547 Examples 548 General approach Reducing amount of Strings An evidence-based approach to Java performance tuning

Chapter 83: Java Pitfalls - Exception usage 550 Introduction 550 Examples 550 Pitfall - Ignoring or squashing exceptions 550 Pitfall - Catching Throwable, Exception, Error or RuntimeException 551 Pitfall - Throwing Throwable, Exception, Error or RuntimeException 552 Declaring Throwable or Exception in a method's \"throws\" is problematic. 553 Pitfall - Catching InterruptedException 554 Pitfall - Using exceptions for normal flowcontrol 555 Pitfall - Excessive or inappropriate stacktraces 556 Pitfall - Directly subclassing `Throwable` 557 Chapter 84: Java Pitfalls - Language syntax 558 Introduction 558 Remarks 558 Examples 558 Pitfall - Ignoring method visibility 558 Pitfall - Missing a ‘break’ in a 'switch' case 558 Pitfall - Misplaced semicolons and missing braces 559 Pitfall - Leaving out braces: the \"dangling if\" and \"dangling else\" problems 561 Pitfall - Overloading instead of overriding 562 Pitfall - Octal literals 564 Pitfall - Declaring classes with the same names as standard classes 564 Pitfall - Using '==' to test a boolean 565 Pitfall - Wildcard imports can make your code fragile 566 Pitfall: Using 'assert' for argument or user input validation 566 Pitfall of Auto-Unboxing Null Objects into Primitives 567 Chapter 85: Java Pitfalls - Nulls and NullPointerException 569 Remarks 569 Examples 569 Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions 569 Pitfall - Using null to represent an empty array or collection 570 Pitfall - \"Making good\" unexpected nulls 571

What does it mean for \"a\" or \"b\" to be null? 572 Did the null come from an uninitialized variable? 572 Does the null represent a \"don't know\" or \"missing value\"? 572 If this is a bug (or a design error) should we \"make good\"? 572 Is this efficient / good for code quality? 572 In summary 573 573 Pitfall - Returning null instead of throwing an exception 573 Pitfall - Not checking if an I/O stream isn't even initialized when closing it 574 Pitfall - Using \"Yoda notation\" to avoid NullPointerException 576 576 Chapter 86: Java Pitfalls - Performance Issues 576 Introduction 576 Remarks 576 Examples 576 577 Pitfall - The overheads of creating log messages 578 Solution 578 579 Pitfall - String concatenation in a loop does not scale 580 Pitfall - Using 'new' to create primitive wrapper instances is inefficient 581 Pitfall - Calling 'new String(String)' is inefficient 581 Pitfall - Calling System.gc() is inefficient 582 Pitfall - Over-use of primitive wrapper types is inefficient 582 Pitfall - Iterating a Map's keys can be inefficient 583 Pitfall - Using size() to test if a collection is empty is inefficient. 583 Pitfall - Efficiency concerns with regular expressions 584 Pattern and Matcher instances should be reused 585 Don't use match() when you should use find() 585 Use more efficient alternatives to regular expressions 585 Catastrophic Backtracking 586 Pitfall - Interning strings so that you can use == is a bad idea 586 Fragility Costs of using 'intern()' The impact on garbage collection The string pool hashtable size

Interning as a potential denial of service vector 587 Pitfall - Small reads / writes on unbuffered streams are inefficient 587 588 What about character-based streams? 588 Why do buffered streams make this much difference? 589 Are buffered streams always a win? 589 Is this the fastest way to copy a file in Java? 590 Chapter 87: Java Pitfalls - Threads and Concurrency 590 Examples 590 590 Pitfall: incorrect use of wait() / notify() 590 The \"Lost Notification\" problem 591 The \"Illegal Monitor State\" bug 591 Wait / notify is too low-level 592 593 Pitfall - Extending 'java.lang.Thread' 594 Pitfall - Too many threads makes an application slower. 595 Pitfall - Thread creation is relatively expensive 595 Pitfall: Shared variables require proper synchronization 596 Will it work as intended? 596 How do we fix the problem? 597 But isn't assignment atomic? 599 Why did they do this? 599 Why can't I reproduce this? 599 599 Chapter 88: Java plugin system implementations 604 Remarks 604 Examples 604 604 Using URLClassLoader 604 605 Chapter 89: Java Print Service 605 Introduction Examples Discovering the available print services Discovering the default print service Creating a print job from a print service Building the Doc that will be printed

Defining print request attributes 606 Listening print job request status change 606 The PrintJobEvent pje argument 608 Another way to achieve the same goal 608 Chapter 90: Java SE 7 Features 609 609 Introduction 609 Remarks 609 Examples 609 New Java SE 7 programming language features 609 Binary Literals 610 The try-with-resources statement 610 Underscores in Numeric Literals 610 Type Inference for Generic Instance Creation 611 Strings in switch Statements 612 Chapter 91: Java SE 8 Features 612 Introduction 612 Remarks 612 Examples 612 New Java SE 8 programming language features 614 Chapter 92: Java Sockets 614 Introduction 614 Remarks 614 Examples 614 A simple TCP echo back server 618 Chapter 93: Java Virtual Machine (JVM) 618 Examples 618 These are the basics. 619 Chapter 94: JavaBean 619 Introduction 619 Syntax 619 Remarks

Examples 620 Basic Java Bean 620 621 Chapter 95: JAXB 621 Introduction 621 Syntax 621 Parameters 621 Remarks 621 Examples 621 622 Writing an XML file (marshalling an object) 623 Reading an XML file (unmarshalling) 624 Using XmlAdapter to generate desired xml format 626 Automatic field/property XML mapping configuration (@XmlAccessorType) 626 Manual field/property XML mapping configuration 627 Specifying a XmlAdapter instance to (re)use existing data 627 Example 627 User class 628 Adapter 629 Example XMLs 629 Using the adapter 630 Binding an XML namespace to a serializable Java class. 631 Using XmlAdapter to trim string. 631 631 Chapter 96: JAX-WS 632 Examples 632 632 Basic Authentication 632 637 Chapter 97: JMX 637 Introduction 637 Examples 641 Simple example with Platform MBean Server Chapter 98: JNDI Examples RMI through JNDI Chapter 99: JShell

Introduction 641 Syntax 641 Remarks 641 Default Imports 641 Examples 641 642 Entering and Exiting JShell 642 Starting JShell 642 Exiting JShell 642 642 Expressions 643 Variables 643 Methods and Classes 645 Editting Snippets 645 645 Chapter 100: JSON in Java 645 Introduction 645 Remarks 646 Examples 646 647 Encoding data as JSON 647 Decoding JSON data 647 optXXX vs getXXX methods 648 Object To JSON (Gson Library) 648 JSON To Object (Gson Library) 648 Extract single element from JSON 648 Using Jackson Object Mapper 649 649 Details 649 ObjectMapper instance 650 Deserialization: 650 Method for serialization: 651 JSON Iteration JSON Builder - chaining methods JSONObject.NULL JsonArray to Java List (Gson Library) Deserialize JSON collection to collection of Objects using Jackson

Deserializing JSON array 651 TypeFactory approach 651 TypeReference approach 652 652 Deserializing JSON map 652 TypeFactory approach 652 TypeReference approach 652 652 Details 654 Note 654 Chapter 101: Just in Time (JIT) compiler 654 654 Remarks History 654 Examples 657 Overview 657 657 Chapter 102: JVM Flags Remarks 657 Examples 657 658 -XXaggressive 658 -XXallocClearChunks 658 -XXallocClearChunkSize 659 -XXcallProfiling 659 -XXdisableFatSpin 659 -XXdisableGCHeuristics -XXdumpSize 661 -XXexitOnOutOfMemory 661 661 Chapter 103: JVM Tool Interface Remarks 661 Examples 663 664 Iterate over objects reachable from object (Heap 1.0) Get JVMTI environment 665 Example of initialization inside of Agent_OnLoad method Chapter 104: Lambda Expressions

Introduction 665 Syntax 665 Examples 665 665 Using Lambda Expressions to Sort a Collection 665 666 Sorting lists 667 Sorting maps 667 668 Introduction to Java lambdas 669 Functional Interfaces 669 Lambda Expressions 670 Implicit Returns 670 Accessing Local Variables (value closures) 670 Accepting Lambdas 671 The Type of a Lambda Expression 671 671 Method References 672 Instance method reference (to an arbitrary instance) 672 Instance method reference (to a specific instance) 672 Static method reference 673 Reference to a constructor 674 Cheat-Sheet 674 676 Implementing multiple interfaces 678 Lambdas and Execute-around Pattern 678 Using lambda expression with your own functional interface 679 `return` only returns from the lambda, not the outer method 680 Java Closures with lambda expressions. 682 Lambda - Listener Example 682 Traditional style to Lambda style 682 Lambdas and memory utilization Using lambda expressions & predicates to get a certain value(s) from a list Chapter 105: LinkedHashMap Introduction Examples

Java LinkedHashMap class 682 Chapter 106: List vs SET 684 Introduction 684 Examples 684 List vs Set 684 Chapter 107: Lists 685 Introduction 685 Syntax 685 Remarks 685 Examples 686 Sorting a generic list 686 Creating a List 687 Positional Access Operations 689 Iterating over elements in a list 690 Removing elements from list B that are present in the list A 691 Finding common elements between 2 lists 692 Convert a list of integers to a list of strings 692 Creating, Adding and Removing element from an ArrayList 692 In-place replacement of a List element 693 Making a list unmodifiable 694 Moving objects around in the list 694 Classes implementing List - Pros and Cons 695 Classes implementing List 695 Pros and Cons of each implementation in term of time complexity 695 ArrayList 696 AttributeList 696 CopyOnWriteArrayList 696 LinkedList 696 RoleList 697 RoleUnresolvedList 697 Stack 697 Vector 697

Chapter 108: Literals 699 Introduction 699 Examples 699 Hexadecimal, Octal and Binary literals 699 Using underscore to improve readability 699 Escape sequences in literals 700 Unicode escapes 701 Escaping in regexes 701 Decimal Integer literals 701 Ordinary integer literals 701 Long integer literals 702 Boolean literals 702 String literals 702 Long strings 703 Interning of string literals 703 The Null literal 703 Floating-point literals 704 Simple decimal forms 704 Scaled decimal forms 705 Hexadecimal forms 705 Underscores 705 Special cases 706 Character literals 706 Chapter 109: Local Inner Class 707 Introduction 707 Examples 707 Local Inner Class 707 Chapter 110: Localization and Internationalization 708 Remarks 708 General Resources 708 Java Resources 708

Examples 708 Automatically formatted Dates using \"locale\" 708 709 Let Java do the work for you 709 String Comparison 709 Locale 710 710 Language 710 Creating a Locale 710 Java ResourceBundle 712 Setting Locale 712 Chapter 111: LocalTime 712 712 Syntax 712 Parameters 712 Remarks 713 Examples 713 714 Time Modification 716 Time Zones and their time difference 716 Amount of time between two LocalTime 716 Intro 716 716 Chapter 112: log4j / log4j2 717 Introduction 717 Syntax 718 Remarks 718 719 End of Life for Log4j 1 reached 719 Examples 720 721 How to get Log4j How to use Log4j in Java code Setting up property file Basic log4j2.xml configuration file Migrating from log4j 1.x to 2.x Properties-File to log to DB Filter Logoutput by level (log4j 1.x)

Chapter 113: Logging (java.util.logging) 723 Examples 723 Using the default logger 723 Logging levels 723 Logging complex messages (efficiently) 724 Chapter 114: Maps 727 Introduction 727 Remarks 727 Examples 727 Add an element 727 Add multiple items 728 Using Default Methods of Map from Java 8 729 Clear the map 731 Iterating through the contents of a Map 732 Merging, combine and composing Maps 733 Composing Map<X,Y> and Map<Y,Z> to get Map<X,Z> 733 Check if key exists 734 Maps can contain null values 734 Iterating Map Entries Efficiently 734 Use custom object as key 737 Usage of HashMap 738 Creating and Initializing Maps 739 739 Introduction 742 Chapter 115: Modules 742 742 Syntax 742 Remarks Examples 742 Defining a basic module 744 744 Chapter 116: Multi-Release JAR Files 744 Introduction Examples

Example of a multi-release Jar file's contents 744 Creating a multi-release Jar using the jar tool 744 URL of a loaded class inside a multi-release Jar 746 Chapter 117: Nashorn JavaScript engine 747 Introduction 747 Syntax 747 Remarks 747 Examples 747 Set global variables 747 Hello Nashorn 748 Execute JavaScript file 748 Intercept script output 748 Evaluate Arithmetic Strings 749 Usage of Java objects in JavaScript in Nashorn 749 Implementing an interface from script 750 Set and get global variables 751 Chapter 118: Nested and Inner Classes 752 Introduction 752 Syntax 752 Remarks 752 Terminology and classification 752 Semantic differences 753 Examples 753 A Simple Stack Using a Nested Class 753 Static vs Non Static Nested Classes 754 Access Modifiers for Inner Classes 756 Anonymous Inner Classes 757 Constructors 758 Method Local Inner Classes 758 Accessing the outer class from a non-static inner class 759 Create instance of non-static inner class from outside 760 Chapter 119: Networking 761

Syntax 761 Examples 761 761 Basic Client and Server Communication using a Socket 761 Server: Start, and wait for incoming connections 761 Server: Handling clients 762 Client: Connect to the server and send a message 762 Closing Sockets and Handling Exceptions 762 Basic Server and Client - complete examples 764 765 Loading TrustStore and KeyStore from InputStream 765 Socket example - reading a web page using a simple socket 766 Basic Client/Server Communication using UDP (Datagram) 768 Multicasting 769 Temporarily disable SSL verification (for testing purposes) 770 Downloading a file using Channel 771 Notes 771 771 Chapter 120: New File I/O 771 Syntax 771 Examples 772 772 Creating paths 772 Retrieving information about a path 772 Manipulating paths 772 773 Joining Two Paths 773 Normalizing a path 773 774 Retrieving information using the filesystem 774 Checking existence 775 Checking whether a path points to a file or a directory Getting properties Getting MIME type Reading files Writing files Chapter 121: NIO - Networking

Remarks 775 Examples 775 775 Using Selector to wait for events (example with OP_CONNECT) 777 777 Chapter 122: Non-Access Modifiers 777 Introduction 777 Examples 778 779 final 780 volatile 781 static 782 abstract 782 synchronized 783 transient 783 strictfp 783 784 Chapter 123: NumberFormat 784 Examples 784 784 NumberFormat 784 785 Chapter 124: Object Class Methods and Constructor 787 Introduction 788 Syntax 789 Examples 790 791 toString() method 792 equals() method 793 Class Comparison 794 hashCode() method 795 Using Arrays.hashCode() as a short cut 798 Internal caching of hash codes wait() and notify() methods getClass() method clone() method finalize() method Object constructor Chapter 125: Object Cloning

Remarks 798 Examples 798 798 Cloning using a copy constructor 798 Cloning by implementing Clonable interface 799 Cloning performing a shallow copy 800 Cloning performing a deep copy 801 Cloning using a copy factory 802 802 Chapter 126: Object References 802 Remarks 802 Examples 806 806 Object References as method parameters 806 806 Chapter 127: Operators 806 Introduction 807 Remarks 808 Examples 809 809 The String Concatenation Operator (+) 810 Optimization and efficiency 810 811 The Arithmetic Operators (+, -, *, /, %) 811 Operand and result types, and numeric promotion 812 The meaning of division 812 The meaning of remainder 813 Integer Overflow 813 Floating point INF and NAN values 813 814 The Equality Operators (==, !=) 814 The Numeric == and != operators The Boolean == and != operators The Reference == and != operators About the NaN edge-cases The Increment/Decrement Operators (++/--) The Conditional Operator (? :) Syntax

Common Usage 815 The Bitwise and Logical Operators (~, &, |, ^) 816 Operand types and result types. 817 The Instanceof Operator 817 The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=) 818 The conditional-and and conditional-or Operators ( && and || ) 820 Example - using && as a guard in an expression 821 Example - using && to avoid a costly calculation 821 The Shift Operators (<<, >> and >>>) 821 The Lambda operator ( -> ) 823 The Relational Operators (<, <=, >, >=) 823 Chapter 128: Optional 825 Introduction 825 Syntax 825 Examples 825 Return default value if Optional is empty 825 Map 826 Throw an exception, if there is no value 827 Filter 827 Using Optional containers for primitive number types 828 Run code only if there is a value present 828 Lazily provide a default value using a Supplier 828 FlatMap 829 Chapter 129: Oracle Official Code Standard 830 Introduction 830 Remarks 830 Examples 830 Naming Conventions 830 Package names 830 Class, Interface and Enum Names 830 Method Names 831 Variables 831

Type Variables 831 Constants 831 Other guidelines on naming 831 832 Java Source Files 832 Special Characters 832 Package declaration 832 Import statements 833 Wildcard imports 833 Class Structure 833 Order of class members 834 Grouping of class members 834 Modifiers 835 Indentation 835 Wrapping statements 836 Wrapping Method Declarations 837 Wrapping Expressions 837 Whitespace 837 Vertical Whitespace 837 Horizontal Whitespace 838 838 Variable Declarations 839 Annotations 839 Lambda Expressions 840 Redundant Parentheses 840 Literals 840 Braces 842 Short forms 842 Chapter 130: Packages 842 Introduction 842 Remarks Examples 842 Using Packages to create classes with the same name

Using Package Protected Scope 842 Chapter 131: Parallel programming with Fork/Join framework 844 Examples 844 Fork/Join Tasks in Java 844 Chapter 132: Polymorphism 846 Introduction 846 Remarks 846 Examples 846 Method Overloading 846 Method Overriding 848 Adding behaviour by adding classes without touching existing code 849 Virtual functions 850 Polymorphism and different types of overriding 851 Chapter 133: Preferences 855 Examples 855 Adding event listeners 855 PreferenceChangeEvent 855 NodeChangeEvent 855 Getting sub-nodes of Preferences 856 Coordinating preferences access across multiple application instances 857 Exporting preferences 857 Importing preferences 858 Removing event listeners 859 Getting preferences values 860 Setting preferences values 860 Using preferences 861 Chapter 134: Primitive Data Types 862 Introduction 862 Syntax 862 Remarks 862 Examples 863 The int primitive 863

The short primitive 864 The long primitive 864 The boolean primitive 865 The byte primitive 866 The float primitive 866 The double primitive 867 The char primitive 868 Negative value representation 869 Memory consumption of primitives vs. boxed primitives 870 Boxed value caches 871 Converting Primitives 871 Primitive Types Cheatsheet 872 Chapter 135: Process 874 Remarks 874 Examples 874 Simple example (Java version < 1.5) 874 Using the ProcessBuilder class 874 Blocking vs. Non-Blocking Calls 875 ch.vorburger.exec 876 Pitfall: Runtime.exec, Process and ProcessBuilder don't understand shell syntax 876 Spaces in pathnames 876 Redirection, pipelines and other shell syntax 877 Shell builtin commands don't work 878 Chapter 136: Properties Class 879 Introduction 879 Syntax 879 Remarks 879 Examples 880 Loading properties 880 Property files caveat: trailing whitespace 880 Saving Properties as XML 882 Chapter 137: Queues and Deques 885

Examples 885 The usage of the PriorityQueue 885 LinkedList as a FIFO Queue 885 Stacks 886 886 What is a Stack? 886 Stack API 886 Example 887 888 BlockingQueue 889 Queue Interface 890 Deque 890 Adding and Accessing Elements 891 Removing Elements 891 Chapter 138: Random Number Generation 891 Remarks 891 Examples 891 892 Pseudo Random Numbers 893 Pseudo Random Numbers in Specific Range 894 Generating cryptographically secure pseudorandom numbers 894 Select random numbers without duplicates 896 Generating Random Numbers with a Specified Seed 896 Generating Random number using apache-common lang3 896 896 Chapter 139: Readers and Writers 896 Introduction 896 Examples 897 897 BufferedReader 897 897 Introduction Basics of using a BufferedReader The BufferedReader buffer size The BufferedReader.readLine() method Example: reading all lines of a File into a List StringWriter Example

Chapter 140: Recursion 899 Introduction 899 Remarks 899 Designing a Recursive Method 899 899 Output 900 Java and Tail-call elimination 900 Examples 900 The basic idea of recursion 901 Computing the Nth Fibonacci Number 901 Computing the sum of integers from 1 to N 901 Computing the Nth power of a number 902 Reverse a string using Recursion 902 Traversing a Tree data structure with recursion 903 Types of Recursion 903 StackOverflowError & recursion to loop 903 Example 904 Workaround 904 Example 906 Deep recursion is problematic in Java 907 Why tail-call elimination is not implemented in Java (yet) 908 908 Chapter 141: Reference Data Types Examples 908 908 Instantiating a reference type Dereferencing 910 910 Chapter 142: Reference Types Examples 910 Different Reference Types 912 912 Chapter 143: Reflection API 912 Introduction 912 Remarks Performance

Examples 912 Introduction 912 Invoking a method 914 Getting and Setting fields 914 Call constructor 915 915 Getting the Constructor Object 916 New Instance using Constructor Object 916 917 Getting the Constants of an Enumeration 918 Get Class given its (fully qualified) name 918 Call overloaded constructors using reflection 920 Misuse of Reflection API to change private and final variables 920 Call constructor of nested class 921 Dynamic Proxies 924 Evil Java hacks with Reflection 924 924 Chapter 144: Regular Expressions 924 Introduction 924 Syntax 924 Remarks 924 925 Imports 925 Pitfalls 925 Important Symbols Explained 926 Further reading 926 927 Examples 927 Using capture groups 928 Using regex with custom behaviour by compiling the Pattern with flags 930 Escape Characters 930 Matching with a regex literal. 930 Not matching a given string Matching a backslash Chapter 145: Remote Method Invocation (RMI) Remarks Examples

Client-Server: invoking methods in one JVM from another 930 Callback: invoking methods on a \"client\" 932 Overview 932 The shared remote interfaces 932 The implementations 933 Simple RMI example with Client and Server implementation 936 Server Package 936 Client package 937 Test your application 939 Chapter 146: Resources (on classpath) 940 Introduction 940 Remarks 940 Examples 941 Loading an image from a resource 941 Loading default configuration 942 Loading same-name resource from multiple JARs 942 Finding and reading resources using a classloader 942 Absolute and relative resource paths 943 Obtaining a Class or Classloader 943 The get methods 943 Chapter 147: RSA Encryption 945 Examples 945 An example using a hybrid cryptosystem consisting of OAEP and GCM 945 Chapter 148: Runtime Commands 950 Examples 950 Adding shutdown hooks 950 Chapter 149: Scanner 951 Syntax 951 Parameters 951 Remarks 951 Examples 951 Reading system input using Scanner 951

Reading file input using Scanner 951 Read the entire input as a String using Scanner 952 Using custom delimiters 952 General Pattern that does most commonly asked about tasks 953 Read an int from the command line 955 Carefully Closing a Scanner 955 Chapter 150: Secure objects 956 Syntax 956 Examples 956 SealedObject (javax.crypto.SealedObject) 956 SignedObject (java.security.SignedObject) 956 Chapter 151: Security & Cryptography 958 Examples 958 Compute Cryptographic Hashes 958 Generate Cryptographically Random Data 958 Generate Public / Private Key Pairs 959 Compute and Verify Digital Signatures 959 Encrypt and Decrypt Data with Public / Private Keys 960 Chapter 152: Security & Cryptography 962 Introduction 962 Remarks 962 Examples 962 The JCE 962 Keys and Key Management 962 Common Java vulnerabilities 962 Networking Concerns 963 Randomness and You 963 Hashing and Validation 963 Chapter 153: SecurityManager 964 Examples 964 Enabling the SecurityManager 964 Sandboxing classes loaded by a ClassLoader 964

Implementing policy deny rules 965 The DeniedPermission class 966 The DenyingPolicy class 970 Demo 972 Chapter 154: Serialization 974 Introduction 974 Examples 974 Basic Serialization in Java 974 Serialization with Gson 976 Serialization with Jackson 2 977 Custom Serialization 978 Versioning and serialVersionUID 980 Compatible Changes 981 Incompatible Changes 982 Custom JSON Deserialization with Jackson 982 Chapter 155: ServiceLoader 985 Remarks 985 Examples 985 Logger Service 985 Service 985 Implementations of the service 985 986 META-INF/services/servicetest.Logger 986 Usage 987 989 Simple ServiceLoader Example 989 Chapter 156: Sets 989 Examples 989 Declaring a HashSet with values Types and Usage of Sets 989 989 HashSet - Random Sorting 990 LinkedHashSet - Insertion Order TreeSet - By compareTo() or Comparator

Initialization 990 Basics of Set 991 Create a list from an existing Set 992 Eliminating duplicates using Set 993 Chapter 157: Singletons 994 Introduction 994 Examples 994 994 Enum Singleton 994 Thread safe Singleton with double checked locking 995 Singleton without use of Enum (eager initialization) 996 Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation 996 Extending singleton (singleton inheritance) 1000 1000 Chapter 158: Sockets 1000 Introduction 1000 Examples 1001 1001 Read from socket 1001 1001 Chapter 159: SortedMap 1003 Introduction 1003 Examples 1003 1003 Introduction to sorted Map. 1003 1004 Chapter 160: Splitting a string into fixed length parts 1004 Remarks 1004 Examples 1004 1005 Break a string up into substrings all of a known length 1005 Break a string up into substrings all of variable length Chapter 161: Stack-Walking API Introduction Examples Print all stack frames of the current thread Print current caller class Showing reflection and other hidden frames

Chapter 162: Streams 1007 Introduction 1007 Syntax 1007 Examples 1007 Using Streams 1007 Closing Streams 1008 Processing Order 1009 Differences from Containers (or Collections) 1010 1010 Collect Elements of a Stream into a Collection 1010 Collect with toList() and toSet() 1010 Explicit control over the implementation of List or Set 1012 Cheat-Sheet 1013 1014 Infinite Streams 1015 Consuming Streams 1015 h21 1016 Creating a Frequency Map 1016 Parallel Stream 1017 Performance impact 1017 Converting a Stream of Optional to a Stream of Values 1018 Creating a Stream 1019 Finding Statistics about Numerical Streams 1019 Get a Slice of a Stream 1020 Concatenate Streams 1020 IntStream to String 1021 Sort Using Stream 1021 Streams of Primitives 1021 Collect Results of a Stream into an Array 1022 Finding the First Element that Matches a Predicate 1022 Using IntStream to iterate over indexes 1023 Flatten Streams with flatMap() 1024 Create a Map based on a Stream Generating random Strings using Streams

Using Streams to Implement Mathematical Functions 1025 Using Streams and Method References to Write Self-Documenting Processes 1025 Using Streams of Map.Entry to Preserve Initial Values after Mapping 1026 Stream operations categories 1027 Intermediate Operations: 1027 Terminal Operations 1027 Stateless Operations 1027 Stateful operations 1028 1028 Converting an iterator to a stream 1028 Reduction with Streams 1031 Joining a stream to a single String 1033 Chapter 163: String Tokenizer 1033 Introduction 1033 Examples 1033 StringTokenizer Split by space 1033 StringTokenizer Split by comma ',' 1035 Chapter 164: StringBuffer 1035 Introduction 1035 Examples 1035 String Buffer class 1037 Chapter 165: StringBuilder 1037 Introduction 1037 Syntax 1037 Remarks 1037 Examples 1037 Repeat a String n times 1038 Comparing StringBuffer, StringBuilder, Formatter and StringJoiner 1040 Chapter 166: Strings 1040 Introduction 1040 Remarks 1041 Examples

Comparing Strings 1041 Do not use the == operator to compare Strings 1042 Comparing Strings in a switch statement 1042 Comparing Strings with constant values 1043 String orderings 1043 Comparing with interned Strings 1043 1044 Changing the case of characters within a String 1046 Finding a String Within Another String 1047 Getting the length of a String 1047 Substrings 1048 Getting the nth character in a String 1048 Platform independent new line separator 1049 Adding toString() method for custom objects 1050 Splitting Strings 1052 Joining Strings with a delimiter 1053 Reversing Strings 1054 Counting occurrences of a substring or character in a string 1054 String concatenation and StringBuilders 1056 Replacing parts of Strings 1056 Exact match 1056 Replace single character with another single character: 1056 Replace sequence of characters with another sequence of characters: 1057 Regex 1057 Replace all matches: 1057 Replace first match only: 1057 Remove Whitespace from the Beginning and End of a String 1058 String pool and heap storage 1060 Case insensitive switch 1061 Chapter 167: sun.misc.Unsafe 1061 Remarks 1061 Examples

Instantiating sun.misc.Unsafe via reflection 1061 Instantiating sun.misc.Unsafe via bootclasspath 1061 Getting Instance of Unsafe 1062 Uses of Unsafe 1062 Chapter 168: super keyword 1064 Examples 1064 Super keyword use with examples 1064 Constructor Level 1064 Method Level 1065 Variable Level 1065 Chapter 169: The Classpath 1067 Introduction 1067 Remarks 1067 Examples 1067 Different ways to specify the classpath 1067 Adding all JARs in a directory to the classpath 1068 Classpath path syntax 1068 Dynamic Classpath 1069 Load a resource from the classpath 1069 Mapping classnames to pathnames 1070 What the classpath means: how searches work 1070 The bootstrap classpath 1071 Chapter 170: The Java Command - 'java' and 'javaw' 1073 Syntax 1073 Remarks 1073 Examples 1073 Running an executable JAR file 1073 Running a Java applications via a \"main\" class 1074 Running the HelloWorld class 1074 Specifying a classpath 1074 Entry point classes 1074 JavaFX entry-points 1075

Troubleshooting the 'java' command 1075 \"Command not found\" 1075 \"Could not find or load main class\" 1076 \"Main method not found in class <name>\" 1077 Other Resources 1077 1077 Running a Java application with library dependencies 1078 Spaces and other special characters in arguments 1079 Solutions using a POSIX shell 1080 Solution for Windows 1080 Java Options 1080 Setting system properties with -D 1081 Memory, Stack and Garbage Collector options 1081 Enabling and disabling assertions 1081 Selecting the VM type 1083 Chapter 171: The java.util.Objects Class 1083 Examples 1083 Basic use for object null check 1083 For null check in method 1083 For not null check in method 1083 1084 Objects.nonNull() method reference use in stream api 1084 Chapter 172: ThreadLocal 1084 Remarks 1084 Examples 1084 1086 ThreadLocal Java 8 functional initialization Basic ThreadLocal usage 1088 Multiple threads with one shared object 1088 1088 Chapter 173: TreeMap and TreeSet Introduction 1088 Examples 1089 TreeMap of a simple Java type TreeSet of a simple Java Type

TreeMap/TreeSet of a custom Java type 1089 TreeMap and TreeSet Thread Safety 1091 Chapter 174: Type Conversion 1093 Syntax 1093 Examples 1093 Non-numeric primitive casting 1093 Numeric primitive casting 1093 Object casting 1094 Basic Numeric Promotion 1094 Testing if an object can be cast using instanceof 1094 Chapter 175: Unit Testing 1096 Introduction 1096 Remarks 1096 1096 Unit Test Frameworks 1096 Unit Testing Tools 1096 Examples 1096 What is Unit Testing? 1098 Tests need to be automated 1098 Tests need to be fine-grained 1099 Enter unit-testing 1100 Chapter 176: Using Other Scripting Languages in Java 1100 1100 Introduction 1100 Remarks Examples 1100 Evaluating A javascript file in -scripting mode of nashorn 1103 1103 Chapter 177: Using the static keyword 1103 Syntax Examples 1103 1103 Using static to declare constants 1104 Using static with this Reference to non-static member from static context

Chapter 178: Using ThreadPoolExecutor in MultiThreaded applications. 1106 Introduction 1106 Examples 1106 Performing Asynchronous Tasks Where No Return Value Is Needed Using a Runnable Class Insta 1106 Performing Asynchronous Tasks Where a Return Value Is Needed Using a Callable Class Instan 1108 Defining Asynchronous Tasks Inline using Lambdas 1110 Chapter 179: Varargs (Variable Argument) 1113 Remarks 1113 Examples 1113 Specifying a varargs parameter 1113 Working with Varargs parameters 1113 Chapter 180: Visibility (controlling access to members of a class) 1115 Syntax 1115 Remarks 1115 Examples 1116 Interface members 1116 Public Visibility 1116 Private Visibility 1116 Package Visibility 1117 Protected Visibility 1118 Summary of Class Member Access Modifiers 1118 Chapter 181: WeakHashMap 1119 Introduction 1119 Examples 1119 Concepts of WeakHashmap 1119 Chapter 182: XJC 1121 Introduction 1121 Syntax 1121 Parameters 1121 Remarks 1121 Examples 1121 Generating Java code from simple XSD file 1121

XSD schema (schema.xsd) 1121 Using xjc 1122 1122 Result files package-info.java 1124 Chapter 183: XML Parsing using the JAXP APIs 1125 Remarks 1125 1125 Principles of the DOM interface 1125 Principles of the SAX interface 1126 Principles of the StAX interface 1126 Examples 1126 Parsing and navigating a document using the DOM API 1127 Parsing a document using the StAX API 1130 Chapter 184: XML XPath Evaluation 1130 Remarks 1130 Examples 1130 Evaluating a NodeList in an XML document 1131 Parsing multiple XPath Expressions in a single XML 1131 Parsing single XPath Expression multiple times in an XML 1133 Chapter 185: XOM - XML Object Model 1133 Examples 1133 Reading a XML file 1135 Writing to a XML File 1139 Credits

Chapter 69: InputStreams and OutputStreams Syntax • int read(byte[] b) throws IOException Remarks Note that most of the time you do NOT use InputStreams directly but use BufferedStreams, or similar. This is because InputStream reads from the source every time the read method is called. This can cause significant CPU usage in context switches into and out of the kernel. Examples Reading InputStream into a String Sometimes you may wish to read byte-input into a String. To do this you will need to find something that converts between byte and the \"native Java\" UTF-16 Codepoints used as char. That is done with a InputStreamReader. To speed the process up a bit, it's \"usual\" to allocate a buffer, so that we don't have too much overhead when reading from Input. Java SE 7 public String inputStreamToString(InputStream inputStream) throws Exception { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, \"UTF-8\"))) { int n; while ((n = reader.read(buffer)) != -1) { // all this code does is redirect the output of `reader` to `writer` in // 1024 byte chunks writer.write(buffer, 0, n); } } return writer.toString(); } Transforming this example to Java SE 6 (and lower)-compatible code is left out as an exercise for the reader. Writing bytes to an OutputStream Writing bytes to an OutputStream one byte at a time OutputStream stream = object.getOutputStream(); https://riptutorial.com/ 465

byte b = 0x00; stream.write( b ); Writing a byte array byte[] bytes = new byte[] { 0x00, 0x00 }; stream.write( bytes ); Writing a section of a byte array int offset = 1; int length = 2; byte[] bytes = new byte[] { 0xFF, 0x00, 0x00, 0xFF }; stream.write( bytes, offset, length ); Closing Streams Most streams must be closed when you are done with them, otherwise you could introduce a memory leak or leave a file open. It is important that streams are closed even if an exception is thrown. Java SE 7 try(FileWriter fw = new FileWriter(\"outfilename\"); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(\"the text\"); //more code out.println(\"more text\"); //more code } catch (IOException e) { //handle this however you } Remember: try-with-resources guarantees, that the resources have been closed when the block is exited, whether that happens with the usual control flow or because of an exception. Java SE 6 Sometimes, try-with-resources is not an option, or maybe you're supporting older version of Java 6 or earlier. In this case, proper handling is to use a finally block: FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter(\"myfile.txt\"); bw = new BufferedWriter(fw); out = new PrintWriter(bw); https://riptutorial.com/ 466

out.println(\"the text\"); out.close(); } catch (IOException e) { //handle this however you want } finally { try { if(out != null) out.close(); } catch (IOException e) { //typically not much you can do here... } } Note that closing a wrapper stream will also close its underlying stream. This means you cannot wrap a stream, close the wrapper and then continue using the original stream. Copying Input Stream to Output Stream This function copies data between two streams - void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[8192]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } Example - // reading from System.in and writing to System.out copy(System.in, System.out); Wrapping Input/Output Streams OutputStream and InputStream have many different classes, each of them with a unique functionality. By wrapping a stream around another, you gain the functionality of both streams. You can wrap a stream any number of times, just take note of the ordering. Useful combinations Writing characters to a file while using a buffer File myFile = new File(\"targetFile.txt\"); PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(myFile))); Compressing and encrypting data before writing to a file while using a buffer Cipher cipher = ... // Initialize cipher https://riptutorial.com/ 467

File myFile = new File(\"targetFile.enc\"); BufferedOutputStream outputStream = new BufferedOutputStream(new DeflaterOutputStream(new CipherOutputStream(new FileOutputStream(myFile), cipher))); List of Input/Output Stream wrappers Wrapper Description While OutputStream writes data one byte at a time, BufferedOutputStream/ BufferedOutputStream writes data in chunks. This reduces the BufferedInputStream number of system calls, thus improving performance. DeflaterOutputStream/ Performs data compression. DeflaterInputStream InflaterOutputStream/ Performs data decompression. InflaterInputStream CipherOutputStream/ Encrypts/Decrypts data. CipherInputStream DigestOutputStream/ Generates Message Digest to verify data integrity. DigestInputStream CheckedOutputStream/ Generates a CheckSum. CheckSum is a more trivial version CheckedInputStream of Message Digest. DataOutputStream/ Allows writing of primitive data types and Strings. Meant for DataInputStream writing bytes. Platform independent. Allows writing of primitive data types and Strings. Meant for PrintStream writing bytes. Platform dependent. Converts a OutputStream into a Writer. An OutputStream OutputStreamWriter deals with bytes while Writers deals with characters Automatically calls OutputStreamWriter. Allows writing of PrintWriter primitive data types and Strings. Strictly for writing characters and best for writing characters DataInputStream Example package com.streams; import java.io.*; public class DataStreamDemo { public static void main(String[] args) throws IOException { InputStream input = new FileInputStream(\"D:\\\\datastreamdemo.txt\"); DataInputStream inst = new DataInputStream(input); https://riptutorial.com/ 468

int count = input.available(); byte[] arr = new byte[count]; inst.read(arr); for (byte byt : arr) { char ki = (char) byt; System.out.print(ki+\"-\"); } } } Read InputStreams and OutputStreams online: https://riptutorial.com/java/topic/110/inputstreams- and-outputstreams https://riptutorial.com/ 469

Chapter 70: Installing Java (Standard Edition) Introduction This documentation page gives access to instructions for installing java standard edition on Windows, Linux, and macOS computers. Examples Setting %PATH% and %JAVA_HOME% after installing on Windows Assumptions: • An Oracle JDK has been installed. • The JDK was installed to the default directory. Setup steps 1. Open Windows Explorer. 2. In the navigation pane on the left right click on This PC (or Computer for older Windows versions). There is a shorter way without using the explorer in actual Windows versions: Just press Win+Pause 3. In the newly opened Control Panel window, left click Advanced System Settings which should be in the top left corner. This will open the System Properties window. Alternatively, type SystemPropertiesAdvanced (case insensitive) in the Run (Win+R), and hit Enter. 4. In the Advanced tab of System Properties select the Environment Variables... button in the lower right corner of the window. 5. Add a New System Variable by clicking the New... button in System Variables with the https://riptutorial.com/ 470

name JAVA_HOME and whose value is the path to the directory where the JDK was installed. After entering these values, press OK. 6. Scroll down the list of System Variables and select the Path variable. 7. CAUTION: Windows relies on Path to find important programs. If any or all of it is removed, Windows may not be able to function properly. It must be modified to allow Windows to run the JDK. With this in mind ,click the \"Edit...\" button with the Path variable selected. Add %JAVA_HOME%\\bin; to the beginning of the Path variable. It is better to append at the begining of the line because Oracle's software used to register their own version of Java in Path - This will cause your version to be ignored if it occurs after Oracle's declaration. Check your work 1. Open the command prompt by clicking Start then typing cmd and pressing Enter. 2. Enter javac -version into the prompt. If it was successful, then the version of the JDK will be printed to the screen. Note: If you have to try again, close the prompt before checking your work. This will force windows to get the new version of Path. Selecting an appropriate Java SE release There have been many releases of Java since the original Java 1.0 release in 1995. (Refer to Java version history for a summary.) However most releases have passed their official End Of Life dates. This means that the vendor (typically Oracle now) has ceased new development for the release, and no longer provides public / free patches for any bugs or security issues. (Private patch releases are typically available for people / organizations with a support contract; contact your vendor's sales office.) In general, the recommended Java SE release for use will be the latest update for the latest public version. Currently, this means the latest available Java 8 release. Java 9 is due for public release in 2017. (Java 7 has passed its End Of Life and the last public release was in April 2015. Java 7 and earlier releases are not recommended.) This recommendation applies for all new Java development, and anyone learning Java. It also https://riptutorial.com/ 471

applies to people who just want to run Java software provided by a third-party. Generally speaking, well-written Java code will work on a newer release of Java. (But check the software's release notes, and contact the author / supplier / vendor if you have doubts.) If you are working on an older Java codebase, you would be advised to ensure that your code runs on the latest release of Java. Deciding when to start using the features of newer Java releases is more difficult, as this will impact your ability to support customers who are unable or unwilling their Java installation. Java release and version naming Java release naming is a little confusing. There are actually two systems of naming and numbering, as shown in this table: JDK version Marketing name jdk-1.0 JDK 1.0 jdk-1.1 JDK 1.1 jdk-1.2 J2SE 1.2 ... ... jdk-1.5 J2SE 1.5 rebranded Java SE 5 jdk-1.6 Java SE 6 jdk-1.7 Java SE 7 jdk-1.8 Java SE 8 jdk-91 Java SE 9 (not released yet) 1 - It appears that Oracle intends to break from their previous practice of using a \"semantic version number\" scheme in the Java version strings. It remains to be seen if they will follow through with this. The \"SE\" in the marketing names refers to Standard Edition. This is the base release for running Java on most laptops, PCs and servers (apart from Android). There are two other official editions of Java: \"Java ME\" is the Micro Edition, and \"Java EE\" is the Enterprise Edition. The Android flavor of Java is also significantly different from Java SE. Java ME, Java EE and Android Java are outside of the scope of this Topic. The full version number for a Java release looks like this: 1.8.0_101-b13 This says JDK 1.8.0, Update 101, Build #13. Oracle refers to this in the release notes as: https://riptutorial.com/ 472

Java™ SE Development Kit 8, Update 101 (JDK 8u101) The update number is important -- Oracle regularly issue updates to a major release with security patches, bug fixes and (in some cases) new features. The build number is usually irrelevant. Note that Java 8 and Java 1.8 refer to the same thing; Java 8 is just the \"marketing\" name for Java 1.8. What do I need for Java Development A JDK installation and a text editor are the bare minimum for Java development. (It is nice to have a text editor that can do Java syntax highlighting, but you can do without.) However for serious development work it is recommended that you also use the following: • A Java IDE such as Eclipse, Intellij IDEA or NetBeans • A Java build tool such as Ant, Gradle or Maven • A version control system for managing your code base (with appropriate backups, and off- site replication) • Test tools and CI (continuous integration) tools Installing a Java JDK on Linux Using the Package Manager JDK and/or JRE releases for OpenJDK or Oracle can be installed using the package manager on most mainstream Linux distribution. (The choices that are available to you will depend on the distro.) As a general rule, the procedure is to open terminal window and run the commands shown below. (It is assumed that you have sufficient access to run commands as the \"root\" user ... which is what the sudo command does. If you do not, then please talk to your system's administrators.) Using the package manager is recommended because it (generally) makes it easier to keep your Java installation up to date. apt-get, Debian based Linux distributions (Ubuntu, etc) The following instructions will install Oracle Java 8: $ sudo add-apt-repository ppa:webupd8team/java $ sudo apt-get update $ sudo apt-get install oracle-java8-installer Note: To automatically set up the Java 8 environment variables, you can install the following package: $ sudo apt-get install oracle-java8-set-default Creating a .deb file https://riptutorial.com/ 473

If you prefer to create the .deb file yourself from the .tar.gz file downloaded from Oracle, do the following (assuming you've downloaded the .tar.gz to ./<jdk>.tar.gz): $ sudo apt-get install java-package # might not be available in default repos $ make-jpkg ./<jdk>.tar.gz # should not be run as root $ sudo dpkg -i *j2sdk*.deb Note: This expects the input to be provided as a \".tar.gz\" file. slackpkg, Slackware based Linux distributions sudo slapt-get install default-jdk yum, RedHat, CentOS, etc sudo yum install java-1.8.0-openjdk-devel.x86_64 dnf, Fedora On recent Fedora releases, yum has been superseded by dnf. sudo dnf install java-1.8.0-openjdk-devel.x86_64 In recent Fedora releases, there are no packages for installing Java 7 and earlier. pacman, Arch based Linux distributions sudo pacman -S jdk8-openjdk Using sudo is not required if you're running as the root user. Gentoo Linux The Gentoo Java guide is maintained by the Gentoo Java team and keeps an updated wiki page including the correct portage packages and USE flags needed. Installing Oracle JDKs on Redhat, CentOS, Fedora Installing JDK from an Oracle JDK or JRE tar.gz file. 1. Download the appropriate Oracle archive (\"tar.gz\") file for the desired release from the Oracle Java downloads site. 2. Change directory to the place where you want to put the installation; 3. Decompress the archive file; e.g. tar xzvf jdk-8u67-linux-x64.tar.gz https://riptutorial.com/ 474


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook