Java Basics — Understanding Basic Syntax

Vahe Aslanyan
9 min readJan 4, 2024

--

If you’re keen on furthering your Java knowledge, here’s a guide to help you conquer Java and launch your coding career. It’s perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  1. Java Data Structures Mastery — Ace the Coding Interview: A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  2. Foundations of Java Data Structures — Your Coding Catalyst: Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech’s website for these resources and more information on the bootcamp.

Connect with Me:

Your First Java Program

This chapter will introduce you to Java programming, starting with the fundamental ‘Hello, World!’ program.

Get Set Up:

JDK Installation: Every Java developer starts with the Java Development Kit (JDK). It equips your machine to understand and execute Java code. Ensure you have the latest JDK installed.

Here’s a guide that’ll help you install JDK in Ubuntu, and here’s one that’ll help you install it on Windows.

IDE Choice: Integrated Development Environments (IDEs) like Eclipse, IntelliJ IDEA, or NetBeans streamline the coding process. I personally prefer IntelliJ IDEA, because of its intuitive interface.

Start Building the Program:

Java hinges on classes. Think of them as blueprints. Our program begins with the HelloWorld class.

Within this class, we house the main method – Java's starting line. This is where we instruct Java to print "Hello, World!".

Here’s what our first Java code will look like:

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

Hello World using Java

Run the Program:

Using IntelliJ IDEA, save your file as HelloWorld.java. Hit the 'Run' button, and voilà! "Hello, World!" should appear in the output console. If you're using the command line, compile with javac HelloWorld.java and run with java HelloWorld.

Deciphering the Code:

  • class: Denotes a blueprint. HelloWorld is our chosen name.
  • public static void main(String[] args): The doorway into our program. Every Java application has one.
  • System.out.println: Java's way of printing to the console. "Hello, World!" is the message we chose.

Congratulations! You’ve penned and executed your first Java program. As you delve deeper into Java, remember this first step.

Understanding Java Syntax

Now that we have crafted our first program, we stand on the threshold of delving into the heart of Java programming — the syntax.

Programming in Java is an exercise in clarity. Its syntax is a lucid framework designed not only to instruct the computer but to facilitate a deliberate and efficient dialogue with technology.

As we embark on this journey of understanding Java’s syntax, remember it’s more than memorizing rules — it’s about mastering the art of clear and purposeful communication with the digital world.

Objects and Classes in Java

Visualize a cat. In Java, a class like Cat serves as a blueprint for creating objects —a template that defines the state and behavior bound to specific data.

For example, when we instantiate a new Cat object using Cat tabby = new Cat();, we bring an instance of the Cat class into memory, complete with attributes such as color and mood, which describe the state of the cat, and methods like purr(), which is an action the cat can perform.

Encapsulation is at play here, encapsulating the cat’s properties and the actions it can perform within one cohesive unit.

class Cat {
String color;
String mood;
    void purr() {
System.out.println("Cat purrs");
}
}

Constructors are specialized methods invoked at the time of object creation to initialize new objects. Java also utilizes access modifiers like public, private, and others to define the accessibility of class members, which play a crucial role in object interaction and encapsulation.

The new keyword is vital as it allocates memory for new Cat instances. Through methods, these objects can interact, influence one another, and collaborate to form complex systems.

public class Cat {
// Using 'private' to restrict access to the properties from outside this class
private String color;
private String mood;
    // Public constructor for Cat class
public Cat(String color, String mood) {
// The 'this' keyword refers to the current instance of the class
this.color = color;
this.mood = mood;
}
// Public method to access the private color field
public String getColor() {
return color;
}
// Public method to access the private mood field
public String getMood() {
return mood;
}
// Private method, only accessible within this class
private void changeMood(String newMood) {
mood = newMood;
}
// Public method to expose the behavior of the Cat object
public void purr() {
System.out.println("Cat purrs");
}
// Public method to interact with the private changeMood method
public void makeHappy() {
changeMood("happy");
purr(); // The cat purrs when made happy
}
}
// To use the class, you would create an instance of Cat using the new keyword
public class Main {
public static void main(String[] args) {
// Creating a new Cat object with the 'new' keyword and the constructor
Cat myCat = new Cat("black", "sleepy");
// Accessing the public methods of the Cat class
System.out.println("The cat is " + myCat.getColor() + " and feels " + myCat.getMood());
myCat.makeHappy(); // Makes the cat happy which internally changes its mood and makes it purr
}
}

In Java, constructors are crucial for initializing new objects, as demonstrated by the Cat class's public constructor Cat(String color, String mood). It's used to set the private fields color and mood.

These private fields encapsulate the state of a Cat object, ensuring controlled access through public methods like getColor() and getMood(). The new keyword is instrumental in this process, allocating memory for new instances. While the changeMood() method remains private for internal class use, the purr() method is public, allowing interaction with the cat's behavior.

By instantiating a new Cat object in the Main class, we demonstrate how objects are created and showcase the interplay of access modifiers that safeguard encapsulation and enable object collaboration within complex systems.

Methods in Java

Methods in Java are the actionable souls of objects. They define specific tasks that objects can perform.

In the Cat class shown, void meow() and void scratch() are method signatures, where void indicates they don't return any value, and the names meow and scratch are the actions they perform. Parentheses following the method names indicate the potential to accept inputs, which these particular methods do not require.

To activate a method, we call it on an object, like tabby.meow();, where tabby is the instance of the Cat class and meow() is the method being invoked.

Methods can encapsulate behaviors, allowing an object like tabby to exhibit actions such as meowing or scratching, and they can be reused to perform these actions multiple times.

This modularity not only promotes reusability but also helps maintain the integrity of an object’s internal state, a cornerstone of encapsulation in object-oriented programming.

public class Cat {
    // A method with no return value (void) that represents the cat's action of meowing
public void meow() {
// Prints "Meow!" to the console when the method is called
System.out.println("Meow!");
}
// A method with no return value (void) that represents the cat's action of scratching
public void scratch() {
// Prints "Scratch!" to the console when the method is called
System.out.println("Scratch!");
}
// Example of a method that changes the internal state of the object
// Here, we assume a mood property is part of the Cat class
private void changeMood(String mood) {
// This method is private and cannot be called from outside the Cat class
}

// Additional method to demonstrate calling other methods and reusability
public void displayBehavior() {
meow(); // The cat meows
scratch(); // The cat scratches
changeMood("curious"); // The cat's mood is changed internally
}
}
// Class containing the main method to run the program
public class Main {
public static void main(String[] args) {
// Creating a new Cat object using the 'new' keyword
Cat tabby = new Cat();

// Calling the public methods of the Cat class
tabby.meow(); // Output: Meow!
tabby.scratch(); // Output: Scratch!
// Demonstrating the reusability of methods
tabby.displayBehavior(); // Calls multiple methods to display behaviors
}
}

Instance Variables in Java

Instance variables capture the essence of an object’s state within a Java class. In the example of a Cat class, the properties name and age are specific to each Cat object, giving each a unique identity.

public class Cat {
// Private instance variables, encapsulating the state of the Cat object
private String name;
private int age;
    // Constructor that initializes a Cat object with a given name and age
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
// Public getter for the name, allowing read access to the private variable
public String getName() {
return this.name;
}
// Public setter for the name, allowing write access to the private variable
public void setName(String name) {
this.name = name;
}
// Public getter for the age, allowing read access to the private variable
public int getAge() {
return this.age;
}
// Public setter for the age, allowing write access to the private variable
public void setAge(int age) {
this.age = age;
}
// Public method to display the Cat's attributes
public void displayInfo() {
System.out.println(this.name + " is " + this.age + " year(s) old.");
}
}

Here, encapsulation is employed by making the name and age variables private, which means they cannot be accessed directly from outside the class. Instead, public getters and setters (getName(), setName(String name), getAge(), and setAge(int age)) are provided to interact with these properties safely.

This approach not only protects the data from being changed in unintended ways but also enables a controlled interface for other classes to interact with the Cat objects.

Java Basic Syntax Rules

Java’s syntax forms the foundation of its programming structure:

// The 'public' modifier allows this class to be accessed from other classes.
public class MyClass {
// 'main' method: Java starts executing the program from this method.
public static void main(String[] args) {
// ... your code goes here
}
}

When crafting a Java class:

  1. Class Declaration: The public keyword specifies that the class is accessible from anywhere in the program, promoting a modular and interactive coding environment.
  2. The main Method: This is where the program's execution commences. It must be public to be universally invokable, static to be callable without instantiating the class, and void to indicate it doesn't return any value. The String[] args parameter serves as a container for any command-line arguments that may be passed to the program.
  3. File Name: The name of the source file should precisely match the class name (MyClass in this case) and should have the .java extension (hence MyClass.java), which is essential for the Java compiler to recognize and compile the class correctly.

By adhering to these basic syntax rules, you ensure that your Java program is structured correctly and ready for execution. These guidelines lay the groundwork for developing clean, efficient, and well-functioning Java applications.

Resources

If you’re keen on furthering your Java knowledge, here’s a guide to help you conquer Java and launch your coding career. It’s perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  1. Java Data Structures Mastery — Ace the Coding Interview: A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  2. Foundations of Java Data Structures — Your Coding Catalyst: Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech’s website for these resources and more information on the bootcamp.

Connect with Me:

--

--

Vahe Aslanyan
Vahe Aslanyan

Written by Vahe Aslanyan

Studying Computer Science and experienced with top tech firms, I co-founded LunarTech to revolutionize data science education. Join us for excellence.

No responses yet