Showing posts with label java certification. Show all posts
Showing posts with label java certification. Show all posts

Friday, July 5, 2024

Check if a Number Is Power of 2 in Java

Check if a Number Is Power of 2 in Java

In this article, we will explore different approaches to check if a given number is a power of 2 in Java. We will cover the following methods:

  • Loop Division
  • Using Bitwise & Operations
  • Counting Set Bits
  • Using Integer.highestOneBit()
  • Using Logarithm

1. Loop Division


This approach involves continuously dividing the number by 2 and checking if the remainder is ever not zero.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        while (n % 2 == 0) {
            n /= 2;
        }
        return n == 1;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero. If it is, we return false.
  • We repeatedly divide the number by 2 as long as it is even.
  • Finally, we check if the resulting number is 1.

2. Using Bitwise & Operations


This method utilizes the property that powers of 2 have exactly one bit set in their binary representation.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

◉ We check if the number is greater than zero.
◉ We use the bitwise AND operation to check if the number has only one bit set.

3. Counting Set Bits


This approach counts the number of set bits (1s) in the binary representation of the number.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n > 0) {
            count += (n & 1);
            n >>= 1;
        }
        return count == 1;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero.
  • We count the number of set bits by checking the least significant bit and right-shifting the number.
  • We return true if the count of set bits is 1.

4. Using Integer.highestOneBit()


This method uses the Integer.highestOneBit() function to check if the number is a power of 2.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        return n > 0 && Integer.highestOneBit(n) == n;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is greater than zero.
  • We use the Integer.highestOneBit() method to get the highest bit of the number.
  • We check if this highest one-bit is equal to the number itself.

5. Using Logarithm


This approach uses the mathematical property that if a number is a power of 2, its logarithm base 2 should be an integer.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        double log2 = Math.log(n) / Math.log(2);
        return log2 == Math.floor(log2);
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero.
  • We calculate the logarithm base 2 of the number.
  • We check if the result is an integer.

6. Summary


Method Advantages  Disadvantages 
Loop Division
  • Simple to understand and implement.
  • Directly checks divisibility by 2.
  • Less efficient for large numbers due to multiple divisions.
Using Bitwise & Operations 
  • Very efficient with constant time complexity O(1).
  • Utilizes fast bitwise operations. 
  • Requires understanding of bitwise operations. 
Counting Set Bits 
  • Conceptually simple and easy to understand. 
  • Less efficient due to the need to count all set bits.
  • Time complexity is O(log n). 
Using Integer.highestOneBit() 
  • Efficient and uses a single built-in method.
  • Constant time complexity O(1). 
  • 5Depends on an understanding of the Integer.highestOneBit() method. 
Using Logarithm
  • 3Uses mathematical properties and is easy to understand. 
  • Less efficient due to the use of floating-point operations.
  • Potential issues with floating-point precision. 

Source: javacodegeeks.com

Wednesday, April 17, 2024

How to Effectively Use Java Certification Practice Exams to Boost Your Score

Enhance your Java certification score with expert tips for effective practice exams. Maximize your preparation and boost your success!

Preparing for a Java certification exam can be daunting. Whether you are aiming for certifications like 1Z0-808, 1Z0-809, 1Z0-811, or more advanced ones such as 1Z0-819, 1Z0-900 and 1Z0-829, practice exams serve as an essential tool in your preparation arsenal. These simulated tests not only familiarize you with the format and style of the questions you'll face but also help pinpoint areas where your understanding may be lacking.

Using practice exams effectively can significantly enhance your chances of achieving a passing score and mastering the professional-level curriculum path for Java certification.

Benefits of Java Certification Practice Exams

Using Java certification practice exams can significantly elevate your preparedness for the actual test day. This preparation not only enhances your understanding of Java but also gives you a hands-on approach to tackling exam-style questions. Here, we will delve into several benefits these practice exams offer to candidates aiming to achieve certification.

Familiarizing Yourself with Exam Format

One of the primary advantages of engaging with Java certification practice exams is they familiarize you with the testing format.

Java certification exams, such as 1Z0-809 or 1Z0-819, have specific structures, often consisting of multiple-choice questions.

By taking practice exams, you get accustomed to the timing, the types of questions, and the overall pacing of the exam. This practice helps minimize any surprises on the actual exam day, allowing you to manage your time efficiently and increase your performance confidence.

Familiarity with the exam format translates directly into reduced exam anxiety and a more strategic approach to answering questions.

Identifying Weak Areas for Improvement

Practice exams serve as a diagnostic tool to highlight your strengths and weaknesses. As you encounter various questions, particularly those you find challenging or get wrong, you begin to see patterns in your knowledge gaps.

Whether it's concepts in Java Standard Edition such as lambdas and streams in the 1Z0-829 exam or debugging and exception handling scenarios in the 1Z0-808 specification, identifying these weak areas provides a focused framework for your study plan.

You can then allocate more time to revise and practice these specific topics, which maximizes the efficiency of your study sessions. This targeted preparation ensures that you bolster your understanding in weaker areas, making you more adept across all areas of the Java platform.

Types of Java Certification Practice Exams

Java certification candidates have access to a variety of practice tests, each designed to cater to different aspects of the learning process. These resources mimic the content and structure of the actual certification exams and can be a pivotal part of your preparation.

Understanding the types of practice exams available can help you choose the right tools to boost your readiness.

Mock Exams

Mock exams are comprehensive practice tests that closely simulate the real certification exam environment. They are designed to be as similar as possible to the actual exam, both in format and difficulty level. Taking mock exams offers several benefits:

  • Real Exam Feel: By replicating the pressure and timing of the real exam, mock exams give you a taste of what to expect, helping to ease nerves on exam day.
  • Performance Tracking: Many platforms offering mock exams provide detailed performance tracking. This feedback is crucial as it shows your progress and highlights areas that still need improvement.
  • Conditioning: Regularly scheduled mock exams can condition your mind and body, getting you used to the exam’s duration and mental stamina required.

A notable strategy is to start taking these mock exams early in your study plan and periodically retake them to track your improvement and adjust your study tactics accordingly.

Exam Simulators

Exam simulators are interactive tools that create a dynamic testing experience. These platforms not only feature a set of questions but also mimic the exam’s technology-based environment. Here's how they can be beneficial:

  • Interactive Experience: Simulators often use technology that mirrors the actual exam’s interface, which can be invaluable for becoming comfortable with the navigation and tools you will use on the real exam day.
  • Adaptability: Some simulators adjust the difficulty of the questions based on your answers, providing a customized difficulty level that can challenge your knowledge more effectively.
  • Immediate Feedback: Unlike some mock exams, simulators usually provide immediate feedback for each question, helping to reinforce learning or correct misunderstandings on the spot.

Utilizing exam simulators can dramatically increase your familiarity with the exam’s digital environment, which is crucial for those who may not be as comfortable with computer-based tests.

Strategies to Maximize Your Score with Java Certification Practice Exams Practice Exams

Utilizing practice exams for Java certification can significantly enhance your preparedness and boost your confidence. Following strategic approaches to leveraging these resources can greatly improve your chances of achieving a high score.

Java Certification Practice Exams: Time Management Techniques

Effective time management is crucial during both your preparation and the actual exam. Here’s how you can optimize your time management skills through practice exams:

  • Simulate Real Exam Conditions: Always time yourself as if you are in the actual exam. This helps you get used to the pressure of completing within the allotted time.
  • Sectional Timing Practice: Divide the practice exam into sections and allocate specific times to each. This strategy will help you to not spend too much time on one section at the expense of another.
  • Analyze Time Spent on Each Question: Post-exam, review how much time you spent on different types of questions. Identify the questions that took the longest time and focus on improving your speed and efficiency in those areas.
  • Speed and Accuracy Balance: Work on striking a balance between speed and accuracy. Concentrating solely on speed can lead to mistakes, whereas focusing only on accuracy might cause you to run out of time.

