Conditional Operators

Conditional Operator is another way of writing the if-else statement. It helps to simplifies the if-else statement and is compact . However, the conditional operator can only be used if there are 2 options which are either true or false. The format to code the conditional operators is shown below:

Condition ? expression1: expression2;

Example
marks > 50 ? “You passed the paper”: “You failed the paper”;

Condition – The conditions will give a Boolean expression
Expression1 – if the conditional is true, then expression1 will be executed.
Expression2 – if the conditional is false, then expression2 will be executed.
Expression1 and Expression2 must have the same data type.

The code snippet below shows how the conditional operator have been coded out:

conditionalStatements
Program with Conditional Statement

Constructors

In the earlier post of Methods and Parameters, we talked about how constructors works for default constructor. Now in this post we are also going to talk about constructor but is a parameter-ised  constructor. Parameter-ised constructor are a constructor with parameter. Therefore, constructor must have the same name as the class, do not have a return type and must pass in a parameter as soon as an the object is created in order for that method to be executed.

The snippets of code below are similar to Methods and Instances snippets but we coded the constructor out with an argument.

First, the class with methods that the main class will use:

constructorSubClass
Class with constructors and other methods

Next, the main class where it will call the other class’s methods:

constructorMainClass.JPG
Main Class where the object was created & pass in the value as an argument.

Since the object pass in an argument, we need to create a constructor that take in the given value from the main class to its class and process the method. Then the class object calls the class method ‘saying()’ where the saying method will give the final output after the execution of ‘getcolor()’ method gets the instance variable value.

Note: We can create multiple class object of the same class but rename the object differently with different variable as its parameter to access the multiple object.

Methods and Instances

First we are going to create a class with methods and instances first before calling the main class method. Take a look at the class with methods and instances below:

mthodsNInstances
Subclass where all the methods and Instances are declared.

Now let me explain the codes:

  1. private String colorName –> From the line we know that we set the variable to private. Why we set the variable to be private? We want the methods inside the class where the variable is declared to access the variable and prevent the other classes from using that variable. We call this declaration as instance variable with private access. If you want the other classes to use the variable you can set it to public.
  2. public void setcolor(String color) –> This line of code is for creating a method that doesn’t return anything but takes in an argument of a string variable. This method is where we assign the argument that was passed in to the private variable that we talked about earlier.
  3. public String getcolor() –> Since we  setcolor ,we need a getcolor to get the colorName by returning a String variable colorName which is an instances variable with private access.
  4. public void saying() –> this method will be used to output the result. In this method we can call other methods to like “getcolor()” to give the color name information.
    NOTE: We print the string by using the printf method format where we can format the string.

    1. %s – for string
    2. %f– for float
    3. %d – for decimal
    4. %n – for newline.

      The format are to be with the hard corded strings follow by a comma and the variable name or method as can be seen from the above snippet of codes.

The main class have the similar codes as the “Methods and Parameters” section but we need to use call 2 method instead of 1 as shown in the snippet below.

mthodsNInstancesMainCLass
Main class calling the setcolor and saying method.

Since the user input need to be stored in the colorName variable which is set to private on another class. The main class need to call the setColor() method from subClass and pass the input to the method. Then only the user input will get stored to the private variable.

After setting the color, the main class will call the saying method from another class to print the final output.

 

Methods and Parameters

Now, we are going to learn on how to call a method from another class that requires a input from the main class and pass into the method as an argument.

First, we create a class with a method that need an argument of String name. The code below shows how to create a method with an argument.

MethodNParameterSubClass
Class with a method that need an argument of String name.

This means that the method(e.g main method) which is calling this method MUST provide a String type name in order for the compiler to access the method.

NOTE: We did not declare a constructor. You may ask what is a constructor? Constructor are a special kind of method that is used to declare in class. Constructor must have the same name as the class and it does not have a return type. In this case, we do not code the Constructor out since it is a default Constructor with no argument. The compiler can automatically create the constructor as a default. For more information: Javatpoint-Constructor

In the main method, we need to create an object for the class so that it will be invoked and call the method from the class. It is same as the previous section but when you call the method in the main method you have to pass in the variable.

<class that wish to use> <variable name> = new  <class that you want to use>
<classVariableName>.<methodName>(<pass in the variable>);

Example:
firstClassCreated class1 = new firstClassCreated();
class1.simpleMessage(name);

Creating a Class

