Getting Started with Java Programming

Writing Your First Java Code

Why Java?

Java is more than just a programming language; it's like a superhero in the world of technology. But what makes Java truly amazing? Well, it's a versatile language with many cool features that not only help big companies create powerful software but also let you build cool applications for web and mobile.

Advantages of Java

Write Once, Run Anywhere

Java can work on all kinds of devices without needing to change the code. We call this "Write Once, Run Anywhere" magic. It's all thanks to a smart thing called the Java Virtual Machine (JVM) that understands and runs Java code on lots of different computers and gadgets.

Java doesn't just stop at being awesome by itself. It's like a friendly host for other languages, like Kotlin, Scala, and Groovy. So, when you learn Java, you're not just learning one language – you're opening the door to a whole world of possibilities. This means you can switch between different languages easily, which is super handy for new developers.

Recognition

Java isn't just a favourite of the tech giants by accident. They've noticed its superpowers and use it to build powerful and reliable stuff. That's why if you want to start a career in software development, Java is a great choice. In job interviews, they might ask you about Java because it shows you can understand and learn other languages like JavaScript, Python, C#, or C++.

Readability

Sure, some people say Java can be a little tricky when you start, but it's one of the easiest languages to read. You can understand it line by line, which isn't always the case with other languages. Java is packed with cool features like letting you write code once and use it everywhere, handling multiple things at once, and having tools to manage errors.

The Evolution of Java

Java's adventure began in 1995 when smart people at Sun Microsystems, led by James Gosling, created it. Later, Oracle took over Sun Microsystems and became the guardian of Java. Since then, Java has been changing and growing, getting better every six months. Even though the changes might not always be super huge, they show that Java is committed to staying a powerful and important language.

Let's Begin Your Java Adventure

In this article, we're going to explore Java together, especially for beginners. We'll break down the important stuff, explain what makes Java cool, and why it's useful in today's tech world. So, get ready to learn about Java.

Setup

Before we dive in, we need to get something important—the JDK, which stands for the Java Development Kit.

Getting the Java Development Kit (JDK)

  1. Open your web browser and type "JDK download" in the search bar.

  2. You'll see a couple of options, including the official version from Oracle and an open-source version. In the past, Oracle had a paid version, but now it's free to use, so we'll go with that.

  3. Click on the first link, that takes you to the official Oracle website for downloading the JDK.

And if you see you will get a lot of options, java releases updates every 6 months so at the time of writing this tutorial, the latest version is 21. With every update, you will get some features but the basic language will remain the same.

Now, you'll notice that there are two versions available. Java releases updates approximately every six months, and at the time of writing this tutorial, the latest version is 21. Each update comes with new features, but the core Java language remains the same.

So, you might be wondering, should you go for version 21 or version 17? The key thing to know is that not every version is a "Long-Term Support" (LTS) version.

Why Choose Java 17 (LTS)?

Java 17 is an LTS version, which receives long-term support and updates. This makes it a more stable choice, especially for beginners. While the non-LTS versions offer exciting new features, they may not be as stable and might have shorter lifespans.

Setting Up JAVA for Your Operating System

Depending on your operating system (OS), the setup process may vary a bit, but the core software remains the same, and the code you write will be consistent. Your choice of OS won't affect your Java programming experience.

For the specifics of setting up Java on your OS, you can easily find step-by-step guides with a quick Google search. Since OS setups can be quite diverse, it's best to refer to resources tailored to your specific OS.

If you've got the JDK sorted out, then we're ready to dive into writing your very first Java code. Stay with me as I guide you through this exciting journey into the world of programming with Java.

Choosing an IDE for Your Java Journey

Now that you're all set with the JDK, let's talk about the tool you'll be using to write your Java programs – the Integrated Development Environment (IDE). There are quite a few options out there, and you can use whichever you're comfortable with. You've got choices like Eclipse, Visual Studio Code, IntelliJ, and hey, you can even go old school with Notepad.

Choosing an IDE is a bit like picking the perfect paintbrush for your masterpiece. It's a personal choice. Whichever IDE you choose, the journey into Java programming is what matters most. So, let's get ready to dive into the coding adventure together!

Writing Your First Java Code

Now that we've got Java set up, let's dive into how Java works and the steps it takes to turn your code into something a computer can understand. Don't worry; we'll keep it simple!

How Does Java Work?

Java is pretty cool because it doesn't care about the computer you're using or the operating system (OS) it runs on. When you write Java code, it can run on any computer, as long as that computer has something called a JVM, which stands for Java Virtual Machine. But here's the catch: JVM itself depends on the specific OS. So, your application is OS-independent, but JVM isn't. Every OS has its own JVM.

Java's Secret: Bytecode

So, JVM says, "I'll run your code, but you need to give me something special called bytecode, not your regular Java code." Bytecode is like a secret language that only JVM understands. You can't write bytecode yourself because you speak human languages like English, not computer languages.

Here's how it works: You write your Java code, and then you use a tool called a compiler to turn it into bytecode. Since we're talking about Java, you can call this tool "javac" which stands for Java compiler. Once you have your bytecode, you feed it to JVM, and it starts running.

One File to Rule Them All