Reviewing and Understanding Correct Answers

Merely taking practice exams is not enough. The real benefit comes from thoroughly reviewing and understanding every answer, particularly the incorrect ones. Here’s how to do this effectively:

  • Detailed Review Session: After completing each practice exam, go through each question carefully. For every wrong answer, understand why your chosen answer was incorrect and learn the correct reasoning.
  • Cross-Reference with Study Materials: For questions you found challenging, cross-reference the concepts with your study materials. This can help reinforce learning and clarify doubts.
  • Keep a Mistake Journal: Maintain a journal to record common mistakes or challenging topics. This helps in identifying patterns and areas needing more focus.
  • Discuss with Peers or Mentors: Sometimes discussing complex questions with peers or a mentor can offer new insights and simplifies complicated concepts.

Creating a Study Plan Incorporating Java Certification Practice Exams

A structured study plan integrating practice exams can systematically prepare you for the Java certification test. Here’s how to create one:

  • Set Specific Goals: Determine what score you are aiming for and set regular milestones to achieve it.
  • Regular Practice Exams: Schedule regular practice exams into your study routine. Start with wider intervals and increase the frequency as you get closer to the exam date.
  • Incorporate Different Resources: Utilize a variety of practice exams from different sources to cover a broader range of topics and question formats.
  • Allocate Time for Review: Ensure your study plan includes ample time for in-depth review of practice exam results. Adjust your study plan based on these reviews to focus on weaker areas.

Tips for Using Practice Exams Effectively

Using practice exams effectively can transform your preparation and significantly enhance your performance on the actual certification test. The key to utilizing these tools efficiently is to adopt smart strategies that simulate the real exam environment and provide actionable insights into your knowledge and preparation level.

Setting Realistic Goals

To make the most out of Java certification practice exams, start by setting realistic and specific goals for each practice session. This involves understanding what each exam covers and designing your goals to match these topics.

For example, if you are preparing for the 1Z0-809 Java SE 8 Programmer II exam, set goals around mastering specific objectives such as Lambda expressions and using java.util.stream to perform complex data processing.

Break down your study sessions into manageable segments, aiming to improve incrementally with each practice exam taken. For instance:

  • -In your first practice session, you might aim to understand the overall exam format and question styles.
  • -In subsequent sessions, narrow your focus to improve in areas where your previous scores were weak.

Furthermore, use your practice exam results to set quantitative goals, like aiming to improve your score by a certain percentage with each attempt, ensuring that your study efforts are yielding measurable improvements over time.

Balancing Practice Exams with Other Study Material

While practice exams are invaluable tools for exam preparation, they should not be your only study resource. Balancing practice tests with other study materials such as textbooks, video tutorials, and hands-on projects is vital. This balanced approach ensures that you have a robust understanding of Java and are not just learning to pass the test.

Incorporate these elements into your study plan:

  • Use textbooks or online resources to deepen your conceptual understanding of Java.
  • Watch video tutorials to visually reinforce complex concepts and procedures.
  • Engage with online forums or study groups to interact with fellow test-takers and share insights.
  • Work on real Java projects or exercises to apply what you've learned practically.

Such a comprehensive approach helps to solidify your knowledge and provides confidence that goes beyond the practice exams.

Utilizing Retake Opportunities Wisely

Most exam simulators and practice tests offer options to retake the exams multiple times. Use these opportunities wisely to maximize your learning. Initially, use the first few attempts to get familiar with the exam’s format and timing. This can help in adjusting your pace and strategy during the exam without the pressure of having to score well.

After you are comfortable with the format, focus on the following during your retakes:

  • Identify patterns in the questions and topics that are often emphasized.
  • Understand and analyze your mistakes deeply. Rather than just noting the correct answers, spend time understanding why your answers were wrong and how to think about such questions correctly.
  • Experiment with different time management strategies to find what best suits you during the exam condition.

