VARIOUS TOPICS IN JAVA

Prosper
8 min readAug 2, 2021

--

Firstly, the definition of java

THINGS TO NOTE ABOUT JAVA

Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: “MyClass” and “myclass” has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class name and add “.java” to the end of the filename. To run the example above on your computer, make sure that Java is properly installed: Go to the Get Started Chapter for how to install Java. The output should be:

hello world

The main Method

The main() method is required and you will see it in every Java program:

public static void main(String[] args

Any code inside the main() method will be executed. You don't have to understand the keywords before and after main. You will get to know them bit by bit while reading this tutorial.

For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.

System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen:

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

Java Data Types

  1. Byte: Stores whole numbers from -128 to 127
  2. Short: Stores whole numbers from -32,768 to 32,767
  3. Int: Stores whole numbers from -2,147,483,648 to 2,147,483,647
  4. Long: Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  5. Float: Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
  6. Double: Stores fractional numbers. Sufficient for storing 15 decimal digits
  7. Boolean: Stores fractional numbers. Sufficient for storing 15 decimal digits
  8. Char: Stores a single character/letter or ASCII values
  9. String: Stores words

Java Operators

  1. + : adds values
  2. - : removes values
  3. * : multiplies values
  4. / : divides values
  5. % : Returns the division remainder
  6. ++ : Increases the value of a variable by 1
  7. — — : Decreases the value of a variable by 1

Java Switch

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

HOW DOES JAVA SWITCH WORK/RULES

  • The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  • The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default ca

Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {
// code block to be executed
}

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
// code block to be executed
}
while (condition)

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax

for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Java Break

The break statement can also be used to jump out of a loop.

Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type with square brackets:\

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal — place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Java Methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.

WHY METHODS?

  1. To define the code once
  2. To use it many times

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:

Syntax

public class Main {
static void prosper(){
// code to be executed
}
}

Example Explained

  • prosper() is the name of the method
  • static means that the method belongs to the Main class and not an object of the Main class.
  • void means that this method does not have a return value. You have the option to remove this so as to return a value.

Call a Method

To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Java OOP

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Tip: The “Don’t Repeat Yourself” (DRY) principle is a useful tip on OOP about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.

Java Classes/Objects

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a “blueprint” for creating objects.

Create a Class

To create a class, use the keyword class:

Main.java

Create a class named “Main" with a variable x:

public class Main {
int x = 5;
}

Create an Object

In Java, an object is created from a class. We have already created the class named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name, and use the keyword new:

Example

Create an object called “myObj" and print the value of x:

public class Main {
int x = 5;

public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}

Java Constructors

A Java constructor is special method that is called when an object is instantiated. In other words, when you use the new keyword. The purpose of a Java constructor is to initializes the newly created object before it is used. … Typically, the constructor initializes the fields of the object that need initialization.

Example

// Create a Main class
public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5

Java Modifiers

The public keyword(which you are quite familiar with) is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.

We divide modifiers into two groups:

  • Access Modifiers — controls the access level
  • Non-Access Modifiers — do not control access level, but provides other functionality

Access Modifiers

For classes, you can use either public or default:

  1. Public :The class is accessible by any other class
  2. Default :The class is only accessible by classes in the same package. This is used when you don’t specify a modifier.

For attributes, methods and constructors including public, you can use the one of the following:

  1. Public :The class is accessible by any other class
  2. Private: The code is only accessible within the declared class
  3. Protected: The code is accessible in the same package and subclasses.

Non-Access Modifiers

For classes, you can use either final or abstract:

  1. Final: The class cannot be inherited by other classes.
  2. Abstract :The class cannot be used to create objects (To access an abstract class, it must be inherited from another class. )

For attributes and methods, you can use the one of the following:

  1. Final: Attributes and methods cannot be overridden/modified
  2. Static: Attributes and methods belongs to the class, rather than an object
  3. Abstract: Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from).
  4. Transient: Attributes and methods are skipped when serializing the object containing them
  5. Synchronized: Methods can only be accessed by one thread at a time
  6. Volatile: The value of an attribute is not cached thread-locally, and is always read from the “main memory”

Java Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

It is possible to access final method data if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

Example

public class Person {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

Note: The variable must be declared public. However, as we try to access a private variable, we get an error.

Here is recommended video on the rest of the java topics

--

--

No responses yet