Chapter1: Java Basics to Learn

·

5 min read

Chapter1: Java Basics to Learn

Why Java?

Java is popular because it lets developers write code that works on different devices, thanks to its "write once, run anywhere" feature. It's like a versatile tool for building programs. It encourages good coding practices with its object-oriented approach and comes with a bunch of useful pre-made code (standard library) which aligns well with DSA concepts, and its robust standard libraries provide a wide range of data structures and algorithms for practice and implementation. Additionally, Java's platform independence allows learners to focus on DSA principles without worrying about low-level system details.

Installation and Execution of program

To compile and run a Java file using the command prompt (cmd) on Windows, follow these steps:

  1. Install Java to run the code:
  • Make sure you have Java Development Kit (JDK) installed on your computer. You can download it from the official Oracle website.
  1. Write Your Java Code:
  • Use a text editor (e.g., Notepad) to write your Java code. Save the file with a ".java" extension. For example, you can create a file named "HelloWorld.java" with the following content:

    public class HelloWorld {
        public static void main(String[] args) {
            //Display Hello, World!
            System.out.println("Hello, World!");
        }
    }
  1. Open Command Prompt (cmd):

    Press Win + R, type "cmd," and press Enter to open the command prompt.

  2. Navigate to the Directory Containing Your Java File:

    Use the cd (change directory) command to navigate to the directory where your Java file is located. For example:

    1.        cd path\to\your\java\file\directory
      

Compile the Java Program:

  • Use the javac command to compile your Java source file (replace "HelloWorld.java" with your file's name if different):

          java HelloWorld
    

    Now if everything is done perfectly, then you should see the output of your program, which is "Hello, World!" in this case.

    That's all it is. Now you know how to compile and run a program. This is how you run complex programs too. Practice more to get the flow.

Inputs in Java

In Java, taking inputs from a user involves using the Scanner class, which is part of the java.util package. Here's a simple explanation:

Import Scanner Class: First, you need to tell Java that you want to use the Scanner class. At the beginning of your program, include this line:

import java.util.Scanner;

Create Scanner Object: Next, create a Scanner object to read input. This is like having a tool to help you get information from the user:

Scanner scanner = new Scanner(System.in);

Get Input: Now, you can use the Scanner object to get input from the user. For example, to get an integer, you can do:

System.out.print("Enter an integer: ");
int a = scanner.nextInt();

If you want a string, you can use:

System.out.print("Enter a string: ");
String str = scanner.next();

Print the output

Use the Input: Finally, you can use the input you got from the user in your program. For example, you can print it back:

System.out.println("You entered: " + a);

Close the Scanner: It's good practice to close the Scanner when you're done to free up resources:

scanner.close();

A simple program

Here's a simple program that puts it all together:

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        // Step 2: Create Scanner object
        Scanner scanner = new Scanner(System.in);

        // Step 3: Get input
        System.out.print("Enter your name: ");
        String userName = scanner.next();

        // Step 4: Use the input
        System.out.println("Hello, " + userName + "!");

        // Step 5: Close the Scanner
        scanner.close();
    }
}

This program prompts the user to enter their name, takes the input, and then prints a greeting using the entered name.

Various Scanner methods

You can use various Scanner methods to read input based on the data type you expect. Here are some common methods:

  • nextLine(): Reads a line of text (including spaces) as a String.

  • nextInt(): Reads the next integer.

  • nextDouble(): Reads the next double-precision floating-point number.

  • nextBoolean(): Reads the next boolean value (true or false).

  • next().charAt(0): Reads the next char value.

  • next(): Reads individual words.

Type Casting

In Java, there are two main types of type casting: implicit casting (widening) and explicit casting (narrowing).

Implicit Casting (Widening):

  • Implicit casting occurs automatically when you assign a value of a smaller data type to a variable of a larger data type.

  • It's safe because there is no risk of data loss or loss of precision.

int intValue = 42;
double doubleValue = intValue; // Implicit casting from int to double

Explicit Casting (Narrowing):

  • Explicit casting is required when you want to convert a value of a larger data type to a smaller data type.

  • It may result in data loss or loss of precision, so you need to use a cast operator.

double doubleValue = 3.14;
int intValue = (int) doubleValue; // Explicit casting from double to int

Conclusion

In this insightful journey through the foundational concepts of Java programming, we've explored the various facets that make Java one of the most popular and versatile programming languages. Our very first Java program, delving into input handling with the Scanner class, and type casting, we've laid a strong foundation for our coding endeavors.

As we continue this learning journey, we'll explore more intricate topics, build sophisticated applications, and embark on exciting coding challenges.

Stay tuned for the next chapter in our learning adventure, where we'll delve deeper into Java, tackle more advanced programming concepts, and work towards becoming proficient developers. Until then cheers to all, happy coding!