Tag Archives: Java

Switch Statement in Java

A switch statement tests a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax:

switch (expression) {
 case value1 :
 //Statements
 break; //optional
 case value2 :
 //Statements
 break; //optional
 //You can have any number of case statements.
 default : //Optional
 //Statements
}

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 after 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.

The example below tests month against a set of values and prints a corresponding message.

int month = 4;

switch(month) {
 case 1:
 System.out.println("January");
 break;
 case 2:
 System.out.println("February");
 break;
 case 3:
 System.out.println("March");
 break;
case 4:
 System.out.println("April");
 break;
}
// Output April

You can have any number of case statements within a switch. Each case is followed by the comparison value and a colon.A switch statement can have an optional default case. The default case can be used for performing a task when none of the cases is matched.

For example:

int month = 3;

switch(month) {
 case 6:
 System.out.println("June");
 break;
 case 7:
 System.out.println("July");
 break;
  default:
 System.out.println("Error");
}
// Outputs "Error"

No break is needed in the default case, as it is always the last statement in the switch.

Java Logical Operators

Logical operators are used to combine multiple conditions.
Let’s say you wanted your program to output “Welcome to HelloTech!” only when the variable num is greater than 20 and the variable salary is greater than 5000.
One way to accomplish this is to use nested if statements:

if (num > 20) {
 if (salary > 5000) {
 System.out.println("Welcome to HelloTech!");
 }
}

The AND (&&) Operator:

The AND operator (&&) checks if both operands of the AND operator are true, then the condition becomes true.The condition becomes false, if any one of the operands evaluates to false.
However,We can solve above problem using the AND logical operator (&&) in a better way:

if (num > 20 && salary > 5000) {
 System.out.println("Welcome to HelloTech!");
}

The OR (||) Operator:

The OR operator (||) checks if any one of the conditions is true. The condition becomes true, if any one of the operands evaluates to true.
For example:

int num = 25;
int salary = 1200;

if (num > 20 || money > 5000) {
 System.out.println("Welcome to HelloTech!");
}
//Outputs "Welcome to HelloTech!"

The code above will print “Welcome to HelloTech!” if num is greater than 20 or if salary is greater than 5000.

The NOT (!) Operator:

The NOT (!) logical operator is used to reverse the logical state of its operand. If a condition is true, the NOT logical operator will make it false.
Example:
int salary = 2500;
if(!(salary > 2000)) {
 System.out.println("Your salary is not greater than 2000");
} else {
 System.out.println("Welcome to HelloTech");
}
//Outputs "Welcome to HelloTech"

!(salary > 2000) reads as “if salary is NOT greater than 2000”.

Conditional Statement in Java|set 2

Nested if Statements:

You can use one if-else statement inside another if or else statement.
For example:

int age = 36;
if(age > 1) {
 if(age > 20) {
 System.out.println("Welcome to HelloTech!");
 } else {
 System.out.println("You are too Young");
 }
} else {
 System.out.println("Error");
}
//Outputs "Welcome to HelloTech!"

You can nest as many if-else statements as you want.

else if Statements:

Instead of using nested if-else statements, you can use the else if statement to check multiple conditions.
For example:

int age = 25;
if(age <= 5)
 {
 System.out.println("Error");
} 
else if(age <= 15) 
{
 System.out.println("Too Young");
} 
else if(age < 100) 
{
 System.out.println("Welcome to HelloTech!");
} 
else 
{
 System.out.println("Really?");
}
//Output: "Welcome to HelloTech!"

The code will check the condition to evaluate to true and execute the statements inside that block.You can include as many else if statements as you need.

Conditional Statement in Java|set 1

Conditional statements are used to perform different actions based on different conditions.

 If Statement:

The if statement is one of the most frequently used conditional statements.If the if statement’s condition expression evaluates to true, the block of code inside the if statement is executed. If the expression is found to be false, the first set of code after the end of the if statement (after the closing curly brace) is executed.
Syntax:

if (condition) {
//Executes when the condition is true
}

Any of the following comparison operators may be used to form the condition:
< less than
> greater than
!= not equal to
== equal to
<= less than or equal to
>= greater than or equal to

For example:

int x = 10;
if(x > 5) {
 System.out.println("Hi Rashmi");
}

Remember  two equal signs (==) to test for equality.

if…else Statements:

An if statement can be followed by an optional else statement, which executes when the condition evaluates to false.
For example:
int age = 25;

if (age < 16) {
 System.out.println("Too Young");
} else { 
 System.out.println("You are Young!");
}
//Outputs You are Young!

As age equals 25, the condition in the if statement evaluates to false and the else statement is executed.

Getting User Input in Java

While Java provides many different methods for getting user input, the Scanner object is the most common, and perhaps the easiest to implement. Import the Scanner class to use the Scanner object, as seen here:

import java.util.Scanner; 

In order to use the Scanner class, create an instance of the class by using the following syntax:

Scanner input = new Scanner(System.in);

You can now read in different kinds of input data that the user enters.
Here are some methods that are available through the Scanner class:

1. Read a byte – nextByte()
2. Read a short – nextShort()
3. Read an int – nextInt()
4. Read a long – nextLong()
5. Read a float – nextFloat()
6. Read a double – nextDouble()
7. Read a boolean – nextBoolean()
8. Read a complete line – nextLine()
9. Read a word – next()

Example of a program used to get user input:

 

import java.util.Scanner;

public class UserInputDemo {
  public static void main(String[ ] args) {
  Scanner input = new Scanner(System.in);
  int age=sc.nextInt();
  double salary=sc.nextDouble()
  System.out.println("Age is:"+age); 
  System.out.println("Salary is:"+salary);
}
}

 

