Java for Beginners
September 9th, 2023
Week 1: Introduction to Java and Basic Programming Concepts
Class 1: Introduction to Programming and Java
What is Programming?
Programming is the process of giving instructions to a computer to perform specific tasks. Computers understand instructions in the form of code, which is written in programming languages like Java.
Introduction to Java
Java is a versatile and widely-used programming language with its own set of strengths and weaknesses compared to other languages. When to use Java depends on your project’s requirements and goals. Below are some of the pros and cons of Java:
Pros of Java:
-
Platform Independence (Write Once, Run Anywhere): Java applications can run on any platform that has a Java Virtual Machine (JVM), which makes it highly portable. This is a significant advantage for cross-platform development.
-
Strong Object-Oriented Language: Java enforces strong object-oriented programming principles, making it suitable for building modular and maintainable code.
-
Rich Standard Library: Java offers a vast standard library that includes classes and methods for a wide range of functionalities. This can significantly speed up development and reduce the need for reinventing the wheel.
-
Memory Management: Java has built-in automatic memory management (garbage collection), which helps prevent memory leaks and simplifies memory management for developers.
-
Multi-Threading and Concurrency: Java provides built-in support for multi-threading, allowing developers to create concurrent and responsive applications.
Cons of Java:
-
Performance: While Java has improved over the years, it may still be less performant than some lower-level languages like C or C++. However, modern JVMs have made significant performance enhancements.
-
Verbosity: Java code can be verbose, requiring more lines of code compared to some other languages for accomplishing similar tasks.
-
Learning Curve: For beginners, Java’s strict syntax and object-oriented concepts may present a steeper learning curve compared to some dynamically-typed languages.
When to Use Java:
-
Android App Development: Java was traditionally one of the primary languages for Android app development. However, Kotlin has gained popularity in recent years and is now the preferred language for Android.
-
Big Data and Cloud Computing: Java is commonly used in big data and cloud computing frameworks like Hadoop, Spark, and AWS Lambda.
-
Web Development: Java can be used for server-side web development with frameworks like Spring, JavaServer Faces (JSF), and Apache Struts.
Setting up the Java Development Environment
To start writing Java code, you need to set up the development environment. Follow these steps:
- Download and install the Java Development Kit (JDK).
- Install a code editor or integrated development environment (IDE) like Eclipse, IntelliJ IDEA, or Visual Studio Code.
Writing and Running a Simple “Hello World” Program
In Java, a simple program that prints “Hello, World!” to the screen looks like this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld
: Defines a class named HelloWorld.public static void main(String[] args)
: This is the main method where the program starts execution.System.out.println("Hello, World!");
: Prints “Hello, World!” to the console.
Exercise
Write a Java program that prints your name to the console.
Class 2: Variables and Data Types
Variables
- Variables are used to store data in a program.
- In Java, you must declare a variable with a specific data type before using it.
- There are two main categories of data types in Java: primitive data types and reference (object) data types.
Primitive Data Types
Primitive data types represent single values and are built into the Java language. They are simple and provide better performance because they store the actual value, not a reference to an object. Here are some commonly used primitive data types:
-
int
: Represents integer numbers (e.g., 42). It can store whole numbers, both positive and negative. -
double
: Represents floating-point numbers with decimal places (e.g., 3.1415). It’s used for numbers with fractional parts. -
char
: Represents single characters (e.g., ‘A’). It stores a single Unicode character. -
boolean
: Represents true or false values. It’s used for conditions and logic (e.g.,true
orfalse
).
Example:
int age = 25;
double pi = 3.1415;
char grade = 'A';
boolean isJavaFun = true;
Type Casting in Java
Type casting in Java refers to the process of converting a value from one data type to another. This is necessary when you want to assign a value of one data type to a variable of a different data type or perform operations that involve different data types. There are two types of type casting in Java:
- Implicit Type Casting (Widening Conversion):
- Implicit type casting occurs when the conversion is done automatically by the Java compiler.
- It happens when you assign a smaller data type to a larger data type, ensuring that there is no loss of data.
- For example, assigning an
int
to adouble
or afloat
to adouble
is implicit type casting.
int x = 5; double y = x; // Implicit type casting from int to double
- Explicit Type Casting (Narrowing Conversion):
- Explicit type casting is done manually by the programmer.
- It is required when you want to convert a larger data type to a smaller data type, which may result in data loss or precision issues.
- To perform explicit type casting, you use a cast operator ().
double a = 5.6; int b = (int) a; // Explicit type casting from double to int
It’s important to note that during explicit type casting, there may be a loss of data or precision if the target data type cannot fully represent the original value. For example, casting a
double
to anint
will truncate the decimal part.
Type casting is commonly used when working with mixed data types in expressions, input/output operations, or when you need to ensure compatibility between different data types. However, it should be used with caution to avoid data loss or unexpected behavior in your Java programs.
Reference (Object) Data Types
Reference data types do not store the actual data but store references (memory addresses) to objects in memory. They are more complex and versatile than primitive data types. One of the most commonly used reference data types is:
String
: Represents a sequence of characters (e.g., “Hello”). It is implemented as an object in Java and provides various methods for working with strings.
Example:
String greeting = "Hello, World!";
When you create a String
object, Java allocates memory to store the character sequence and provides methods to manipulate it. Other reference data types include arrays, classes, and user-defined objects.
Memory usage in Java
Understanding the difference between primitive and reference data types is essential when working with Java, as it affects memory usage, performance, and the way you interact with data in your programs.
Memory allocation and management in Java are automatic and handled by the Java Virtual Machine (JVM). Let’s explore how memory is utilized in Java, including the concept of the byte unit and the sizes of various data types in bytes.
Primitive data types are used to represent simple values, and they directly store the actual value in memory. They are typically used for basic data such as numbers and characters. Here are some common primitive data types and their sizes in bytes:
byte
(8 bits or 1 byte): Represents small integers from -128 to 127.short
(16 bits or 2 bytes): Represents small integers from -32,768 to 32,767.int
(32 bits or 4 bytes): Represents integers from approximately -2 billion to 2 billion.long
(64 bits or 8 bytes): Represents large integers.float
(32 bits or 4 bytes): Represents single-precision floating-point numbers.double
(64 bits or 8 bytes): Represents double-precision floating-point numbers.char
(16 bits or 2 bytes): Represents a single Unicode character.boolean
(size not strictly defined): Represents true or false values.
Reference data types store references (memory addresses) to objects in memory, rather than the actual data itself. They are used for more complex and user-defined data structures. The size of a reference data type variable is consistent, regardless of the size of the object it refers to. Common reference data types include:
String
: Represents a sequence of characters.Arrays
: Ordered collections of elements of the same or different data types.- Custom classes and objects: User-defined data types.
Example:
int age = 25;
double pi = 3.1415;
char grade = 'A';
boolean isJavaFun = true;
String greeting = "Hello, World!";
In Java, the equal operator (==
) compares the values stored in the memory. This can introduce a misleading result when comparing two reference datatypes, since it will compare the memory address, not the actual value that the variable is pointing to.
Following example compares memory usage between primitive data types and reference data types by creating and comparing a large number of objects:
public class MemoryUsageComparison {
public static void main(String[] args) {
int primitive1 = 42;
int primitive2 = 42;
String reference1 = new String("Hello");
String reference2 = new String("Hello");
// Check if primitive1 and primitive2 reference the same memory location
boolean primitiveEquality = (primitive1 == primitive2);
// Check if reference1 and reference2 reference the same memory location
boolean referenceEquality = (reference1 == reference2);
System.out.println("Primitive Equality: " + primitiveEquality);
System.out.println("Reference Equality: " + referenceEquality);
}
}
Basic Input and Output (I/O) using Scanner
You can use the Scanner
class to read input from the user. Here’s an example:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
scanner.close();
}
}
Pop Quiz
Quiz 1: What is the purpose of a variable in Java?
- To display output to the user.
- To store and manage data during program execution.
- To define a class in Java.
- To create loops and conditions in Java programs.
Quiz 2: Which data type is used to store decimal numbers in Java?
- int
- double
- boolean
- char
Quiz 3: What is the correct way to declare and initialize a variable named age
with the value 30
in Java?
- age = 30;
- int age = 30;
- 30 = age;
- age == 30;
Quiz 4: Which data type is used to store a single character in Java?
- int
- double
- boolean
- char
Quiz 5: What is the purpose of the Scanner
class in Java?
- To perform mathematical calculations.
- To create graphical user interfaces (GUIs).
- To read input from the user and display output.
- To define custom classes and objects.
Quiz 6: What is the result of the following Java expression?
int x = 5;
int y = 3;
int result = x / y;
- 2
- 1.67
- 1
- 1.0
Quiz 7: Which of the following is NOT a valid Java variable name?
- myVariable
- _variable
- 123variable
- variable123
Quiz 8: What is the data type of the result in the following Java expression?
double x = 5.0;
int y = 2;
double result = x / y;
- int
- double
- float
- String
Quiz 9: Which of the following is a valid way to convert an int
variable named num
to a double
in Java?
- double result = num;
- double result = (double) num;
- double result = num.toDouble();
- double result = Double.parse(num);
Answers:
- b
- b
- b
- d
- c
- c
- c
- b
- b
Exercise
Write a Java program that takes the user’s age as input and prints a message based on whether they are a minor or an adult.