Diving into Core Java — Part 1

Proteek Bose
9 min readJan 2, 2024

--

Embarking on your journey to learn Java can be exhilarating yet challenging. This article serves as your companion through the initial steps of understanding and practicing Core Java. It’s structured to provide a clear learning path, complete with code snippets, explanations, and typical interview questions related to each topic.

Introduction to Java Language

Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It’s a widely used robust technology.

Why Java?

  • Platform Independent: Write once, run anywhere.
  • Object-Oriented: Enhances flexibility and maintainability.
  • Secure: Designed with security in mind.

Interview Question Example: What are the main features of Java?

JDK Setup

The Java Development Kit (JDK) is a software development environment used for developing Java applications. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development.

Steps for JDK Setup:

  1. Download JDK from the Oracle website.
  2. Install and verify by typing java -version in your command line.

Interview Question Example: How do you set up JDK on your system?

Setting Environment Variable

Setting the environment variable is crucial for the OS to locate the JDK tools.

Steps to Set Environment Variable:

  1. Locate your JDK installation directory.
  2. Set the JAVA_HOME environment variable to this path.
  3. Update the system path to include %JAVA_HOME%\bin.

Interview Question Example: What is the JAVA_HOME environment variable, and why is it important?

Choice of IDE

An Integrated Development Environment (IDE) is where you will write your Java programs. Popular ones include Eclipse, IntelliJ IDEA, and NetBeans.

Factors to Consider When Choosing an IDE:

  • Ease of Use: Should have an intuitive interface.
  • Support and Community: A good community means better support.
  • Performance: Should be fast and able to handle large projects.

Interview Question Example: What IDE do you use for Java development and why?

Hello World Code in Java

Every Java developer’s journey starts with the traditional “Hello, World!” program.

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

Explanation: This code defines a class HelloWorld with a main method that prints "Hello, World!" to the console.

Interview Question Example: Can you explain the structure of a basic Java program?

How Java Works

Understanding how Java works from code to execution is crucial.

The Process:

  1. Write Code: You write the .java file.
  2. Compile: The javac compiler converts it into bytecode (.class files).
  3. Load: The Classloader loads the bytecode.
  4. Bytecode Verification: Verifies the code for security and Java standards.
  5. Execution: The Just-In-Time (JIT) compiler of JVM executes the bytecode.

Interview Question Example: What is the role of the JVM, and why is Java called platform-independent?

Variables

In Java, variables are containers that hold data values during the execution of a program. They are a fundamental aspect of any programming language, allowing you to store and manipulate data dynamically. Understanding variables is crucial for writing any Java program, as they are used to represent real-world data and calculations within your code.

Declaration and Initialization:
Before you can use a variable in Java, you must declare it, specifying the data type it will hold. This tells the Java compiler what type of data the variable will store and how much memory to allocate for it.

Declaration Syntax: dataType variableName;

You can also initialize a variable, which means you assign it an initial value at the time of declaration.

Initialization Syntax: dataType variableName = value;

Types of Variables:

  1. Local Variables: These are declared within a block or method. They are created when the block is entered and destroyed upon exit from the block.

Example:

public void myMethod() {
int localNum = 10; // Local variable
System.out.println(“Local Number: “ + localNum);
}

2. Instance Variables: These are declared in a class but outside any method, constructor, or block. Each instance (object) of the class will have its copy of these variables.

Example:

public class MyClass {
int instanceNum; // Instance variable

public MyClass(int num) {
this.instanceNum = num;
}

public void displayNumber() {
System.out.println(“Instance Number: “ + instanceNum);
}
}

3. Class/Static Variables: These are declared with the static keyword in a class but outside any method, constructor, or block. They are stored in the static memory and are shared among all instances of the class.

Example:

public class MyClass {
static int staticNum; // Static variable

public static void displayStaticNumber() {
System.out.println(“Static Number: “ + staticNum);
}
}

Example Code Demonstrating Variables:

public class VariableExamples {

static int staticNum = 99; // Static variable

int instanceNum; // Instance variable

public VariableExamples(int num) {
this.instanceNum = num;
}

public static void main(String[] args) {

int localNum = 15; // Local variable

// Creating an object of VariableExamples and passing 25 to the constructor
VariableExamples obj = new VariableExamples(25);

// Accessing instance variable through object reference
System.out.println(“Instance Number: “ + obj.instanceNum);

// Accessing static variable
System.out.println(“Static Number: “ + VariableExamples.staticNum);

// Accessing local variable
System.out.println(“Local Number: “ + localNum);
}
}

Explanation:

  • Static Variable: staticNum is a static variable shared by all instances of VariableExamples. It's accessed directly with the class name, VariableExamples.staticNum.
  • Instance Variable: instanceNum is an instance variable unique to each object of VariableExamples. It's accessed through the object reference, obj.instanceNum.
  • Local Variable: localNum is a local variable that exists only within the main method's scope.

Best Practices:

  • Naming: Use meaningful variable names to make your code more readable.
  • Scope: Keep the scope of variables as narrow as possible to ensure they don’t affect other parts of your program.
  • Initialization: Always initialize your variables. Uninitialized variables can lead to unpredictable behavior.

Interview Question Example: What is the difference between local, instance, and class variables in Java?

Data Types

Java is a strongly typed language, which means every variable and every expression has a type that is known at compile time. Types determine what values can be stored and what operations can be performed. Understanding data types is crucial for writing any Java program, as they form the building blocks of the data you will manipulate.

  • Primitive Types: int, boolean, char, float, etc.
  • Non-Primitive Types: String, Arrays, Classes, etc.

Primitive Types:
Primitive types are the most basic kinds of data types and are built-in to the Java language. They are not objects and hold their values in the memory where the variable is allocated.

  1. int: Represents an integer, a whole number. It has a width of 32 bits and has a range from -2,147,483,648 to 2,147,483,647.
    Example: int myNum = 100;
  2. boolean: Represents one bit of information, but its “size” isn’t something that’s precisely defined. It has only two possible values: true and false.
    Example: boolean isJavaFun = true;
  3. char: Represents a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
    Example: char myGrade = 'A';
  4. float: Represents a single-precision 32-bit IEEE 754 floating point. It’s mainly used to save memory in large arrays of floating point numbers.
    Example: float myFloatNum = 5.99f;
  5. … and others: such as byte (8-bit integers), short (16-bit integers), long (64-bit integers), double (double-precision 64-bit IEEE 754 floating points).

Example Code for Primitive Types:

public class PrimitiveExamples {
public static void main(String[] args) {
int myNum = 100;
boolean isJavaFun = true;
char myGrade = ‘A’;
float myFloatNum = 5.99f;

System.out.println(“Integer: “ + myNum);
System.out.println(“Boolean: “ + isJavaFun);
System.out.println(“Character: “ + myGrade);
System.out.println(“Float: “ + myFloatNum);
}
}

Non-Primitive Types (Reference Types):
Non-primitive types are more complex types referred to by references. They can be used to call methods to perform certain operations, while primitive types cannot. A reference type references a memory location where the data is stored rather than directly containing a value.

  1. String: Represents a sequence of characters, like a Python string. It’s not a primitive data type, but it’s so commonly used that it’s often referred to alongside them.
    Example: String greeting = "Hello World";
  2. Arrays: An array in Java is a type that can hold multiple values of the same type. The elements in an array are ordered and have specific, fixed positions.
    Example: int[] myNumArray = {10, 20, 30, 40};
  3. Classes/Objects: In Java, a class is a user-defined blueprint or prototype from which objects are created. Objects are instances of classes. Example:
    public class Main {
    int x = 5;
    }
    Main myObj = new Main();
    System.out.println(myObj.x);

Example Code for Non-Primitive Types:

public class NonPrimitiveExamples {
public static void main(String[] args) {
// String Example
String greeting = “Hello World”;

// Array Example
int[] myNumArray = {10, 20, 30, 40};

// Object Example
Main myObj = new Main();

System.out.println(“String: “ + greeting);
System.out.println(“Array Element: “ + myNumArray[2]);
System.out.println(“Object Attribute: “ + myObj.x);
}

public static class Main {
int x = 5;
}
}

Interview Question Example: What is the difference between primitive and non-primitive data types?

Literals

Literals are a fixed value that appears directly in your code. For example, 100, 'A', and "Hello" are all literals.

int age = 25;

Explanation: Here, 25 is an integer literal.

Interview Question Example: Can you give an example of a literal in Java?

Type Conversion

Type conversion in Java is the process of converting a value from one data type to another. This is a common practice in programming when you need to operate on values of different types. Java supports two types of conversions: implicit (automatic) and explicit (manual), each vital for different scenarios.

Implicit Conversion (Automatic)

Implicit conversion, also known as widening conversion, occurs when the data type of a smaller-sized variable is converted to a larger-sized data type. Java does this automatically because there’s no risk of data loss. For instance, converting an int to a long, or a float to a double, is done implicitly by the Java compiler.

int myInt = 100;
long myLong = myInt; // Automatically converts the int to a long

float myFloat = myLong; // Automatically converts the long to a float
System.out.println(“Int value: “ + myInt);
System.out.println(“Long value: “ + myLong);
System.out.println(“Float value: “ + myFloat);

Explanation:

  • Line 1: An integer myInt is declared and initialized to 100.
  • Line 2: A long myLong is declared and automatically assigned the value of myInt. Even though long is larger than int, Java automatically converts and assigns the value because there's no risk of losing information.
  • Line 3: A float myFloat is declared and automatically assigned the value of myLong. The same automatic conversion logic applies here.

In these cases, Java handles the conversion for you because the target type can accommodate all possible values of the source type without loss of precision or range.

Explicit Conversion (Manual/Casting)

Explicit conversion, also known as narrowing conversion, is necessary when you’re converting from a larger-sized data type to a smaller-sized type. This process is not automatic because there’s a risk of data loss or precision loss. You, the programmer, must explicitly direct Java to perform this conversion using casting.

double myDouble = 9.78;
int myInt = (int) myDouble; // Manually casting double to int

char myChar = (char) myInt; // Manually casting int to char
System.out.println(“Double value: “ + myDouble);
System.out.println(“Converted Integer: “ + myInt);
System.out.println(“Converted Char: “ + myChar);

Explanation:

  • Line 1: A double myDouble is declared and initialized to 9.78.
  • Line 2: An integer myInt is declared. It's explicitly cast from the double myDouble. Here, the fractional part (0.78) is lost because int can only hold whole numbers.
  • Line 3: A character myChar is declared. It's explicitly cast from the integer myInt. This conversion translates the integer value to its equivalent ASCII character.

In explicit conversions, data loss might occur. In the above example, when converting double to int, the fractional part is lost. Therefore, explicit casting should be done carefully and usually when you're certain that the conversion won't lead to unexpected results or when you're willing to accept the lossy conversion due to specific requirements.

Best Practices and Considerations

  • Data Loss: Always be cautious with explicit conversions. Understand that narrowing conversions might lose information.
  • Code Readability: Overusing type conversions, especially explicit ones, can make your code hard to read and maintain.
  • Numeric Limits: Be aware of the limits of numeric types to avoid overflow or underflow errors.
  • Precision: When dealing with floating-point numbers, consider the precision and how it might affect your calculations.

As you embark on this journey, remember that practice is key. Try modifying the code snippets, predict the output, and play around with variations to deepen your understanding. Your path to becoming a proficient Java developer is a marathon, not a sprint. Happy coding!

Next Up: Stay tuned for our follow-up articles, where we’ll explore each topic more deeply with advanced examples, best practices, and more interview questions to prepare you for your Java developer journey.

--

--

No responses yet