Java Strings

A String is an object that represents a sequence of characters.
For example, “HelloWorld” is a string of 10 characters.
For example:

String s = "HelloTech";

The + (plus) operator between strings adds them together to make a new string. This process is called concatenation.The resulted string is the first string put together with the second string.For example:

String firstName, lastName;
firstName = "sani";
lastName = "kamal";
System.out.println("My name is " + firstName +" "+lastName);
 
// Prints: My name is sani kamal
The char data type represents a single character.

Java Assignment Operators

You are already familiar with the assignment operator (=), which assigns a value to a variable.

 int x = 12;

This assigned the value 12 to a variable called x of type int.
Java provides a number of assignment operators to make it easier to write code.
Addition and assignment (+=):

int a = 5;
int b = 25;
b += a; // b = b + a;
// b is 30 and a is 5
Subtraction and assignment (-=):
int a = 5;
int b = 20;
b -= a; // b = b - a;

// b is 15 and a is 5
Multiplication and assignment (*=):
int a = 5;
int b = 20;
b *= a; // b = b * a;

// b is 100 and a is 5
Division and assignment (/=):
int a = 5;
int b = 20;
b /= a; // b = b / a;

// b is 4 and a is 5
Remainder and assignment (%=):
int a = 4;
int b = 27;
b %= a; // b = b % a;

// b is 3 and a is 4

Java increment and decrement operator

An increment or decrement operator provides a more convenient and compact way to increase or decrease the value of a variable by one.
For instance, the statement x=x+1; can be simplified to ++x
Example:

int x =10;
++x; // x is now 11

The decrement operator (–) is used to decrease the value of a variable by one.

For instance, the statement x=x-1; can be simplified to –x

int x = 10;
--x; // x is now 9

Prefix and Postfix

Two forms, prefix and postfix, may be used with both the increment and decrement operators.With prefix form, the operator appears before the operand, while in postfix form, the operator appears after the operand. Below is an explanation of how the two forms work:
Prefix: Increments the variable’s value and uses the new value in the expression.
Example: 

int x = 3;
int y = ++x; // y is 4

The value of x is first incremented to 4, and is then assigned to y, so the values of both x and y are now 4. 

Postfix: The variable’s value is first used in the expression and is then increased.
Example:

int x = 3;
int y = x++; // y is 3

x is first assigned to y, and is then incremented by one. Therefore, x becomes 4, while y is assigned the value of 3.

The same applies to the decrement operator. 

Example:
//pre decrement
int x = 10;
int y = --x; // y is 9

The value of x is first decremented to 9, and is then assigned to y, so the values of both x and y are now 9.

//post decrement
int x = 10;
int y = x--; // y is 10

x is first assigned to y, and is then decremented by one. Therefore, x becomes 9, while y is assigned the value of 10.

Java Math Operators

Java provides a rich set of operators to use in manipulating variables. A value used on either side of an operator is called an operand.
For example, in the expression below, the numbers 5 and 8 are operands of the plus operator:

 int a = 5 + 8;

Java arithmetic operators:

1.   + addition
2.   – subtraction
3.   * multiplication
4.    / division
5.   % modulo

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebraic equations.

Addition:

The + operator adds together two values, such as two constants, a constant and a variable, or a variable and a variable. Here are a few examples of addition:

int a = 40 + 10; 
int b = a + 34; 
int c = a + b;

Subtraction:

The – operator subtracts one value from another.

int a = 100 - 15;
int b = a - 5;
int c = a - b;

Multiplication:

The * operator multiplies two values.
int a = 100 * 6;
int b = a * 3;
int c = b * c;

Division:

The / operator divides one value by another.

int x = 500 / 5;
int y = x / 4;
int z = x/ y;

In the example above, the result of the division equation will be a whole number, as int is used as the data type. You can use double to retrieve a value with a decimal point.

Modulo:

The modulo (or remainder) math operation performs an integer division of one value by another, and returns the remainder of that division.
The operator for the modulo operation is the percentage (%) character.
Example:

int value = 36;
int result = value % 5; // result is 1

Dividing 36 by 5 returns a quotient of 7, with a remainder of 1. Thus, the value of 1 is assigned to the result variable.

Java variables

Variables store data for processing.A variable is given a name (or identifier), such as name, age, height, and the like. The name uniquely identifies each variable, assigning a value to the variable and retrieving the value stored.Variables have types.

For examples:

  1. int: for integers (whole numbers) such as 224 and -456002

2. double: for floating-point or real numbers with optional decimal points and fractional parts in fixed or scientific notations, such as 3.1416, -73.66,3.12e10.

3.String: for texts such as “Hello” or “Good Evening!”. Text strings are enclosed within double quotes.
You can declare a variable of a type and assign it a value.
Example:
String name = "sani kamal";
int age=25;
double interest=45.98;
This creates three variables called name of type String, age of type integer and interest of type double and assigns value “sani kamal”,25,45.98 respectively.
It is important to note that a variable is associated with a type, and is only capable of storing values of that particular type. For example, an int variable can store integer values, such as 445; but it cannot store real numbers, such as 19.34, or texts, such as “Hello Rashmi”.
Examples of variable declarations:
class DemoClass {
 public static void main(String[ ] args) {
 String name ="sani kamal";
 int age = 25;
 double score =55.9;
 char group = 'A';
 }
}

char stands for character and holds a single character.
Another type is the Boolean type, which has only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
For example:

 boolean isOpen = true;
You can use a comma-separated list to declare more than one variable of the specified type. Example:
 String a = "Hello John ", b = "India";