Each retake should be viewed as a learning experience rather than just another attempt. This perspective shifts focus from merely answering questions to actively learning and adapting strategies that will help in the real certification exam.

Using practice exams effectively is crucial in a well-rounded preparation strategy. By setting realistic goals, balancing various forms of study materials, and utilizing retakes productively, you are setting the stage not just for passing but excelling at your Java Certification examination. Remember, the goal is both a deep understanding of Java and an excellent performance on the exam day.

Conclusion

In conclusion, effectively leveraging Java certification practice exams, such as those for 1Z0-829, 1Z0-819, and other similar certifications, is pivotal for not only enhancing your Java skills but also for ensuring you are thoroughly prepared on exam day. By following the structured approach of understanding the exam format, practicing consistently, using quality resources, and simulating real exam scenarios, you can significantly boost your chances of achieving a passing score. Remember, consistency and perseverance are your best tools on this journey. Good luck on your path to Java certification success!

Monday, September 11, 2023

Java Card 3.1: Security Services

Java Card Technology, Core Java, Oracle Java Certification, Java Prep, Java Preparation, Oracle Java Tutorial and Materials, Oracle Java Guides

A key goal of version 3.1 is to ensure the availability of security services on a large range of secure hardware, including smartcards, embedded chips, secure enclaves within microprocessor units (MPUs) and microcontroller units (MCUs), and removable SIMs. It was designed to support the growth of existing Java Card markets, such as payment, identity, and connectivity markets, while enabling new IoT use cases with dedicated features. This blog entry covers those features.

Security services in Java Card 3.1 include the Certificate API, the Key Derivation API, the Monotonic Counter API, and the System Time API. Let’s look at these in more detail.

Certificate API. Cryptographic certificates are critical for security and serve as a basis in a public key infrastructure (PKI) to establish trust between different entities. A notable example of a protocol using cryptographic certificates is the Transport Layer Security (TLS) protocol. Based on certificate chains, a client (such as an IoT gateway) and a server (for example, an IoT cloud service) can authenticate each other.

The javacardx.security.cert package is an efficient way to manage cryptographic certificates such as X.509 certificates for memory- and resource-constrained devices.

With Java Card’s Certificate API, it is possible to verify a certificate signature, select and check some of its fields and extensions, and access its public key—without needing to create a dedicated certificate object that is potentially useless in the future. You can also build a certificate object (for example, for root certificates) that will be reused later, while deciding on fields and extensions that need to be associated with this certificate object and storing only useful components of the certificate.

With these mechanisms, an application has an efficient way to verify a certificate chain, check sensitive certificate fields, and keep track of trusted public keys.

Key Derivation API. Pseudorandom functions (PRFs) and key derivation functions (KDFs) are widely used in cryptography to derive sensitive data such as a secret key. They make it possible to stretch a secret or to derive multiple keys from it.

A typical usage is the derivation of a password to store a derived value without needing to store the initial password value. Another common example is the derivation of the shared secret established by a key-agreement operation in Diffie-Hellman (DH) or Elliptic-Curve Diffie Hellman (ECDH) key exchange. Another example is the TLS handshake protocol, which uses a PRF applied to a shared secret in between a client and a server to generate the cryptographic block material used during a TLS session between the two peers.

Java Card 3.1 introduces the javacardx.security.derive package. Its class DerivationFunction permits the management of both PRF and KDF algorithms, and it is easily extensible. Currently, eight algorithms are proposed that enable support for the International Civil Aviation Organization (ICAO) or TLS protocols, among others.

In addition, the Key Derivation API guarantees both the security of the derivation keys and the derived keys by encapsulating them into trusted objects.

