In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice, it’s good to know a few basic principles:
Here is an example of the command:
System.out.println("Hello, World!");
The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.
If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:
System.out.println(1);
Command to display the number 1.
System.out.println(5 + 5);
A command in which two numbers are summed and their sum (10) is displayed.
As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".
public class HelloWorld {
public static void main(String[] args) {
//here we print the text out
System.out.println("Hello, World!");
}
}
We have a class called HelloWorld, a method called main(), and the command System.out.println("Hello, World!"). You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.
Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.
Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out
You can read the theory on this topic here, here, and here. But try practicing first!
Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.
The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.
System.out.println("I am a String");
System.out.println(5);
In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:
int a;
int b = 5;
String s = "Hello, World!";
Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5, declared a string called s and gave it the value Hello, World!
Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).
int a;
a = 5;
We created an integer variable named a with the first command and assigned it the value 5 with the second command.
Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:
public class HelloWorld {
public static void main(String[] args) {
int a;
int b = 5;
String s = “Hello, World!”;
a = 2;
System.out.println(a);
System.out.println(a + b);
System.out.println(s);
}
}
In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen
This program will display the following:
2
7
Hello, World!
We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:
Scanner scanner = new Scanner(System.in);
Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.
The following code reads a number from the console and prints it to the console:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Enter a number ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println(number);
}
}
Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.
This code will print the following output in case of user’s input is 5:
Enter a number
5
5
More information about the topic you could read here, here, and here.
See the exercises on Types and keyboard input to practice Java coding:
Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.
The syntax for an if statement is as follows:
if (condition1) {
// code to be executed if the condition is true
}...
if (conditionN) {
// code to be executed if the condition is true
} else {
// code to be executed if the conditions is false
}
Here could be one or more conditions in if and zero or one condition in else.
Here's a simple example:
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."
More information about the topic you could read here, here, and here.
Here are some Java practice exercises to understand Conditions and If statements:
In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:
boolean isJavaFun = true;
boolean isCodingEasy = false;
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Is coding easy? " + isCodingEasy);
The output of this program is here:
Is Java fun? true
Is coding easy? false
In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.
boolean isJavaFun = true;
boolean isCodingEasy = false;
// Using logical operators
boolean isBothFunAndEasy = isJavaFun && !isCodingEasy;
boolean isEitherFunOrEasy = isJavaFun || isCodingEasy;
System.out.println("Is it both fun and easy? " + isBothFunAndEasy);
System.out.println("Is it either fun or easy? " + isEitherFunOrEasy);
So the output of this program is:
Is it both fun and easy? true
Is it either fun or easy? true
More information about the topic you could read here, and here.
Here are some Java exercises to practice booleans:
With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:
Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.
1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.
Example:
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.
2. for Loop: The for loop is used for iterating a specific number of times.
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."
More information about the topic you could read here, here, and here.
Here are some Java coding challenges to practice the loops:
An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.
What you should know about arrays in Java:
Example:
// Declare and initialize an integer array of length 3
int[] myArray = new int[3];
// Assign values to array elements
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
// Access and print an element
System.out.println("Element at index 1: " + myArray[1]);
In this example, we create an integer array, assign values to its elements, and access an element using indexing.
More information about the topic you could read here, here, and here.
In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:
public static void methodName() {
// Method body with commands
}
Examples:
public class MethodExample {
public static void main(String[] args) {
// Call the customMethod
customMethod();
}
public static void customMethod() {
// This is our custom method
System.out.println("Hello from customMethod!");
}
}
In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.
public class Main {
public static void main(String[] args) {
int result = add(5, 3); // Calling the add method
System.out.println("The sum is: " + result);
}
public static int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
}
In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.
More information about the topic you could read here, here, and here.
All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:
Simple types are grouped into composite types, that are called classes. Example:
public class Person
{
String name;
int age;
}
We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.
More information about the topic you could read here, here, and here.
See the exercises for a coding practice in Java data types:
String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.
String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.
Example of comparing strings using the equals() method.
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
Also you can check if a string contains a substring using the contains() method.
String text = "This is a sample text.";
String search = "sample";
if (text.contains(search)) {
System.out.println("Substring found.");
} else {
System.out.println("Substring not found.");
}
You can create a new substring from an existing string using the substring() method.
String text = "Hello, World!";
String subText = text.substring(7);
System.out.println(subText); // Output: "World!"
More information about the topic you could read here, here, here, here, and here.
Here are some Java programming exercises to practice the strings:
In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:
First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:
ClassName objectName = new ClassName();
It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:
Person john = new Person("Jane", 25);
Example:
Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:
// Step 1: Define the Person class
class Person {
String name; // Property
// Method to say hello
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
public class Main {
public static void main(String[] args) {
// Step 2: Create an object of the Person class
Person person1 = new Person();
// Set the name property
person1.name = "Johnny";
// Call the sayHello method
person1.sayHello(); // Output: "Hello, my name is Johnny"
// Create another object
Person person2 = new Person();
person2.name = "Ivy";
person2.sayHello(); // Output: "Hello, my name is Ivy"
}
}
In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.
More information about the topic you could read here, here, and here.
Here are some coding challenges in Java object creation:
Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.
Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.
You declare them with the static modifier.
Static Methods
A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.
public class Calculator {
public static int add(int num1, int num2) {
return num1 + num2;
}
}
public class Main {
public static void main(String[] args) {
int result = Calculator.add(5, 3);
System.out.println("Result: " + result); // Output: Result: 8
}
}
In this example, the add method is static. You can directly call it using Calculator.add(5, 3)
Static Classes
In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.
public class School {
static class Student {
String name;
Student(String name) {
this.name = name;
}
}
}
public class Main {
public static void main(String[] args) {
School.Student student1 = new School.Student("Johnny");
School.Student student2 = new School.Student("Ivy");
System.out.println("Student 1: " + student1.name); // Output: Student 1: Johnny
System.out.println("Student 2: " + student2.name); // Output: Student 2: Ivy
}
}
In this example, Student is a static nested class within the School class. You can access it using School.Student.
More information about the topic you could read here, here, here, and here.
See below the exercises on Static classes and methods in our Java coding practice for beginners: