Java — java coredump


Содержание

Khai’s personal knowledge vault.

Materials on this site are not original. When possible, references to original articles are listed on each page.

https://www.youtube.com/watch?v=78hvWy_c88Y — thread state in java thread dump analysis — good
https://www.youtube.com/watch?v=1qzHSEjU8Hc — Thread Dump Analysis Fundamentals — Part 1 — Pierre-Hugues Charbonneau — done watching
https://www.youtube.com/watch?v=H34ZEkrJV1k — Thread Dump Analysis Fundamentals — Part 2 — Pierre-Hugues Charbonneau
https://www.youtube.com/watch?v=1qzHSEjU8Hc&list=PLeLNWvESQ0GaJv8VCelD0bXiTIcVCRuSC — Pierre-Hugues Charbonneau

How can we enable core dump?

To enable core dumping, try «ulimit -c unlimited» before starting Java again.

The ulimit utility is used to get or set the limitations on the system resources available to the current shell and its descendants. Use the ulimit -c command to check or set the core file size limit. Make sure that the limit is set to unlimited; otherwise the core file could be truncated.

ulimit is a Bash shell built-in command; on a C shell, use the limit command.

Where can we find the core dump file?

On the Linux operating system, unhandled signals such as segmentation violation, illegal instruction, and so forth, result in a core dump. By default, the core dump is created in the current working directory of the process and the name of the core dump file is core.pid, where pid is the process id of the crashed Java process.

How can we take a core dump on Linux?

To get the list of Java processes running on the machine, you can use any of the following commands:

The jps command-line utility does not perform name matching (that is, looking for «java» in the process command name) and so it can list Java VM embedded processes as well as the Java processes.

The following is one option to collect core dumps on Linux.

ShowMessageBoxOnError option in Linux: A Java process can be started with the -XX:+ShowMessageBoxOnError command-line option. When a fatal error is encountered, the process prints a message to standard error and waits for a yes or no response from standard input. Example 17-3 shows the output when an unexpected signal occurs.

Type yes to launch the gdb (GNU Debugger) interface, as suggested by the error report shown above. In the gdb prompt, you can give the gcore command. This command creates a core dump of the debugged process with the name core.pid, where pid is the process ID of the crashed process. Make sure that the gdb gcore command is supported in your versions of gdb. Look for help gcore in the gdb command prompt.

In order to generate a dump, we need to know the PID of the Java program. The above commands help us determine the PID of the Java program. Different ways to generate a dump:

  1. kill -3 PID
  2. jstack PID
  3. Java Visual VM
  4. Weblogic Admin Console — Monitory tab

jstack is part of JDK. Some production environment only have JRE installed, and therefore jstack is not available. In such cases, we can use the kill -3 PID command to generate the dump. With the kill -3 PID command, the dump is sent to the console / terminal that is running the Java program, which is typically not the console that we are currently using. For Tomcat, the dump is output to the catalina.out file. With the jstack PID command, the dump is output to the console that we use to run the jstack command. This is a bit of a convenient for us. However, if the machine is struggling, using the kill -3 PID command may be a faster way to generate the dump. Java Visual VM is nice but, like jstack, it is also a bit resource-intensive compared to the kill -3 PID command.

With the WebLogic Admin Console — Monitoring tab, WebLogic tries to be helpful by reducing some information, but sometime, that information happens to be what we need. In that case, we just have to fall back to using the jstack PID command , or kill -3 PID command.

We should have a way to use New Relic or some other tools to automatically detect deadlock, database connection leaks, data leak, and automatically send these problematic dumps to us.

How can we specify the location of Fatal Error Log?

To specify where the log file will be created, use the product flag -XX:ErrorFile=file, where file represents the full path for the log file location. The substring %% in the file variable is converted to %, and the substring %p is converted to the PID of the process. In the following example, the error log file will be written to the directory /var/log/java and will be named java_errorpid.log:

If the -XX:ErrorFile=file flag is not specified, the default log file name is hs_err_p >

What is a core dump?

A core dump or a crash dump is a memory snapshot of a running process. A core dump can be automatically created by the operating system when a fatal or unhandled error (for example, signal or system exception) occurs. Alternatively, a core dump can be forced by means of system-provided command-line utilities. Sometimes a core dump is useful when diagnosing a process that appears to be hung; the core dump may reveal information about the cause of the hang.

When collecting a core dump, be sure to gather other information about the environment so that the core file can be analyzed (for example, OS version, patch information, and the fatal error log).

Core dumps do not usually contain all the memory pages of the crashed or hung process. With each of the operating systems discussed here, the text (or code) pages of the process are not included in core dumps. But to be useful, a core dump must consist of pages of heap and stack as a minimum. Collecting non-truncated good core dump files is essential for postmortem analysis of the crash.

What are the reasons for not getting a core file?

The following list explains the major reasons that a core file might not be generated. This list pertains to both Oracle Solaris and Linux operating systems, unless specified otherwise.

  1. The current user does not have permission to write in the current working directory of the process.
  2. The current user has write permission on the current working directory, but there is already a file named core that has read-only permission.
  3. The current directory does not have enough space or there is no space left.
  4. The current directory has a subdirectory named core.
  5. The current working directory is remote. It might be mapped by NFS (Network File System), and NFS failed just at the time the core dump was about to be created.
  6. Oracle Solaris operating system only: The coreadm tool has been used to configure the directory and name of the core file, but any of the above reasons apply for the configured directory or filename.
  7. The core file size limit is too low. Check your core file limit using the ulimit -c command (Bash shell) or the limit -c command (C shell). If the output from this command is not unlimited, the core dump file size might not be large enough. If this is the case, you will get truncated core dumps or no core dump at all. In addition, ensure that any scripts that are used to launch the VM or your application do not disable core dump creation.
  8. The process is running a setuid program and therefore the operating system will not dump core unless it is configured explicitly.
  9. Java specific: If the process received SIGSEGV or SIGILL but no core dump, it is possible that the process handled it. For example, HotSpot VM uses the SIGSEGV signal for legitimate purposes, such as throwing NullPointerException, deoptimization, and so forth. The signal is unhandled by the Java VM only if the current instruction (PC) falls outside Java VM generated code. These are the only cases in which HotSpot dumps core.

  10. Java specific: The JNI Invocation API was used to create the VM. The standard Java launcher was not used. The custom Java launcher program handled the signal by just consuming it and produced the log entry silently. This situation has occurred with certain Application Servers and Web Servers. These Java VM embedding programs transparently attempt to restart (fail over) the system after an abnormal termination. In this case, the fact that a core dump is not produced is a feature and not a bug.

How can we collect core dump on Windows?

On Windows operating system there are three types of crash dumps:

  1. Dr. Watson logfile, which is a text error log file that includes faulting stack trace and a few other details.
  2. User minidump, which can be considered a «partial» core dump. It is not a complete core dump, because it does not contain all the useful memory pages of the process.
  3. Dr. Watson full-dump, which is equivalent to a Unix core dump. This dump contains most memory pages of the process (except for code pages).