Now we are going to create a class and call the class in the main method. As mentioned previously Java will first execute the commands inside the main methods.

First, create a class file by right clicking on the package and selecting new > class. Name your class anything that you like but something meaningful. In that class, we can create as many methods as you like. The figure below is an example that I have explained.

firstClassCreated
Class Created with a method named simpleMessage.

void – are used in the method when it is not needed to return any values.

Now, we need to call this ‘firstClassCreated’ class to the main method. First, we need to create a object for this class in the following format:

<class that wish to use> <variable name> = new  <class that you want to use>

Example:
firstClassCreated class1 = new firstClassCreated();

After creating the object for the class, we can call the method from the class now in this following format:

<classVariableName>.<methodName>();

Example:
class1.simpleMessage();

The snippet below is the Main class file that is used to call the other class.

mainClass1
Main class file that is used to call the other class

Question: Why do we need to create other class file? Why can’t we just code everything in the main method?

Yes, you can code everything in the Main method. However, if your program changes due to client requirements then it would be difficult for the programmers to make the changes. It would be difficult to make the changes because the code is too long and if the progrmmer change one thing it would affect the whole program. That is why it is good to use multiple classes to break the program down and if the program requirement changes the coder can easily make the changes without any difficulties.

While Loop

While loop are used to allow a block of code or the program to run a certain number of time. While loop are coded once but run a number of times. For while loop we use a conditional statement as long as the conditional statement is true that block of code will execute but if the statement is false it will exit the while loop. To exit, from the while loop we use a pre-increment counter.

Below is the snippet of the code on how the while loop will be executed:

whileLoop
Code for while loop with comments.

Switch Statement

Switch statement are like if-else statement which uses equal to operator (==) in each conditional statement. We use switch statements to test the variable out with multiple choices.

The code below is how the syntax of the switch statement will look like:

// we are gonna test the variableName against some choices
switch(variableName){

case 1:
// read case 1 as if the variableName is equal to 1. The case replace the if statement.
System.out.println(“The variableName is 1”);
break; // if the case is true it will break out of the switch statement.

default:
// is like the else statement. If none of the given cases is true then the default block of code will be executed.
System.out.println(“The variableName is unknown”);
break;

}

Below is the snippet of the code:

switchStatement
Code for switch statement to check integers with comments.

Logical Operator

Logical operator are used to check multiple conditions in a given conditional statement rather than using nested if-else statement. To check multiple conditions in a conditional statement you must either use “&&”(And) or “||”(or) in between a pair of conditions.

For “&&” every statement must be true so that the whole statement will be true and the block of code will be executed. For “||” at least one condition must be true for the statement to be true and the block of code will be executed.

logicalStatement
Example of logical operator. In this case both if statement will be executed with comments.

Conditional Statements

In Java, we utilize conditional statements to execute certain block of codes if the conditional statement is true it will execute that block of code or else it will either execute another conditional statement or execute the statement outside the conditional statements.

From the above paragraph already I gave you the answer of the type of conditional statement that we are going to use.  That’s right we are going to use the “if-else statement”. “If-else statement” help the program to make certain decision and execute the block of code if the decision is correct. Let me now explain how the program reads your if-else statement.

if (conditional statement is true){

//Execute this block of code.

} else if( 2nd conditional statement is true){

/* if the 1st conditional statement is false, the program will go the next conditional statement to check if it is true. If it is the program will execute this block of code. */
}

else{
// else execute this block of code if the above 2 conditional statement are false.

}

When using conditional statements you need to make use of the comparison operators like “==” (equals to), “<” (lesser than), “>”(greater than), “<=” (lesser than or equals to), “>=”(greater than or equals to), “!=”(not equals to).

The image below is a snippet of a simple code:

ifStatement1
Code for if-else statement to check integers with comments.

Integer is  a primitive data type means it has a special characteristics about the kind of data it handles and it is easy to manipulate data. Since, it is primitive we can make use of “==” to check is the 6 is equal to the data inside the variable. There are primitive data too which are boolean, float, double, short, char and bytes.

How about strings??? Strings are non-primitive data type and also known as object data types.  Therefore, it has its own method to check if the variable is equal to the value or not. For example: if(gender.equals(“female”)) or gender.equalsIgnoreCase(“female”).  “equals” and “equalsIgnoreCase” is a method of string.  For more info: Link.

The image below is a snippet of a simple code:

ifStatement2
Code for if-else statement to check Strings with comments.