Чашечка Java
الذهاب إلى القناة على Telegram
Лучшие материалы по Java на русском и английском Разместить рекламу: @tproger_sales_bot Правила общения: https://tprg.ru/rules Другие каналы: @tproger_channels
إظهار المزيد8 281
المشتركون
-124 ساعات
-37 أيام
-7130 أيام
أرشيف المشاركات
8 280
Как красиво избавиться от switch-case посредством перечисления
Привет, хабр! Применение switch-case в коде - давняя тема холиваров на форумах на предмет чистоты кода. Лично я склоняюсь к простому мнению: инструмент необходимо использовать по назначению.
Сегодня хотелось бы рассмотреть несколько простых кейсов, где switch-case является не лучшим выбором и предложить красивое и удобное решение проблемы.
Читать: https://habr.com/ru/post/680940/?utm_campaign=680940
8 280
10 Examples of ps command in Linux
In Today's article, You will be learning about the "ps" command in Linux and our objectives are:
To know what Ps stands for, how it works with numerous options, and provide different examples and the usage of it.
PS stands for processes status. Basically used to list the processes that are running at the moment. As we all know that when a task needs to be implemented it must follow or have a process. There are different options you could use with it and this gives you a different result.
Java Interview questions and tutorials
Read: http://www.java67.com/2022/08/10-examples-of-ps-command-in-linux.html
8 280
How to fix "variable might not have been initialized" error in Java? Example
This error occurs when you are trying to use a local variable without initializing it. You won't get this error if you use an uninitialized class or instance variable because they are initialized with their default value like Reference types are initialized with null and integer types are initialized with zero, but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessingor using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.
Java Interview questions and tutorials
Read: http://www.java67.com/2016/07/how-to-fix-variable-might-not-have-been-initialized-error-in-java.html
8 280
[Solved] Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg'
Hello guys, if you are getting "Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg'" error or just Error: could not open 'jvm.cfg and wondering what to do and how to solve this error then you have come to the right place. I will show you how I solved this error and how you can use my tips to solve your error as well. A couple of weeks back I updated my laptop to Windows 10 but after trying for one day, I reverted back to Windows 8.1. Everything was alright until I open Eclipse, which was throwing "Error: could not open 'C:\Program Files\Java\jre8\lib\amd64\jvm.cfg', as soon as I launch it. It was quite bizarre because everything was fine earlier.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/10/error-could-not-open-java-jmv-cfg-lib-eclipse.html
8 280
Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java [Solution]
Problem:You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Loggererror in your Java application, which is using Log4j Logger either directly or indirectly via some popular Java framework like Spring, Struts or Hibernate.
Cause : Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error indicates that JVM is not able to found org.apache.log4j.Logger class in your application's CLASSPATH. The simplest reason for this error is the missing log4j.jarfile. Since org.apache.log4j.Logger class belongs to this JAR file, if it's not available at run-time then your program will fail.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/08/caused-by-javalangnoclassdeffounderror-org-apache-log4j-Logger.html
8 280
How to Avoid/Fix ConcurrentModificationException while looping over ArrayList in Java [Example]
Apart from the NullPointerException and ClassNotFoundException, ConcurrentModificationExceptionis another nightmare for Java developers. What makes this error tricky is the word concurrent, which always mislead Java programmers that this exception is coming because multiple threads are trying to modify the collection at the same time. Then begins the hunting and debugging, they spent countless hours to find the code which has the probability of concurrent modification. While in reality, ConcurrentModficationException can also come in a single-threaded environment.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/10/how-to-solve-concurrentmodificationexception-in-java-arraylist.html
8 280
[Solved] Exception in thread "main" java.lang.IllegalStateException during Iterator.remove() in Java
Hello guys, if you are wondering how to deal with java.lang.IllegalStateException while trying to remove elements from ArrayList in Java then you have come to the right place. In this article, I am going to share how I solved this problem and how you can do the same. I was writing a sample program to demonstrate how to remove elements from the list while iterating over it by using the Iterator.remove() method. Unfortunately, I was getting the following error, right at the place where I was calling the Iterator.remove() method :
Java Interview questions and tutorials
Read: http://www.java67.com/2016/01/exception-in-thread-main-java.lang.IllegalStateException-Iterator-remove.html
8 280
How to Fix java.lang.NoClassDefFoundError: org/dom4j/DocumentException [Solution]
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException comes when your program is using the DOM4j library but necessary JAR is not present. This error can also come when you are indirectly using the DOM4j library like when you use the Apache POI library to read the XLSX file in Java, this library needs dom4j.jar in your classpath. Not just this one but there are several other libraries that use this JAR internally, if you are using any of them but don't have this JAR then your program will compile fine but fail at runtime because JVM will try to load this class but will not be able to find it on the classpath.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/06/org.dom4j.DocumentException-javalangnoclassdeffounderror.html
8 280
java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [Solved]
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject error means that your Java program needed a class called org.apache.xmlbeans.XmlObject but JVM is not able to find that in your application's CLASSPATH. You can see the actual cause of this error is "java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject". The most probable reason for this error could be a missing JAR file. In order to solve this error, you need to first find out which JAR file this class belongs. If you look at the error message it's clearly saying that it's from xmlbeans package, it means this class belongs to XMLBeans library.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/06/OrgApachexmlbeansXmlObjectNoClassDefFoundErrorClassNotFoundException.html
8 280
Быстро сжимаем, быстро пишем и читаем! На Java
В ходе разработки IDE 1С:Enterprise Development Tools у нас возникла необходимость быстро оперировать с довольно большими (несколько гигабайтов) объемами данных. Если не вдаваться в детали: при интерактивной работе пользователя с IDE при переключении с одной ветки репозитория на другую нам нужно сохранить текущее состояние проекта и загрузить состояние проекта из новой ветки. Детали (и объяснение – почему счет идет на гигабайты) — в конце статьи, непосредственно к Java это отношения не имеет, кому интересно – прочтет. Ну а что касается Java, то задача выглядит так: быстро сохранить несколько гигабайт информации на диск и быстро считать несколько гигабайт информации с диска. Как мы решали эту задачу, с какими трудностями столкнулись и как их преодолели – под хабракатом.
Читать: https://habr.com/ru/post/680838/?utm_campaign=680838
8 280
'javac' is not recognized as an internal or external command [Solution]
'javac' is not recognized as an internal or external command, operable program, or batch fileerror comes when you try to compile a Java source file using the javac command like javac Helloworld.java but your PATH is not set properly. It means that the javac.exe executable file, which exists in the bin directory of the JDK installation folder is not added to the PATH environment variable. You need to add the JAVA_HOME/binfolder in your machine's PATH to solve this error. You cannot compile and run a Java program until your add Java into your system's PATH variable.
Java Interview questions and tutorials
Read: http://www.java67.com/2015/07/javac-is-not-recognized-as-internal-or-external-command-program-batch-file.html
8 280
How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory
Java allows an application to access non-heap memory by using a direct byte buffer. Many high-performance applications use a direct byte buffer, along with a memory-mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of the Garbage collection scope. This means the garbage collectors can not reclaim this memory. It is often used to store large data like order or static data cache. Since generally, your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running the following code
Java Interview questions and tutorials
Read: http://www.java67.com/2014/01/how-to-fix-javalangoufofmemoryerror-direct-byte-buffer-java.html
8 280
java.lang.OutOfMemoryError: Java heap space : Cause and Solution
So you are getting java.lang.OutOfMemoryError: Java heap space and run out of ideas on what to do, especially if you are a user of any Java application and not the programmer or developer, this could be a tricky situation to be in. I receive lots of emails from Minecraft user ( a popular Java game), along with junior developers who are using Tomcat, Jetty, Untow, JBoss, WebSphere, Android user, who uses Android apps and several other Swing-based Java desktop application user complaining about java.lang.OutOfMemoryError: Java heap space in their Mobile or Laptop.
Java Interview questions and tutorials
Read: http://www.java67.com/2013/08/guide-of-javalangoutofmemoryerror-java-heap-space-tomcat-eclipse-minecraft-jboss.html
8 280
Исследуем граф «мир тесен» при помощи Neo4j
Когда моя сестра переехала в другой город и познакомилась с соседями, оказалось, что дедушка и бабушка ее соседа и наши бабушка с дедушкой были хорошими друзьями и общались, живя рядом в другом городе – два поколения назад. Интересно, когда обнаруживаются такие неожиданные связи. Согласно теории сетей, пути, соединяющие узлы сети, зачастую короче, чем могло бы показаться.
Если каждый в сети знает k других людей, то можно упрощенно предположить, что, начав от этого человека и совершив n переходов от узла к узлу, мы найдем kⁿ человек. Учитывая экспоненциальный рост, потребуется совсем немного времени, чтобы построить путь от любого конкретного человека до любого другого в графе.
Но в реальных социальных сетях многие люди, знакомые конкретному человеку, также знают друг друга. Такое пересечение между друзьями друзей снижает количество новых людей, к которым я могу обратиться после каждого перехода на пути от стартового узла. Может быть непросто найти такие пути, которые начинаются в сплоченном сообществе, а далее разветвляются до самых отдаленных уголков сети.
В главе 20 книги Networks Crowds and Markets ее авторы Дэвид Изли и Джон Клейнберг дают теоретический аппарат, описывающий, как в реальном мире могут возникать феномены, укладывающиеся в граф «мир тесен». В этой теории сочетается идея гомофилии, согласно которой схожие люди кучкуются вместе, и идея слабых связей, где отношения ветвятся в масштабах всей сети. Объяснение основано на работе Дункана Уоттса и Стива Строгаца. Давайте проследим эти примеры при помощи кода, написанного при помощи Neo4j.
Читать: https://habr.com/ru/post/680576/?utm_campaign=680576
8 280
Top 30 Gradle Interview Questions with Answers for beginners and experienced
Hello guys, if you are preparing for Java or Kotlin developer interview where Gradle skills are needed then you should prepare for Gradle related questions. I have seen many interviewer asking Maven and Gradle related questions during interviews and many Java developer don't prepare them. But, considering you are looking for Gradle questions I think you are one step ahead of them and If you are looking for Gradle interview questions then you have come to the right place. Earlier, I have shared Maven Interview Questions and in this article, I am going to share Gradle interview questions for Java and Kotlin developers.
Java Interview questions and tutorials
Read: http://www.java67.com/2022/08/gradle-interview-questions-with-answers.html
8 280
[Solved] How to Fix StringIndexOutOfBoundsException 1 and ArrayIndexOutOfBoundsException in Java?
Though both StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException are children of IndexOfBoundsExceptionclass, the former is thrown by methods of String and related class like StringBuffer and StringBuilder to indicate that an index is either negative or greater than the size of the String, or more generally not valid. For example, charAt() method throws StringIndexOutOfBoundsException when an index is equal to the length of String? why? because String is backed by character array where index starts at 0and ends at length -1.
Java Interview questions and tutorials
Read: http://www.java67.com/2016/04/difference-between-stringindexoutofboundsException-vs-ArrayIndexOutOfBoundsException-Java.html
8 280
How to fix "class, interface, or enum expected" error in Java? Example
If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single missing curly bracecan blow your program and throw 100s of "illegal start of expression" errors during compilation of Java Programmer. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allows you to write Java programs. I didn't know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It's our lab computer where everything is supposed to work as much as our instructor wants.
Java Interview questions and tutorials
Read: http://www.java67.com/2016/08/how-to-fix-class-interface-or-enum-expected-error-java.html
8 280
How to fix "illegal start of expression" error in Java? Example
The "illegal start of expression"error is a compile-time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compile your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws an "illegal start of expression"error. The most common reason for this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won't get an error that there is a missing semi-colon at the end of the statement because the compiler doesn't know the end.
Java Interview questions and tutorials
Read: http://www.java67.com/2016/08/how-to-fix-illegal-start-of-expression-error-in-java.html
8 280
How to deal with Unsupported major.minor version 55.0, 57,0, 60.0, 61.0 in Java + Eclipse + Linux [Solution]
The "unsupported major.minor version 55.0"error started to come after Java SE 11 release and the root cause of this error is trying to run a Java application compiled with JDK 11 into a JRE lower than Java SE 11 like JRE 9 or JRE 8. This is very common because a developer has updated their compiler or IDE to Java SE 11 but many times their runtime is not upgraded to Java 11. If you remember, in Java you can run a class file compiled with a lower version say Java 8 to a higher version say JRE 11 because Java is backward compatible but vice-versa is not allowed. I mean, you cannot run a JAR file or class file created by Java 11 version into Java 8 or Java 9 version. Similarly, you cannot run a Java SE 17 compiled class file in Java SE 11 or Java SE 13 runtime environment.
Java Interview questions and tutorials
Read: http://www.java67.com/2016/06/unsupported-majorminor-version-520-in-java-eclipse-linux.html