When an unexpected exception occurs on Windows, the action taken depends on two values in the following registry key: \\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AeDebug

The two values are named Debugger and Auto. The Auto value indicates if the debugger specified in the value of the Debugger entry starts automatically when an application error occurs.

  1. A value of 0 for Auto means that the system displays a message box notifying the user when an application error occurs.
  2. A value of 1 for Auto means that the debugger starts automatically.

The value of Debugger is the debugger command that is to be used to debug program errors. When a program error occurs, Windows examines the Auto value and if the value is 0 it executes the command in the Debugger value. If the value for Debugger is a valid command, a message box is created with two buttons: OK and Cancel. If the user clicks OK, the program is terminated. If the user clicks Cancel, the specified debugger is started. If the value for the Auto entry is set to 1 and the value for the Debugger entry specifies the command for a valid debugger, the system automatically starts the debugger and does not generate a message box.

The following are two ways to collect crash dump on Windows:

  1. Configure Dr.Watson
  2. Force a crash dump

How can we configure Dr.Watson to take a crash dump on Windows?

The Dr. Watson debugger is used to create crash dump files. By default, the Dr. Watson debugger (drwtsn32.exe) is installed into the Windows system folder (%SystemRoot%\System32). To install Dr. Watson as the postmortem debugger, run the following command: drwtsn32 -i

To configure name and location of crash dump files, run drwtsn32 without any options. In the Dr. Watson GUI window, make sure that the Create Crash Dump File check box is selected and that the crash dump file path and log file path are configured in their respective text fields. Dr. Watson may be configured to create a full dump using the registry. The registry key is shown in Example 17-4.

Note: If the application handles the exception, then the registry-configured debugger is not invoked. In that case it might be appropriate to use the -XX:+ShowMessageBoxOnError command-line option to force the process to wait for user intervention on fatal error conditions.

How can we force a crash dump on Windows?

On the Windows operating system, the userdump command-line utility can be used to force a Dr. Watson dump of a running process. The userdump utility does not ship with Windows but instead is released as a component of the OEM Support Tools package. An alternative way to force a crash dump is to use the windbg debugger. The main advantage of using windbg is that it can attach to a process in a non-invasive manner (that is, read-only). Normally Windows terminates a process after a crash dump is obtained but with the non-invasive attach it is possible to obtain a crash dump and let the process continue. To attach the debugger non-invasively requires selecting the Attach to Process option and the Noninvasive checkbox.

When the debugger is attached, a crash dump can be obtained using the command shown:

The windbg debugger is included in the «Debugging Tools for Windows» download. An additional utility in this download is the dumpchk.exe utility, which can verify that a memory dump file has been created correctly. Both userdump.exe and windbg require the pid of the process. The userdump -p command lists the process and program for all processes. This is useful if you know that the application is started with the java.exe launcher. However, if a custom launcher is used (embedded VM), it might be difficult to recognize the process. In that case you can use the jps command-line utility as it lists the pids of the Java processes only.

As with Oracle Solaris and Linux operating systems, you can also use the -XX:+ShowMessageBoxOnError command-line option on Windows. When a fatal error is encountered, the process shows a message box and waits for a yes or no response from the user. Before clicking Yes or No, you can use the userdump.exe utility to generate the Dr. Watson dump for the Java process. This utility can also be used in cases when the process appears to be hung.

Examples:

WAITING: a thread is in the waiting state and this wait is over only when some other thread perform some appropriate action.

Что такое ядро ​​Java и передовые Java

Я слышал большую часть времени люди говорят, что ядро ​​Java и расширенный java.I хотел бы знать, в чем разница между основной Java и передовых Java.

Цукерберг рекомендует:  Math - Помогите написать код для формулы OpenOffice Math

«Core Java» является AFAIK не является официальным, а определенный срок. Это, однако, название книги от солнца, который вводит Java как язык и наиболее важные части стандартного API Java SE — и это, вероятно, что большинство людей думают о том, когда они слышат термин.

«Advanced Java» бы тогда все, что выходит за рамки этого — самое главное в API-интерфейсы, определенные в Java Enterprise Edition, то есть Servlet программирование, Web-сервисы, тем Java Persistence API, и т.д.

Я не тот, кто «люди», но они могут относиться к Java SE как «ядро» и Java EE, как «продвинутый».

Там нет четкого различия. Я бы сказал, что «Core Java» является:

Все остальное «передовые».

Как мне известно основное различие между основной Java и передовых Java является то, что, Core Java используется для разработки общего приложения Java, где, как Advanced Java используется для разработки веб-приложений и корпоративных приложений. Ядро Java испытывает концепцию Java Основы, апплета, Качели, JDBC, JavaBeans.

Вы можете рассмотреть Java Core, как язык API Basic Java / Классы / Lib, который является Java SE. Advanced Java написано поверх ядра Java за ядро ​​Java классов и библиотеки.

Основное различие между ядром и заблаговременного Java:

Ядро Java: J2SE

Advance Java: J2EE


Вероятно, «ядро Java» является Java SE, другими словами материал доступен в стандартной версии (без Java EE, нет Java ME).

Расширенный затем остальные!

Вот одно объяснение перечисленное на основе этой точки зрения пользователя на WikiAnswers — Какова разница между основной Java и передовые Java? Вы можете прочитать больше, если вам нравится.

Ядро Java имеет дело с основным пакетом объектов Java, которые обычно используются для общих приложений для настольных компьютеров. Эти объекты входят в «Standard Edition» Ява

Advanced Java действительно может относиться к любой продвинутой теме, имеющей отношение к Java programming— и есть много.

Как было отмечено в комментарии, не существует конкретное определение того , что различия, ( или даже то , что определение термина Ядро Java ) этот термин может быть использован свободно и определение будет варьироваться в зависимости от пользователя к пользователю.

Там нет нет ядра и передовые Java в Java мире . У нас есть только J2SE, J2EE и J2ME. В Основах концепции Java , который имеет дело в основном с OOPS понятий и их реализации в языке можно назвать основной Java. Advanced Java означает , чтобы получить краткие знания о какой — либо конкретной концепции Java.

Те, кто знает Advanced Java они знают Core, Java, но не наоборот

Что это называется, если вы работаете с очень сложными алгоритмами, которые используют только Core, Java? Расширенное Ядро Java программирование?

Что делать, если вы пишете очень простые приложения Java EE? Простое программирование Advanced Java?

Я хотел бы сказать, ядро ​​Java является Java SE. Advanced Java это то, что является более сложным, чем простое программирование. Некоторые строго Основные Java программы могут быть Advanced Java. Некоторый Advanced Java может использовать больше, чем просто ядро ​​Java.