Now, in your project, you might have loads of files—10, 100, 1000 of them! But guess what? JVM only cares about one special file, the one it's going to execute. So, you need to tell JVM which file to start with. This file must have something called a "main method," and it should look exactly like this:

public static void main(String[] args)

Without this magic "main method" and the right signature, your code won't run.

Let's Write Your First Java Code

To get started, create a file named "Hello.java" with the code below (keep an eye on the ".java" extension):

// Hello.java

class Hello {
    public static void main(String[] args) {
        System.out.print("Hello World");
    }
}

Now, to turn this code into bytecode, open your terminal or command prompt and type:

javac Hello.java

As soon as you hit Enter, you'll notice another file called "Hello.class." That's where your bytecode lives and JVM can understand it.

Time to Run Your Code

Now, to see your code in action, type the following command in your terminal:

java Hello

You're not running the filename ("Hello.java") but the classname ("Hello") this time. And just like that, you've run your very first Java code! It should display "Hello World" in the terminal.

Variables in Java

In Java, variable types are strongly typed, which means that the data type of a variable is explicitly declared and enforced at compile time. This ensures that you can't perform operations on variables of incompatible types without explicit type casting. Here's an explanation and some code examples to illustrate strongly typed variables in Java.

1. Variable Declaration: In Java, when you declare a variable, you explicitly specify its data type. For example:

int age = 24; // Declare an integer variable
String name = "Victoria"; // Declare a string variable
double salary = 20000.20; // Declare a double variable

In the above code, the data type (int, String, double) is explicitly declared when the variables (age, name, salary) are defined.

2. Type Safety: Strongly typed languages, like Java, provide type safety. This means that you cannot assign values of one data type to a variable of another data type without proper casting.

For example, you cannot do this without casting:

int x = 10;
String str = x; // This will result in a compilation error

To make it work, you need to cast the int to a String explicitly:

int x = 10;
String str = Integer.toString(x); // Correct way to convert int to String

3. Type Inference (Java 10+): In modern versions of Java (Java 10 and later), there is a feature called "var" that allows for local variable type inference. With "var," you can declare variables without explicitly specifying their data type, but the type is still determined at compile time.

For example:

var age = 24; // Compiler infers that age is an int
var name = "Victoria"; // Compiler infers that name is a String

4. Strong Typing in Function Arguments: Strong typing is also enforced in function arguments. If a method expects a specific data type as an argument, you must provide that exact data type.

For example:

public void printNumber(int num) {
    System.out.println(num);
}

public static void main(String[] args) {
    printNumber(10); // Correct usage
    printNumber("10"); // Compilation error because a string is not an int
}

In summary, strong typing in Java ensures that you declare and use variables with specific data types, and it prevents you from performing operations that would lead to type mismatches without explicit type casting. This helps catch type-related errors at compile time, making Java a safer and more reliable language.

Data types in Java

In Java, data types are used to categorize and specify the type of data that a variable can hold. Data types in Java are broadly categorized into two groups: primitive data types and non-primitive/reference data types. Here, I'll explain these data types and provide code examples for each.

1. Primitive Data Types: Primitive data types represent basic, simple data values. Java provides several primitive data types, including:

  • int: Represents integer values.

  • double: Represents floating-point numbers (decimal numbers).

  • char: Represents a single character.

  • boolean: Represents a true or false value.

  • byte: Represents small integer values.

  • short: Represents short integer values.

  • long: Represents long integer values.

  • float: Represents single-precision floating-point numbers.

Here are some code examples:

int age = 24;
double salary = 20000.20;
char grade = 'A';
boolean isJavaFun = true;
byte smallNumber = 123;
short smallInteger = 43767;
long veryLargeNumber = 123456789012345L; // Note the 'L' at the end for long
float smallDecimal = 3.14F; // Note the 'F' at the end for float

2. Non-primitive/Reference Data Types: Reference data types are more complex and represent objects and references to objects. Some common reference data types include:

  • String: Represents a sequence of characters.

  • Arrays: Represents a collection of elements of the same data type.

  • Classes: You can create your data types using classes.

Here's an example using the String reference data type:

String name = "John Doe";

You can also create custom reference data types using classes. For example:

class Person {
    String name;
    int age;
}

Person person1 = new Person();
person1.name = "Elizabeth";
person1.age = 20;

Person person2 = new Person();
person2.name = "Bob";
person2.age = 25;

In the above example, Person is a custom reference data type created using a class. It can hold both String and int data for representing information about a person.

These are the fundamental data types in Java, and they are essential for defining and working with data in Java programs. Different data types are used for different purposes, and choosing the right data type is important for efficient and error-free programming.

Assignment Operators in Java

// Hello.java

class Hello {
    public static void main(String[] args) {
        int num = 7;
        num += 1;
        num++; //post increment
        ++num; //pre increment
        num--;

        int result = num++; //fetch the value of num and assign it to result, then incremented value of num 
        int result = ++num; //increment the value of num, fetch the value and then assign it to result 


    }
}

Conclusion

Congratulations! You've taken your first steps into the exciting world of Java programming. The journey is just beginning, so stay curious and keep exploring.

To stay updated on all the awesome tutorials and reads coming your way, be sure to hit that like ❤️, share ↗️, and follow button. Thanks for reading. ❤️

Happy coding!