Monotonic Counter API. To prevent replay attacks, numerous security protocols use monotonic counters, which are counters whose value can only increase. Once the value of a monotonic counter has been used, the counter is incremented (typically by 1). Thus, if a counter value has been attached to a given protocol payload at a certain time, it is guaranteed that the same counter value cannot be reused and attached to the same protocol payload later. This allows a third party consuming the protocol payload to know whether it has already been used by checking the counter value.

Device attestation (also known as remote attestation) is an example of a payload that needs to be protected against replay attacks. A remote attestation is a signature of software measurements running on a given device, and the attestation is sent to a third party. The third party can check whether a device is running unaltered software and can make sure the attestation is current and not replayed from the past.

External secure storage is another example requiring a monotonic counter. DRM licenses or the number of PIN entry tries are typical sensitive data protected by a Java Card secure element. In some hardware architectures, like the ones with an integrated secure element, such sensitive data might be stored in the memory flash of the host device; that is, in storage external to the secure element hardware itself. Thus, untrusted and rogue applications from the device host might be able to save and restore later such sensitive data. In the case of a DRM license, this risk would mean that access to a content item is granted an unlimited number of times instead of the initial limited times granted originally. Hence, in addition to integrity and confidentiality, the secure element must guarantee an anti-replay protection to sensitive data stored in external secure storage.

The javacardx.security.util package and its MonotonicCounter class enable the creation and management of multiple monotonic counters of up to 64 bits each. The Monotonic Counter API guarantees the atomicity of the update of the counter value.

System Time API. Time stamping and time interval calculation are important security operations. Time stamps enable you to record or check the time at which an event occurred. Estimating a time interval allows you to limit the duration of a transaction, for instance.

Java Card 3.1 introduces the package javacardx.framework.time, which has two classes:

◉ SysTime serves to retrieve the uptime; that is, the time elapsed since system boot. It does not require an internal clock.
◉ TimeDuration represents a time duration with microsecond resolution. Several operations, such as comparisons and conversions as well as plus and minus operations, are supported.

Java Card’s System Time API can support a variety of use cases related to device security. For example, consider an IoT device managing a temperature sensor in the chemical industry. This monitoring system is critical and needs to react to unexpected temperature variations. With the new I/O mechanism introduced in Java Card 3.1 and the System Time API, an application has the ability to retrieve a temperature value securely and to assess the elapsed time since the beginning of the measurement. If the time is too short or too long compared with the average expected value, this is reported to the monitoring system, which will trigger corrective operations such as changing the sensor or checking for a corruption of the IoT device software.

Source: oracle.com

Wednesday, June 9, 2021

The Subs Bench

Core Java Tutorial and Material, Oracle Java Career, Oracle Java Preparation, Oracle Java Exam Prep

How do I subclass a list element declared in my interface?

In a current project, we’re looking at our strong types having both interfaces and concrete implementations. There’s a reason for this that’s NOT about making things mockable.

Read More: 1Z0-816: Oracle Java SE 11 Programmer II

What’s nice and obvious is that this is possible:

public interface Bar {

}

public interface Foo {

    Bar getBar();

}

public class BarImpl implements Bar {

}

public class FooImpl implements Foo {

    public BarImpl getBar() { ... }

}

Despite the fact that the FooImpl subclass returns a subclass of the interface’s declared getter everything compiles happily, because a subclass can be substituted for a base class and still meet the Liskov substitution principle.

However, there’s a problem if you try to do this:

public interface Foo {

   List<Bar> getBars();

}

public class FooImpl implements Foo {

   // compiler error...

   public List<BarImpl> getBars() { ... }

}

In the Java generic type system, List<BarImpl> is not a subclass of List<Bar>. The folks who designed this stuff are pretty clever, and there’s probably a very good technical reason why this is the case.

The question is – can it be solved?

public interface Foo<T extends Bar> {

    // we know this is "at least" a Bar

    List<T> getBars();

}

public class FooImpl implements Foo<BarImpl> {

    // compiles great

    public List<BarImpl> getBars() { ... }

}

For lots of List or Optional of things, this might seem a bit cumbersome, but it is how it’s done… apparently.

Source: javacodegeeks.com

Wednesday, December 23, 2020

Java – Get Time In MilliSeconds

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep

A quick guide to get the current date time in milliseconds using Date, Calendar and java 8 api classes.

1. Overview

In this tutorial, We’ll learn how to get the time in milliseconds in java. Time in milliseconds is the right way and format in storing into the database for date time columns. Because this is stored as Number type and which reduces the space than DateTime type in SQL.

Let us come to our topic today is getting the time milliseconds can be retrieved from Date, Calendar and java 8 api classes such Instant, ZonedDateTime classes.

2. Using java.util.Date

First, we’ll try with the simple way to get the time in milliseconds format is from Date class. Date class has a method getTime() which returns the milliseconds in long value for the given time or current time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Date;

/**

 * Example to get time in milli seconds in java using util Date api

 * 

 * @author JavaProgramTo.com

 *

 */

public class MilliSecondsFromDate {

    public static void main(String[] args) {

        // Getting the current date from Date class.

        Date currentDate = new Date();

        // Getting the time in milliseconds.

        long milliSeconds = currentDate.getTime();

        // printing the values

        System.out.println("Current date : "+currentDate);

        System.out.println("Current date time in milliseconds : "+milliSeconds);

        // Creating the future date

        Date futureDate = new Date(2025, 01, 01, 02, 30, 50);

        // Getting the future date

        milliSeconds = futureDate.getTime();

        // printing the future date time values

        System.out.println("Future date : "+futureDate);

        System.out.println("Future date time in milliseconds : "+milliSeconds);

    }

}

Output:

Current date : Sat Dec 12 21:48:25 IST 2020

Current date time in milliseconds : 1607789905027

Future date : Sun Feb 01 02:30:50 IST 3925

Future date time in milliseconds : 61696501250000

3. Using java.util.Calendar

Next, use the Calendar class to get the time in milli seconds. This class has a method getTimeInMillis() which returns the milliseconds for the time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Calendar;

import java.util.Locale;

/**

 * Example to get time in milli seconds in java using Calendar api

 * 

 * @author JavaProgramTo.com

 *

 */

public class MilliSecondsFromCalendar {

    public static void main(String[] args) {

        // Getting the current date from Calendar class.

        Calendar calendar = Calendar.getInstance();

        // Getting the time in milliseconds.

        long milliSeconds = calendar.getTimeInMillis();

        // printing the values

        System.out.println("Current calender time in milliseconds : "+milliSeconds);

        // Creating another calendar object for Canada locale

        Calendar canadaLocale = Calendar.getInstance(Locale.CANADA);

        // Getting the future date

        milliSeconds = canadaLocale.getTimeInMillis();

        // printing the future date time values

        System.out.println("Future date time in milliseconds : "+milliSeconds);

    }

}

Output:

Current calender time in milliseconds : 1607790439838
Future date time in milliseconds : 1607790439859

4. Using Java 8 API


Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep

There are multiple ways to get the date time in milliseconds in java 8 date time api using Instant and ZonedDateTime classes.

Use toEpochMilli() method to get the date time in milli seconds epoch format.

package com.javaprogramto.java8.dates.milliseconds;
 
import java.time.Instant;
import java.time.ZonedDateTime;
 
/**
 * Example to get time in milli seconds in java 8 Using ZonedDateTime and Instant.
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsInJava8 {
 
    public static void main(String[] args) {
         
        // Getting milli seconds from ZonedDateTime class.
         
        // Creating zoned date time
        ZonedDateTime dateTime = ZonedDateTime.now();
         
        // getting the instant from zoned date time
        Instant instant = dateTime.toInstant();
         
        // Converting Instant time to epoch format milli seconds
        long timeInMilliSeconds = instant.toEpochMilli();
         
        // print the output
        System.out.println("Milli seconds from ZonedDateTime : "+timeInMilliSeconds);
         
        // Getting the milli seconds from Instant class.
        // Creating Instant object
        Instant instantTime = Instant.now();
         
        // Getting millis epoch value
        timeInMilliSeconds = instantTime.toEpochMilli();
         
        // printing
        System.out.println("Milli seconds from Instant : "+timeInMilliSeconds);
    }
}

Output:

Milli seconds from ZonedDateTime : 1607790957290
Milli seconds from Instant : 1607790957291

Thursday, April 23, 2020

How to Create File and Directory in Java with Example

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

Many beginners confused with the fact that same class java.io.File is used to create both file and directory in Java. I agree, this is not very intuitive and  junior developers probably start looking for a class called java.io.Directory, which doesn't exists. On the other hand, creating file and directory are simple in Java, as java.io.File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These method returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully. There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command.

For checking, whether a file or directory exists or not, we will use java.io.File.exists() method, this method returns true, if file or directory is already there. To see complete behaviour in action, please run this program twice with same inputs. First time it will create directory and file, and second time, it will just say that they already exists.

Java Program to make File and Directory


This is the complete code of our sample Java program to create file and directory in Java. As I told same object java.io.File is used to represent both file and directory,  its important to name variable properly to distinguish between them e.g. using prefix "f" for file and "dir" for directory, or something similar.

After that we are checking if directory already exists or not by using exists() method from java.io.File class, extremely useful to prevent accidental overwrite of old data. If directory doesn't already exists then we call mkdir() method from File class to actually create a directory, thankfully name is similar to popular command mkdir, which is used to create directory in both Windows and Linux operating systems. This method returns a boolean value, which can be used to check if creation of directory is successful or not, you can either leverage this value for error handling or printing error message.

Once directory is ready, we are creating a File object by passing string path. This file object is further used to check if any file of same name already exists on same location or not. If not then only we create file, using createNewFile() of java.io.File class.

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

Similar to mkdir() method, this also returns a boolean to pass result of operation. It will return true if file is successfully created otherwise false, which may be due to various reasons e.g. not having sufficient permissions to create file, or there is not enough space to accommodate new files etc.

Code Sample

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
* Simple Java program to create File and Directory in Java, without using
* any third-party library.
* @author http://oraclejavacertified.blogspot.com/
*
*/
public class FileDemo {

    public static void main(String args[]) throws IOException {

        Scanner reader = new Scanner(System.in);
        boolean success = false;

        System.out.println("Enter path of directory to create");
        String dir = reader.nextLine();

        // Creating new directory in Java, if it doesn't exists
        File directory = new File(dir);
        if (directory.exists()) {
            System.out.println("Directory already exists ...");

        } else {
            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();
            if (success) {
                System.out.printf("Successfully created new directory : %s%n", dir);
            } else {
                System.out.printf("Failed to create new directory: %s%n", dir);
            }
        }

        // Creating new file in Java, only if not exists
        System.out.println("Enter file name to be created ");
        String filename = reader.nextLine();

        File f = new File(filename);
        if (f.exists()) {
            System.out.println("File already exists");

        } else {
            System.out.println("No such file exists, creating now");
            success = f.createNewFile();
            if (success) {
                System.out.printf("Successfully created new file: %s%n", f);
            } else {
                System.out.printf("Failed to create new file: %s%n", f);
            }
        }

        // close Scanner to prevent resource leak
        reader.close();

    }
}

Output :

First run :
Enter path of directory to create
C:\dhoom3
Directory not exists, creating now
Successfully created new directory : C:\dhoom3
Enter file name to be created
Abhishek.txt
No such file exists, creating now
Successfully created new file: Abhishek.txt

Second run :
Enter path of directory to create
C:\dhoom3
Directory already exists ...
Enter file name to be created
Abhishek.txt
File already exists

Don't forget to close Scanner once done, a good practice to prevent resource leak in Java. Alternatively you can also use try-with-resource statements from Java 7, which facilitate automatic resource clean up for you. That not only take care of releasing resources once you are done with that, but also removes coding headache and finally block from above code, making it more concise and readable. That's all about how to create or make file and directory in Java.

Saturday, February 15, 2020

Earn Oracle Java Certification and Boost Your Professional Life


Java Certification is one of the most desired Certifications in IT field. Earning a Java Certification will help you to get a dream job. Java Programming is the world's highest used language, no doubt about it. Everyday lot of individuals are coming to Java world because there is always a strong need for Java language. Not only to create have new applications, but new learners required to conceives already written applications in Java. Java/JEE is a vast domain. You can browse any job portal, and you will undoubtedly find amongst all vacant positions Java is in high demand. So it is advised you learn Java language, and to demonstrate your knowledge get certified by Oracle. To help you clear Java Certification, below, we have listed a few tips to make your preparation easy.

Tips to Prepare for Oracle java Certification

1) Mentally Prepare Yourself

Seriously think about why you are getting Java Certification, and why do you want to be Java certified Professional. You have to decide firmly, and you will earn any one of Java Certification which one you opt for your career within the next 3-5 months or so. Try to study with complete dedication.

2) Obtain the Appropriate Study Material

There is a lot of recommendations you obtain your study material, and some applicants study from books, study guides, practice tests, etc.

There are enough resources to provide practice tests to prepare for the Java certification exam. Practice tests help to measure your learning before appear for your actual Java exam. Make sure you get updated and reliable practice tests. Practice tests will also strengthen your confidence. Become a member of the code ranch forum; this is very useful for you, and you will get a lot of helpful answers, tips, and advice from experienced professionals.

3) Approach in Deep

Before start, your Java Certification exam preparation, determine your objectives, and plan your study schedule. Then begin your preparation. Study Both the basic and advanced sessions initially. This will equip you with a good knowledge of concepts. If you have successfully learned the basic and advanced sessions, then you can start taking practice questions available.

4) Register for the Exam

If you already have studied basic and advanced sessions, you should register for the java exam now.

5) Revision

Read one more time to revise the topics. This step is voluntary if you feel you are weak with some topics, and you could not perform well in the practice tests, then you can do this as many time as possible. Go through all the topics one more time.

6) Relax

This is the last part of your study, and there is no u-turn. Don't study a day before the exam. It is necessary to rest and get a good night's sleep. If you follow all the steps above and understand all the topics, you should be more than ready by now.

Why are Java Certifications Important for the IT Professionals?

Java Certifications are a plus point to get jobs quickly because in this competitive world, receiving a job is a challenging task.

Millions of peoples have completed their studies and looking for a job. So to get the first preference for the job opportunity, individuals need the certifications. If you are a Java certified professional, you receive more job opportunities because certifications are the first step or the plus point for the professionals.

Oracle divided the three editions (SE, EE, and ME) into four distinct levels (OCA, OCP, OCE, and OCM) of certifications. On the basis of these levels, you can determine your exam path. Java is the most sought-after technology worldwide because most of the applications are formed in Java technology only. Even smartphones also work on Java technology.

Java field has so many vacant jobs, but the companies give a chance to the certified professionals. The real fact is, "companies strongly believe that certified professionals have the practical experience with the technologies, and also they have definite ideas about the technologies."

This is the only reason all the Java certified professionals point out to all the aspirants, don't rely on the braindumps for your Java certification exam preparation. Learn all the exam topics thoroughly, practice codes. If you follow the dumps, it kills your expertise to deal with technologies; it ruins your working experience, maybe theoretically, you have good knowledge of concepts, but if you do not practice with codes, you could not get expertise in Java language.

So study well, learn the exam objectives thoroughly, Practice with codes, and before sit for your actual Java exam, measure your knowledge level with practice tests.

I hope this article gives you at least some ideas on how to study for the Java certification exam. In any case, if you fail in your exam at the first time, don't get disappointed. You will have more understanding and confidence when you attempt it the next time then the person who passed it on the first attempt.