Сказать, что Advanced Java == Java EE и Java Ядро == Java SE кажется глупым мне.

GDB: Debug native part of java application (C/C++ libraries and JDK)

Why debugging of C/C++ code may be required for Java developers?

I worked with a few java projects that used native libraries created by another team from the same organization. Usually, we invoked C++ code from java.

The issue with C++ code invoked from Java is that it is usually not visible from java. We only see a top-level interface with JNI/JNA but don’t know what is going under the hood.

As a result, we can’t get a lot of information from java debugger and profiler that we use daily.

In this post, I’ll describe a gdb debugger that is able to work with the native code. As an example, we will build a C++ library for Linux (.so-file), invoke from Java and debug it.

As low-level part of JDK is also written in C++, we will take a look at how to debug JDK native code also.

GDB or GNU Debugger is a command-line debugger that comes with most Linux distributions and supports lots of processors. GDB supports both remote and local mode.

It is important to note that as of now GDB doesn’t support debugging of Java code (on https://www.gnu.org/software/gdb/ you won’t find Java in the list of supported languages ). If you want to debug java code from command-line you can try JDB. It looks similar to GDB but has less functionality.

Having said that GDB doesn’t allow you to debug java-code, it can perfectly debug a native part (written not in java) of Java application. If it is important for you to debug both Java and native code “from the same IDE”, you can try to use Netbeans or Eclipse. Netbeans uses default debugger for Java code and GDB for native code. However, for IDE users switch between Java and the native code won’t be visible.

Of course, command-line debugging may look weird at first for people familiar with IDEs. But it has some benefits. One of them is the ability to run on a remote host. Although remote debug is built-in in java, debugging an application running in another part of the globe using IDE remote debuggers could be very sloooooow. GDB from the other hand runs on the target host. This is especially useful when you need to evaluate some code during debugging.

Prepare native code

All code is available in my github repo.

To be able to see a native code in the debugger, the code should be compiled in a special way. Information about method names and variables should be included in the library or comes as a separate package.

Often the easiest way to include debug info is to add it to the resulted library. Let’s write a simple java application and a C++ library.

We define an interface of native methods and load the library. The code won’t run, because the library doesn’t exist right now. We will build it soon.

Method’s names are self-describing: nativePrint — prints constant string to stdout, nativeSleep — sleeps for ms milliseconds, nativeAllocate — allocates memory for an array of size n, nativeCrash — crashes application (we will simulate a crash at the end of the article to check what information is available for investigation).

Let’s generate a c++ header file (interface) for methods defined in JNIDemoJava.java.

After we got a definition of C++ methods we can implement them:

Java Thread Dump Analyzer

Troubleshoot JVM crashes, slowdowns, memory leaks, freezes, CPU Spikes
Upload thread dumps

(uncompressed or .zip, .gz formats):

#1 thread dump analysis tool

fastThread is the DevOps engineers favorite thread dump analysis tool to troubleshoot complex production problems.

Universal Thread dump Analysis

fastThread, a universal tool that will parse and analyze thread dumps written in any language that runs on the JVM. It will convert your Java, Scala, Jython, JRuby thread dumps to useful information for root cause analysis (RCA).

Intuitive Dashboard

Get a simple but easy to understand view of your thread analysis through intuitive data display. View your blocked, runnable, timed waiting, waiting and repeating stack traces in a click. Reliably fix scalability, performance and availability issues quickly and at your convenience.

Online Thread dump analyzer

There is no hazzle to register or download or install the tool in your machine. Just upload your applications thread dump files & review the reports instantly.


REST API

fastThread has built industry’s first (and only) REST API to analyze thread dumps. Instead of manually uploading and analyzing thread dumps — you can analyze thread dumps from all your JVMs in a programmatic manner.

Core dump analysis

Java core dump has lot of rich information but in a hard to understand/digest format. fastThread.io can analyze Java core dump files and provide you precise information in a graphical format.

hs_err_pid analysis

A crashes or fatal error causes a JVM to terminate abnormally. When JVM terminate abnormally it creates hs_err_pid file. This file has lot of information, fastThread helps you to analyze this hs_err_pid file effectively.

How it works?

Capture thread dumps

There are 8 different options to capture thread dumps. Use the one that suits you.

Upload thread dumps to fastThread.io

Upload the captured thread dumps file to fastThread.io

Review the report

Review our world-class analysis report. Our Deep learning algorithms instantly spots root cause of complex problems.

You can also use REST API

To analyze hundreds/thousands of JVMs thread dumps in a proactive manner, use our REST API

Ultimate DevOps Tool

fastThread liberates DevOps from engaging vendors to troubleshoot your production problems. This highly effective and efficient tool allows DevOps to instantly identify and resolve root cause issues in matter of seconds. Designed with intelligent patterns, you can trace the problem right down to the exact class, method and even line number.

Our Machine learning algorithms can detect patterns and it can forecast problems that’s going to happen in near future. It can tell you very soon your application is going to experience OutOfMemoryError, very soon your application’s CPU is going to spike up.

Beyond APM

Application Performance Monitoring (APM) tools are great at telling that your application’s CPU spiked up by x%, your memory degraded by y%, your response time increased by z milliseconds. But it won’t tell you what caused the CPU to spike? what caused the memory consumption to degrade? what caused the response time to increase?

fastThread answers these questions. It can tell you exact class, exact method, exact line of code that caused the problem. Beauty is: it does the analysis without adding runtime overhead to your application.

REST API

Leverage our light-weight REST APIs to do pro-active thread dump analysis on all your production JVMs. Build alerts. Never have down-time.

Tag Archives: java core dump

Where is the JVM Dump file physically located in JBoss Server environment?

I was debugging an enterprise application at my office today and suddenly got a heap dump – so I thought of creating a new post in this blog about the location of the JVM dump file in JBoss 4.0.5 server along with the stack trace of the error (and what other files are created during dump process). My IDE is IBM’s Rational Software Architecht (RSA) and I am running my JBoss server against a JDK of 1.4.2_12.

As you can see in the stack trace below, the java dump files are located at JBoss bin folder. There were basically three files created during this dump process:

  • System Dump File – core.20100830.093556.8156.dmp
  • Snap Dump File – Snap0001.20100830.093556.8156.trc
  • Java Dump file – javacore.20100830.093556.8156.txt

Java — java coredump

The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.

Java Tutorial Network

Java Tutorials for Beginners and Professionals

Java Core

How to install Maven on Windows, Linux and Mac

In this tutorial, we will be going through the installation process of Maven. If you are a WINDOWS user (if you are not, scroll down to view how to install Maven if you are a Linux or Mac user): Before proceeding with the next steps, make sure you have JDK installed on your system. If…

How to use Maven profiles

Simply said, Maven profile is a set of configuration value which override default values. By using it, it allows you to create a custom build for different environments (Production/Development). Before we proceed with the tutorial’s content, it is assumed you have Maven installed. In case you don’t, follow this tutorial for a step-by-step guide. To…

How to include custom library into maven local repository

If you’ve ever wondered whether you can upload your own libraries as a dependency using Maven, the answer is yes, you can. And it is really simple. It’s a 2-step process. Step 1 Navigate to your Maven project path in the command line and to upload a library, that’s the structure of the maven command:…

How to use JUnit for unit testing

What is software testing and why is it useful? Testing software in the simplest terms is to evaluate whether it meets all the requirements or not and to also inspect if there are any misbehaviors and bugs associated with its currents state. Testing in Java Java has multiple testing frameworks available, however, in this tutorial,…


How to run JUnit test with Maven

This tutorial will cover how to run Unit tests using the Maven’s Surefire plugin. If you are not familiar with Unit Testing, you can follow this tutorial for a quick catch-up. In our Maven Project, we need the following mandatory dependencies: org.junit.jupiter junit-jupiter-api 5.4.2 test org.junit.jupiter junit-jupiter-engine 5.4.2 test …

How to create submodules with Maven in Java

What you will need. IDE or a text editor JDK 1.8 or above Maven What exactly is Maven’s multi-module? This multi-module project is built off of a POM aggregator that handles multiple submodules. Often the aggregator is located in the project’s root directory and must have packaging of type pom. The submodules are Maven projects…

How to create Java JAR file with Maven

We do not normally need additional dependencies when it comes to creating an executable jar. All we need to do is create a Maven Java project and have a minimum of 1 class alongside the main method. Please note that we assume you have Maven installed on your machine. In case you don’t, follow this tutorial…

How to create Java WAR file with Maven

Before proceeding with the next steps, make sure you have JDK and Maven installed on your system. If you don’t have JDK installed, click here. If you don’t have Maven installed, click here. 1. Generating a WAR file using Eclipse Step 1 – Open Eclipse and create a new Maven project (File->New->Other->Maven Project) Step 2…

JVM Explained

This article describes the Java Virtual Machine (JVM) and its architecture

Java Memory Model Explained with Examples

Memory can be described as an array of bytes where you can access each byte individually. In each byte or rather, location, in the memory, there is data that you can access, just like in arrays in Java. In 32-bit architectures, each memory “slot” contains 32 bits, or also called 1 word, or just 4…

Top 3 Methods for Capturing Java Heap Dump

In this post, I’ll teach you multiple methods for capturing java heap dump. Critical for memory consumption optimisation, a heap dump is described as a memory print of the Java process.

Java Garbage Collection

This article discusses about Java Garbage Collection (GC) which is considered as one of the complex topics in Java programming language.

Java Mutex Example

Let’s give an example first before going deeper into what Mutex is: Think of a queue. Doesn’t matter short or long. Now think of a truck that is selling tickets for an amusement park. One person at a time can buy a ticket. When the person has bought the ticket, it is time for the…

Java Semaphore example

Semaphore can be used to limit the amount of concurrent threads and essentially, this class maintains a set of permits. acquire() takes a permit from the semaphore and release() returns the permit back to the semaphore. In the event of absence of permits, acuire() will block until one is available Semaphore is used to control…

Цукерберг рекомендует:  Javascript - Как создать массив из элементов с одинаковым классом в JS

Java Parallel Streams Example

Stream API allows developers to take advatange of multi core architectures and improve the performance of Java program by creating parallel streams and making your program perform operations faster. There are two ways of creating a parallel stream: by using the parallelStream() method by using the parallel() method When you are using parallel streams, effectively…

Java thread synchronization

This article talks about the importance of thread synchronization in Java and how you can implement it in your programs.

Java Thread Pool Example

Active threads consume system resources, which can cause JVM creating too many threads which means that the system will quickly run out of memory. That’s the problem Thread Pool in Java helps solving. How Thread Pools work? Thread Pool reuses previously created threads for current tasks. That solves the problem of the need of too…

ThreadLocal Java Example

Livelock and Deadlock In Java

The following article talks about the livelock and deadlock states in java, how they occur and what can be done to avoid them.

Java Future Example

The result of an asynchronous computation is called Future and more specifically, it has this name because it (the result) will be completed at a later point of time in the future. Future object is created when an asynchronous task has been created. There are many methods that are provided that help to retrieve the result (using get methods(which is…

Java equals() Method Example

Java equals() method and the “==” operator are both used to compare objects for equality. However, they are doing the checking in a very different way, generating different results. The main difference between them is that “==” checks if both objects point to the same memory location and equals() evaluates to the comparison of the…

Java Lambda Expressions Tutorial

Java 8 introduced Lambda Expressions and is one of the biggest, if not the biggest, feature that was introduced because Lambda expression makes functional programming possible and it makes your code way cleaner and overall simplifies the whole code implementation drastically. For example, when you have to work with anonymous class and that class is…

Java Optional Example

Java 8 introduced Optional class which is used to manipulate data based on whether a value is present or absent. You can have the same functionality without using this class, however you would end up with way messier code. In other words, you will have less null checks and no NullPointerException’s. Let me give you…

Java 11 HTTP Client Example

Java 11 introduced the HTTP Client which can be used to send requests over the network and retrieves their responses. HTTP Client replaces the HttpUrlConnection class as it is considered old and doesn’t support ease of use. HTTP Client API supports both HTTP/1.1 and HTTP/2. HttpClient is also immutable, meaning it can be used to…

Java > October 9, 2020 October 25, 2020 filip

This article explains the key components of Java class loaders.

Java Enum Example

Enum type is a special data type which holds different constants such as WHITE, BLACK, RED. The convention is that they should be named with upper case because, again, they are constants. In java, you define enum type by using the enum keyword. public enum Macronutrients < FATS, CARBOHYDRATES, PROTEIN >If you know all the…


Java hashCode() Method Example

The super class in Java java.lang.Object provides two important methods for comparing objects: equals() and hashcode(). These methods are widely used when faced against implementing an interaction between classes. In this tutorial, we are only going to look at hashCode(). Method Definition and Implementation hashCode(): By default, this method returns a random integer that is unique every time. If you execute…

How to profile standalone java applications

What are unit tests? Unit tests are a method of software testing in which small components of a Java application are being tested. Its purpose is to confirm the fact that every piece of the software behaves as expected. And even if it is, you can use unit testing to determine whether another implementation would…

SWING JFrame basics, how to create JFrame

This tutorial explains JFrame basics from creation to customization.

Java SWING JFrame Layouts Example

This tutorial explains various JFrmae layouts with examples and use.

Display text and graphics in Java on JFrame

This tutorial explains how to display text and graphics on JFrmae for example, lines, circle and rectangle.

Interact with JFrame – buttons, listeners and text fields

This tutorial explains how you can interact with JFrame by using buttons, listeners and text fields.

How to create Java JAR file with Maven

This tutorial will explain how to create Java JAR file with Maven with step by step guidelines and screen shots.

Java Collection Beginner’s Gu > January 25, 2020 October 27, 2020 filip

The “Collections” framework in Java came into action with the release of JDK 1.2 and was expanded quite a few times in Java 1.4 and Java 5 and then again in Java 6.

Choose the Right Java Collection

Java offers you a variety of collection implementations to choose from. In general you will always look for the collection with the best performance for your programming task, which in most cases is ArrayList, HashSet or HashMap. But be aware, if you need some special features like sorting or ordering you may need to go for a special…

Java ArrayList Example

Java ArrayList class is a resizable array that implements the List interface. It permits all elements, including null and also implements all optional list operations. Most operations that can be run on ArrayList such as size, isEmpty, get, set, iterator and listIterator are all constant time. However, the add operation’s complexity is O(n) time. Compared to LinkedList, the…

Java LinkedList Example

LinkedList class in Java uses a doubly linked list to store elements and it also provides a linked-list data structure. It implements List, just like ArrayList class, and Deque interfaces. Just like arrays, Linked List is a linear data structure but unlike arrays, the elements in the linked list are linked together using pointers. There…

Java HashSet Example

Collections that use a hash table for storage are usually created by the Java HashSet class. As the name suggests, HashSet implements the Set interface and it also uses a hash table which is a HashMap instance. The order of the elements in HashSet is random. The null element is permitted by this class. In…

Java TreeSet Example

Java TreeSet class is a NavigableSet implementation that is based on TreeMap. The elements are either ordered by a Comparator or simply by their natural ordering. In terms of complexity, this implementation provides log(n) time cost for all basic operations like add, remove, contains. What is important to know about TreeSet in Java TreeSet implements the…

Java LinkedHashSet Example

LinkedHashSet class in Java differs from HashSet as its implementation maintains a doubly-linked list across all elements. This linked list defines the iteration ordering which is the order in which the elements were inserted into the set. It is called an insertion-order. If an element is re-inserted into the set, the insertion order is not affected by…

Java EnumSet Example

Java EnumSet class implements Set and uses it with enum types. EnumSet (as the name suggests) can contain only enum values and all the values belong to the same enum. In addition, EnumSet does not permit null values which means it throws a NullPointerException in attempt to add null values. It is not thread-safe which means if required,…

Java ConcurrentHashSet Example

Java 8 finally allows us, the programmers, to create thread-safe ConcurrentHashSet in Java. Before then, it was simply not possible. There were variations that tried to improvise the implementation of the above-mentioned class, one of which would be, using ConcurrentHashMap with a dummy value. However, as you might have guessed, all of the improvisations of…

Java HashMap Example

Arrays’ items are stored as an ordered collection and we can access them by indices. HashMap class in Java on the other hand, stores items in a group pairs, key/value. They can be accessed by an index of another type. This class does not guarantee that there will be a constant order over time. HashMap provides…

Java LinkedHashMap Example

LinkedHashMap is a combination of hash table and linked list that implement the Map interface with predictable iteration order. The difference between HashMap and LinkedHashMap is that LinkedHashMap maintains a doubly-linked list which allows scanning through all of its entries back and forth. The order is maintained, meaning the order in which keys were inserted…

Java TreeMap Example

TreeMap implements the Map interface and also NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys or by a Comparator provided a the time of initialization. In terms of time complexity, this implementation provides log(n) cost for the containsKey, get, put and remove operations. It’s important…

Java EnumMap Example

EnumMap class implements the Map class and enables the use of enum type keys. Enum maps are maintained in the natural order of their keys. It is important to note that null keys are not permitted. If attempt has been made for adding a null key, NullPointerException will be thrown. However, even though null keys are not allowed, null values are. Since all…

Java WeakHashMap Example

WeakHashMap in Java implements the Map interface and represents a hash table that has weak keys. If a key is not in an ordinary use, the entry from the map will be automatically removed. This is what differentiates it from other Map implementations. Null and non-null values are supported and the performance is similar to HashMap class in and…

Java > June 27, 2020 October 28, 2020 ym_coding

Java SortedMap Example


SortedMap interface extends Map and ensures that all entries are in an ascending key order (hence SortedMap). If you want to have it in a descending order, you will need to override the Compare method in the SortedMap which we will do shortly. TreeMap implements SortedMap and it either orders the keys by their natural…

Java ConcurrentMap Example

Even though Map is implemented by many classes, many of them are not thread-safe or some of them are but not efficient. This is why ConcurrentMap was introduced in Java 1.5. It is thread-safe and efficient. Overridden default implementations: compute replaceAll forEach getOrDefault computerIfAbsent computerIfPresent ConcurrentMap consists of an array of nodes that are represented as table…

Java Hashtable Example

Hashtable implements a hash table (as the name suggests) and maps keys to values (like LinkedHashMap). Hashtable class allows non-null objects to be used as a key or as a value. Just like HashMap, Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash…

Difference Between ArrayList and LinkedList in Java

This article explains the differences between ArrayList and LinkedList and in which case we should prefer the one over the other.

Java Iterate through a HashMap Example

This examples shows you how to iterate through a HashMap in Java

Java HashMap Inline Initialization

Following examples demonstrate how to initialize a Java HashMap using standard and inline methods.

Difference between HashMap and TreeMap in Java

In this article I will explain the difference between java HashMap and java TreeMap

Graphs Java Example

Graphs are usually made from vertices and arcs. Sometimes they are also called nodes (instead of vertices) and edges (instead of arcs). For the sake of this tutorial I will be using nodes and edges as reference. Graphs usually look something like this: In many cases, the nodes and the edges are assigned values to…

Depth-First-Search Example Java

Searching and/or traversing are equally important when it comes to accessing data from a given data structure in Java. Graphs and Trees are an example of data structures which can be searched and/or traversed using different methods. Depth-first-search, DFS in short, starts with an unvisited node and starts selecting an adjacent node until there is…

Breadth-First-Search Example Java

Searching or traversing is really important when it comes to accessing data from a given data structure. There are different methods of traversing/searching elements within these data structures such as Graphs and Trees. Breadth-first search is one example of these methods. BFS is an algorithm that traverses tree or graph and it starts from the…

Different Algorithm Time Complexities

Before starting to explain the different time complexities, let’s first look at what an actual algorithm is. The formal definition of an algorithm is “a process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer.”. So in other words, an algorithm is a defined path which is…

Java Serialization example

Serialized object. What does that mean? Java provides a functionality which represents an object as a sequence of bytes which include the object’s data and also information about the object’s type and the types of data stored in that object. When a serialized object has been written into a file, it can later be deserialized,…

Java Reflection Example

Reflection (which is a feature in Java) allows executing Java program to examine itself (or another code) and manipulate internal properties of the program such as obtaining names of members and perform something on them, like deleting them or displaying them. By default, every object in Java has getClass() which basically determines the current object’s…

Weak references in Java

This article discusses the concept of weak references in Java.

Java 8 Date Time API

Java 8 introduced a new Date-Time API which purpose is to cover drawbacks of the old date-time API. The previous date-time api was not thread safe and the replacement for the new date-time API is that it does not have any setter methods. Another drawback that is fixed by the new API is the poor…

Basic Java Regular Expressions

Today I will show you the very basics of Regular Expressions and how to use them in Java.

Retrieve Free Disk Space with Java

Sometimes you wish to know how much disk space is left on your hard drive. There are several ways to do that. In this example I will show you how to do this with Apache commons.

Java generate MD5 hash sum

In this example I will show you how to generate the MD5 hex sum for a given string using Java

Java Increase Memory

The Java memory model specifies how the Java virtual machine works with the computer’s memory (RAM). In this tutorial I will show you how to configure the memory used by Java.

Java Properties File Example

In this tutorial I will show you how to store and retrieve values from a properties file in Java

How to Install Java 9 Beta on Eclipse

This tutorial demonstrates how to install and configure Java 9 Beta on Eclipse Oxygen

Java 9 JShell Example

This tutorial explains how to use the JShell tool in Java 9


Java 9 Immutable List Example

This example demonstrates how to create immutable lists with the new Java 9 Collections factory methods

Java 9 Immutable Set Example

This example demonstrates how to create immutable Set with the new Java 9 Collections factory methods

Java 9 Immutable Map Example

This example demonstrates how to create immutable Map with the new Java 9 Collections factory methods

Java Singleton Design Pattern Example

As we know design pattern are created to solve a specific problem. Singleton solve the problem of creating only one object of one class. Singleton design pattern is one of the most popular design patterns, it restricts any class to have only one object. And that object is used where ever required. There are certain…

Java Proxy Design Pattern Example

This article describes the proxy design pattern in java.

Цукерберг рекомендует:  MATLAB инструмент будущего или дорогая игрушка

Java Observer Design Pattern Example

The Observer pattern is a software design pattern in which an object, called the subject, maintains a list of all the other objects that depend on it (the subject). These dependents are called observers. They are automatically notified if the state of the subject (the maintainer of all dependents(observers)) changes. It is usually accomplished by…

Java Factory Design Pattern

This article talks about the factory design pattern in Java which is one of the popular design patterns used in Java.

Java Builder design pattern

Here we will talk about the Java Builder design pattern, where and how it should be used.

Java Comparator Example

in this tutorial, we will discuss java comparator and its examples. What is Java Comparator? Java Comparator is an interface for arranging Java objects. Summoned by “java.util.comparator,” Java Comparator analyzes two Java protests in a “compare(Object 01, Object 02)” group. Utilizing configurable strategies, Java Comparator can contrast objects with profit a number based for a…

Java Send Email Example

The JavaMail API “pp”-independent(platform and protocol) framework which purpose is to help build messaging and mail applications. It is

Java volatile Example

In this tutorial, we will discuss the Java volatile Example. What is Java volatile? The Java volatile keyword is utilized to check a Java variable as “being put away in fundamental memory”. All the more decisively that implies, that each read of an unpredictable variable will be perused from the PC’s primary memory, and not…

Introduction to Docker and Docker containers in Java

In short, Docker is a tool that allows you to build, deploy and run applications easily by the usage of so-called containers. These containers let us package all the essentials such as libraries and dependencies. In addition, the containers run on the host operation system. There are many benefits that come when we use Docker. It…

Installing and configuring MySQL database and server for Spring usage

In the end of this tutorial, you will have installed the right MySQL products needed to develop applications in Spring. You will need two essential things: MySQL Database and MySQL Server. Follow the steps below. Configuring the MySQL Database Visit https://www.mysql.com/downloads/ and then select Community downloads, like so: On the next page, you will see…

How to use the MySQL connector in Java

Before testing the MySQL connection from a Java program, we’ll need to add the MySQL JDBC library to the classpath. We will need to download the mysql-connector-java-*.jar file from the downloads page: Now, depending upon your work environment (e.g. Eclipse or Command line) you will have to do either one: If working with Eclipse IDE,…

How to debug java with eclipse

Debugging – the technique one uses most and is inevitable. If only there was a tool that allowed us to make this sometimes-tedious task much easier and not-so-tedious… oh wait. There is. Eclipse allows to start a Java programin in the so-called Debug mode. What it is most useful for is that it allows you…

Быстрый старт в Java: от установки необходимого софта до первой программы

Как вы знаете, Java — один из самых популярных языков программирования в мире и его знание существенно увеличит вашу значимость как программиста. Итак, вы решили начать писать на этом языке. Вам понадобится поставить JDK для того, чтобы писать и запускать программы на Java. JDK — набор софта, разработанного Oracle, содержащий в себе компилятор (javac), среду выполнения (Java Runtime Environment), стандартную библиотеку языка, примеры и документацию. Прочитав эту статью, вы узнаете, как установить и настроить JDK на своей системе, что такое среда разработки и какие варианты IDE существуют для Java. Также вы напишете свою первую программу на Java.

Установка Java Development Kit

  1. Перейдите на сайт Oracle и загрузите JDK для вашей платформы.
  2. После загрузки извлеките полученный архив и запустите извлеченное приложение.
  3. В процессе установке выберите вариант «Development Tool» и нажмите «Next».
  4. Спустя некоторое время установка завершится.

Итак, вы установили Java Development Kit, но это еще не всё. Необходимо настроить его для вашей системы.

Настройка JDK на примере Windows

  1. Перейдите в папку %ProgramFiles%\Java\%версия установленного вами jdk%\bin , нажмите на свойства любого файла в этой папке и скопируйте путь к нему.
  2. Перейдите в свойства вашего компьютера, откройте вкладку «Дополнительно», нажмите «Переменные среды…». В открывшемся окне создайте новую переменную, назовите её Path , в её значение вставьте скопированный ранее путь.

  3. Теперь самое важное. Откройте командную строку и наберите javac , чтобы убедиться, что JRE установлен и настроен. Если выдаётся список аргументов к команде javac , то поздравляю, вы успешно установили и настроили всё, что необходимо для использования Java!

После установки JDK и JRE не помешает установить на компьютер одну из IDE.

Установка IDE

Для начала разберёмся, что такое IDE.

IDE (Integrated Development Environment) – это комплекс программных средств, используемый программистами для разработки программного обеспечения. IDE позволяет с лёгкостью писать, запускать, отлаживать и тестировать код.

Для написания сложных программ целесообразно использовать IDE. Мы рассмотрим наиболее популярные.

Блокнот

Да, и в блокноте можно писать код! Для разработки вам потребуется всего лишь установить JDK и указать путь к ней. Пишете код в блокноте, компилируете с помощью командной строки. Тем не менее, для разработки сложных программ это не самый лучший вариант из-за отсутствия каких-либо дополнительных возможностей, присутствующих в продвинутых IDE.

NetBeans

NetBeans — выбор профессиональных Java-разработчиков. В ней есть уникальные возможности и инструменты, которые позволят вам сделать вашу программу кроссплатформенной, а код удобочитаемым. NetBeans поддерживает не только Java, но и другие языки программирования для десктоп- и веб-разработки. Она полностью бесплатна, скачать её можно с официального сайта. Вот лишь некоторые её возможности:

  • форматирование кода;
  • установка сторонних библиотек;
  • простой графический интерфейс;
  • и многое, многое другое…

Eclipse

Eclipse, как и Netbeans — одна из наиболее популярных IDE. Она предоставляет впечатляющий интуитивно понятный интерфейс и производительную среду разработки, позволяющую комфортно разрабатывать приложения на Java. Скачать Eclipse можно бесплатно с официального сайта. Преимущества:

  • возможность форматировать код так, как вам удобно;
  • поддержка разбиения кода на модули;
  • лёгкость использования одного и того же кода в разных проектах;
  • перетаскивание (drag-and-drop);
  • просмотр содержимого библиотек;
  • удобный интерфейс.

IntelliJ IDEA

IntelliJ IDEA — известная IDE для Java, написанная, как ни странно, на Java. Укомплектована уникальными инструментами и позволяет без проблем ориентироваться в программе. Нахождение ошибок и отладка кода никогда не были такими легкими, как с IntelliJ IDEA.

JCreator

JCreator — продвинутая и самая быстрая IDE для Java, написанная на C++.

Пишем свою первую программу

Итак, вы установили и настроили JDK, JRE и IDE для Java. Каков следующий шаг? Конечно же, написать программу, чтобы окончательно убедиться, что всё работает и вы готовы к изучению языка. Вы познакомитесь с базовой структурой кода на Java и создадите свою первую программу! Стоит отметить, что перед изучением Java следует ознакомиться хотя бы с самыми простыми принципами объектно-ориентированного программирования.

Структуру программы на Java можно представить так:

Структура программы на Java

В файле с исходным кодом содержится несколько классов — это части программы, имеющие определённые функции. Хорошей практикой считается разбиение программы на несколько файлов с исходным кодом, каждый со своим назначением. В классах содержатся методы — действия, которые могут выполнять объекты данного класса. В методе содержатся команды, с помощью которых вы можете получить желаемый результат.

15–16 ноября, Минск, 133–390 br

Перед тем, как приступить к созданию программы, необходимо создать проект, а в нём и файл, в котором будет содержаться ваш код. Рассмотрим создание проекта на IDE Eclipse, но в остальных IDE процесс отличается не сильно. Cверху выберите «File», затем наведите курсор на «New», в открывшемся меню выберите «Java Project». В появившемся окне введите имя проекта и другие нужные вам настройки (если не уверены, что делать, то можно просто оставить все как есть) и нажмите «Next». Готово, вы создали проект! Осталось лишь создать в нём класс, в котором вы напишете свою первую программу. Щёлкните правой кнопкой мыши по вашему проекту (он должен появиться справа) и выберите «New» → «Class». Присвойте новому классу имя (в данном примере – это first ) и нажмите «Finish».

Приступим к написанию вашей первой программы. По традиции — это программа, выводящая на экран «Hello, world!».

Разберём по частям написанное нами:

  • public – это модификатор доступа, определяющий, из какой части программы может использоваться наш класс. В вашем примере public — это весь код;
  • class – ключевое слово, показывающее, что вы объявляете класс, а не что-либо иное;
  • first – имя вашего класса. Круглые скобки определяют начало и конец кода класса;
  • public static void main(String args[]) – объявление публичного статического метода (то есть который можно вызвать, не создавая объект класса). Метод в примере ничего не возвращает и принимает в качестве аргументов массив строк. Единственная команда в этом методе выводит в консоль сообщение «Hello, world!». Заметьте, вместо println можно написать print , разница лишь в том, что в случае с println дополнительно выведется символ переноса строки.

Хорошо, вы написали вашу первую программу. Теперь её надо запустить. Для этого просто нажмите белую стрелочку в зеленом кружке на верхней панели (при наведении курсора на неё должно высветиться «Run»). После нажатия внизу откроется консоль, в которой вы увидите сообщение “Hello, world”! Поздравляю, вы написали вашу первую программу на Java и готовы погрузиться в увлекательный мир этого языка!

Полезные ссылки для дальнейшего изучения

Вот несколько ресурсов, которые помогут вам в изучении Java:

  • документация Oracle по стандартной библиотеке языка;
  • уроки по Java от Oracle;
  • теория объектно-ориентированного программирования;
  • хорошая книга-самоучитель;
  • большое количество интересных и полезных статей про Java на русском языке.

Java — java coredump

Краткое описание:
Поддержка программ, написанных на языке Java базового уровня. (напр. для запуска того же Minecraft или работа с APK)

Описание:
(с Вики + изменениями на «людской язык»)
Java Runtime Environment (сокр. JRE) — минимальная реализация виртуальной машины, необходимая для исполнения Java-приложений, без компилятора и других средств разработки.

Можно описать много чело, есть огромное кол-во ссылок по поводу JRE, поэтому я не буду всё описывать — это можно найти прямо на самом сайте — https://www.java.com/ru/

  • Условные обозначения:
    (?) — не точно, возможно что не сработает, или возможно, ухудшит работу.
    Q: — вопрос.
    Z: — ответ.

Q: Программы не видят Java, что б я не делал.
Z: Java использует переменную среду Win для своего обнаружения (или ссылания на себя). Но почему-то установщик сам редко когда записывает в среду это значение, поэтому Java себя и не показывает.

Это также касается JDK и прочих!

Увы, я знаю только как на Windows это выглядит. С «Пингвином» и т.д. — хз как там. Можете написать в тему инструкцию, кину сюда ссылку на пост.

Пути практически идентичны в разных версиях Windows:

[b]Все элементы панели управления[b] -> Система -> Доп. параметры системы -> Дополнительно -> Переменные среды -> Системные переменные -> нажать на «PATH» -> -> Изменить. -> Создать -> прописать путь к версии Java.
Пример: У меня стоит 64-bit, поэтому я пишу C:\Program Files\Java\jre*\ (звёздочка — номер версии).
Для 32-bit: C:\Program Files (x86)\Java\jre*\.
P.S. Можно зайти в C:\Program Files\Java\ и вписать версии которые там есть.

Если не сработает, то пробуем после jre* дописать \bin\, т.е. C:\Program Files\Java\jre*\bin\.

— 512Мб: 512 Мб , естественно.
— 1Гб: 1024 Мб
— 2Гб: 2048 Мб
— 3Гб: 3072 Мб
— 4Гб: 4096 Мб
— 6Гб: 6144 Мб
— 8Гб: 8192 Мб
— 16Гб: 16384 Мб
— 32Гб: 32768 Мб
— И т.д.

Можно открыть калькулятор и посчитать в ручную, если нужно собственное значение. Пример: Нужно 5Гб? 4096 + 1024 = 5120. Живой пример.

При обнаружении проблем и ответов на них — писать в тему, добавлю сюда ссылку на автора текста.

Русский интерфейс: Нет

  • Beta v8u202
    • Windows:
      • Web, 32-bit:ТЫЧКА
      • Автономно, 32-bit:ТЫЧКА
        • Распакованный:ТЫЧКА
      • Автономно, 64-bit:ТЫЧКА
        • Распакованный:ТЫЧКА

    • Linux:
      • 32-bit:ТЫЧКА
        • Распакованный:ТЫЧКА
      • 64-bit:ТЫЧКА
        • Распакованный:ТЫЧКА

    • Mac OS X:
      • Автономно, 64-bit:ТЫЧКА
        • Распакованный:ТЫЧКА

    • Solaris:
      • Распакованный, 64-bit:ТЫЧКА

    • Solaris SPARC:
      • Распакованный, 64-bit:ТЫЧКА

В теме нет куратора. Если нужно что-то изменить в шапке, добавить какую-то обнову, и т.д. — мне в QMS и кинуть ссылку на пост, на который нужно указать ссылку. Возможно личное наименовывание ссылки.
Если я не буду отвечать промежуточное время (пару дней, а не один или полтора дня), то обращайтесь к модераторам раздела через кнопку под постами, на которые необходимо добавить ссылки. Я потом отредактирую шапку по порядку.

Сообщение отредактировал ctich — 20.03.19, 19:48

Всем привет, уважаемые форумчане.

Прошу у вас помощи, так как исчерпал возможности самостоятельно решить проблему с ява.

Детали- На Netbeans написал пример приложения на Ява, скомпилировал. Пробую запустить в консоли- вылазит сообщение

«A JNI error has occurred, please check your installation and try again
Exception in thread «main» java.lang.UnsupportedClassVersionError: verysimplechatserver/VerySimpleChatServer has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 52.0″

Тоесть моя версия JNI на компе ниже чем нужно.

Ява обновил с официального сайта- не помогло.
Установил отдельно JDK с оф сайта- не помогло.

Возможно нужно в Netbeans указать целевую версию ява для компиляции- но как это сделать.

Сорь, правка- моя версия JRE ниже чем 54.

установка последней версии JRE с сйта Oracle ничего не поменяла.

Тэк, отчёт по проблеме-

Удалил вообще все версии Ява с компа, Поставил JDK 10 с сайта Oracle, в комплекте установилось и JRE.
На компе в переменных средах прописал переменную Path- путь к папке bin в JDK, на всякий случай прописал переменную JAVA_HOME — путь к JDK, в Netbeans
— в tools-options- вкладка Java, там во вкладке Ant переменная Classpath- указан путь к JDK, во вкладке Java Shell выбран JDK 10, во вкладке Nashorn так же выбран JDK 10.
Компилируется, запускается с командной строки, всё норм.

Добавлено 09.04.2020, 12:19:

Мле, чуть не забыл- в Netbeance в выпадающем меню Run есть строка SetProjectConfiguration, далее Customize, и там в пункте Source выбираем JDK 10, и Profile- full JRE.
Фух.

А можно где скачать oracle java 8 jdk .А то скачал oracle 8 jre c cайта oracle и в Intellij idea c ней не запускається компилирование програмы.Требует jdk а на сайте oracle для скачывання требует логинится.Только удалось скачать java 12.0.1 jdk последнюю.

Сообщение отредактировал s1a1g1e1r1t — 29.04.19, 21:50

Установка примеров программ

27.10.2015, 17:04

Море примеров кода!
The Java Developers Almanac 1.4: http://javaalmanac.com/egs/index.html

Сборник примеров по JAVA
Здравствуйте. Где можно скачать Сборник задач и примеров по програмированию на JAVA.

Нужны исходники программ-примеров из книги
Привет всвем. Если кто-то, когда-то работал с книгой «Станислав Горнаков. DirectX 9. Уроки.

Какие открыть файлы для запуска примеров программ?
скачал MASM 32 7.0 от суда http://www.allasm.ru/soft.php редактор запускается вроде в.

Разобраться с классом семафор, скинуть несколько примеров не сложных программ
Здравствуйте не могли бы вы помочь мне разобраться с классом семафор, скинуть несколько примеров не.

27.10.2015, 17:59 [ТС] 2

И подскажите правильно ли я прописал пути если в командной строке после ввода java -version отображается как на скриншоте

Добавлено через 35 минут
Пишут что должно появится javac и версия а у меня появляется то что на скриншоте

Добавлено через 17 минут
А как установить примеры программ? Вы можете найти их по адресу horstmann.com/corejava хранятся они в corejava.zip но я не могу их найти что то. Подскажите где их скачать

27.10.2015, 18:00 3 27.10.2015, 18:22 [ТС] 4

Скажите пожалуйста,мне нужно создать папку в каталоге JDK с названием CoreJavaBook и поместить все скачанные папки corejava.zip в эту папку?

Добавлено через 15 минут
Использование инструментов командной строки.
1.Откройте окно командной оболочки
2.Перейдите к каталогу CoreJavaBook/v1ch02/Welcome
3.Введите
javac Welcome.java
java Welcome

Я ввожу но пишет ошибку. У меня файлы находятся по этому пути C:\Program Files\Java\jdk1.8.0_65\CoreJavaBook\v1ch02\Welcome Как правильно ввести команду в командной строке?

27.10.2015, 18:22
27.10.2015, 18:47 5
27.10.2015, 20:30 [ТС] 6
27.10.2015, 21:27 7
28.10.2015, 10:01 8
28.10.2015, 10:26 [ТС] 9
28.10.2015, 20:56 [ТС] 10

Вот смотрите. По книге 9-е издание Java-Основы.
Установка примеров программ.
Вы можете найти их на hortsmann.com/corejava . Скачал. Создал папку с названием CoreJavaBook в папке JDK и поместил в нее все скачанные файлы.
Теперь использование инструментов командной строки.
1.Откройте консоль
2.Перейдите к каталогу CoreJavaBook/v1ch02/Welcome.
3.Введите следующие команды:
javac Welcome.java
java Welcome

Когда это ввожу то получаю (скрин 1)
Ввожу cd /d C:\Program Files\Java\jdk1.8.0_65\CoreJavaBook\v1ch02\Welcome как писал Alradalion то получаю (скрин 2)

Подскажите пожалуйста как правильно, я совсем запутался уже что к чему.
Правильно ли вообще у меня установлена java ? (скрин 3)

Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих