Java While Loop

When we want to execute a block of code again and again until a condition remains true we can use loops in java.
There are four types of loops in java

Java while loop

Java while loop executes the code block until the loop condition remains true.

Syntax


while(condition){
// statements of code to be executed.
}

Example:

Following is an example of loop. It will will execute the statement again and again until the value of index remains less than ten.


int index = 1;
while (index < 10) {
System.out.println("Value of index is :"+index);
index++;
}

Important: Loop will never terminate if variable used in condition remains constant. Therefore it should be incremented / decremented according to situation.

Java Switch Statement

Java switch statement is used to execute one or multiple blocks of code based on equality of a variable or output of an expression to a list of values. Each value in the list is called a case and variable or output of expression is compared to each case.

Syntax of Java Switch Statement

Following is syntax of java switch statement:

switch(expression){
case value1:
//// some statements
break;
case value2:
//// some other statements
break;
case value3:
case value4:
case value5:
//////// statements for multiple cases.
break;
default:
///// statements to run of no case matches from above cases.
}

Rules for Java Switch Statement

Following are rules for switch statement:

  • Variable used in a switch statement can only be of primitive data type ( integer, short, char, byte) strings or enums.
  • There may be any number of cases within a switch statement. In each case the keyword case is followed by the value to be compared to and a colon(:).
  • The variable in the switch and value for a case must be of same data type.
  • When the variable and case value match the statements after the case are executed until a break statement is encountered.
  • The switch terminates at break statement and controls goes to next statement right after switch statement.
  • break statement is not mandatory. If there is no break statement in a case then next all cases are executed until break is reached.
  • At the end of switch statement there may be an optional default statement.
  • The default statement will be executed if no other case has been matched.

Example


public class JavaSwitchTest {
public static void main(String args[]) {
char grad = 'B';
switch(grad) {
case 'A' :
System.out.println("Great!");
break;
case 'B' :
case 'C' :
System.out.println("Good");
break;
case 'D' :
System.out.println("Statisfactory");
case 'F' :
System.out.println("Try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grad);
}
}

Java if else statement

General mathematical logic based conditions are supported in java e.g.

  • Equal to: x == y (will be true of both x and y are equal other wise false)
  • Less than x < y ( we be true of x is less than y)
  • Less than or equal to: x <= y (will be true if x is less y or both have hold same value)
  • Greater than: x > y (will be true if x holds a value greater than that of y)
  • Greater than or equal to: x >= y (will be true if x holds a value greater than y or both hold same value)
  • Not equal to: x != y (will be true if x and y hold different values)

These conditions are used in java to perform decisions for different actions
Java supports if, ifelse, ifelseif and switch to control flow of execution of a program based on above conditions:

Note: if, else and switch are in lower case and upper case letters will generate error because java is a case sensitive language.

Java if statement

Java code in if statement is executed when the condition is true

Syntax for if statement

if ( condition) {
// java code placed here will be executed if condition is true
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}

Java if-else statement

Java code in if statement is executed when the condtion is true. Otherwise code in else block will be executed.

Syntax for if-else statement

if ( condition) {
// java code placed here will be executed if condition is true
} else
{
//Java code placed here will be executed if condition is false.
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}else
{
System.out.println("value in variable x is not greater than that of y, may be equal!");
}

Java if-else-if statement

We can test a new condition instead of execution of else block.

Syntax for if-else-if statement

if ( condition) {
// java code placed here will be executed if condition is true
} else if(condition2){
//Java code placed here will be executed if condition2 is true.
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}else if(x == y)
{
System.out.println("value in variable x is equal to the value in y");
}else{
System.out.println("value in variable x is greater than the value in y");
}

Java Booleans

In some cases we need a variable to store only two possible values, either false or true. For this, boolean data type is used in java. The variable declared as boolean can take either true or false as value.

Boolean Variable in java
Boolean variable is declared using boolean keyword and can take true or false value.


public class JavaBooleanExample {
public static void main(String[] args) {
int age1=30;
int age2=40;
boolean elder=true;
boolean younger=false;
if(age1<age2)
{
System.out.println(elder);
}
else
{
System.out.println(younger);
}
}
}

Java Boolean Expressions

An expression involves multiple variables and some arithmetic and logical operators and function calls. Final result of a boolean expression will be true or false

Following is an example of a boolean expression:


int a = 20;
int b = 30;
int c = 300;
if( (a+b)<c)
{
System.print.ln("Sum of a and b is less than value in c");
}

How to Remove / Hide Page or Post Title in WordPress

Title of wordpress post can be removed using the_title filter for a category, single post or page or all pages / posts. Following code will remove title of posts in wordpress category. Place the code to the end of functions.php file of active theme of your website.


function remove_title_of_category( $title, $id = null ) {
if( is_single() ) {  /* this will remove title of post/page on single page and not from list of posts */
if ( in_category('wordpress', $id ) ) {
return false;
}
}
return $title;
}
add_filter( 'the_title', 'remove_title_of_category', 10, 2 );

Hide / Remove post title using CSS

We can hide post title using display property of element which contains the title of page.

  1.  Visit a page / post using Chrome or you favorite web browser.
  2. Right Click on its heading / title text.
  3. Click on inspect.
  4. You will see HTML source of title / heading element.
  5. There will be an attribute class for this element. Note down its value e.g. entry-title
  6. Login into admin dashboard of you site.
  7. Go to Appearance->Theme Editor.
  8. Select the file style.css from files list given on right side bar
  9. Go to end of style.css and place following code at the end:


.entry-title{
display:none !important;
}

Java Strings

Strings are used to store text.
A String variable in java contains a sequence of characters surrounded by double quotes:

String str = "A test String";

Strings are treated as objects in Java. The Java platform provides the String class to create and manipulate strings. Whenever a string literal is encountered in your code, the compiler itself creates a String object with its value in this case, “A test String” .Like other object, we can create String objects by using the new keyword and a constructor. Java String class has 11 constructors that allow you to initialize the newly created string object using different sources e.g. an array of characters.

Java String Methods

The Java String class has a number of methods which can be used to manipulate strings:

Method Description Return Type
charAt() Returns the character at the specified index (position) char
codePointAt() Returns the Unicode of the character at the specified index int
codePointBefore() Returns the Unicode of the character before the specified index int
codePointCount() Returns the Unicode in the specified text range of this String int
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of characters boolean
contentEquals() Checks whether a string contains the exact same sequence of characters
of the specified CharSequence or StringBuffer
boolean
copyValueOf() Returns a String that represents the characters of the character array String
endsWith() Checks whether a string ends with the specified character(s) boolean
equals() Compares two strings. Returns true if the strings are equal, and false
if not
boolean
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
format() Returns a formatted string using the specified locale, format string, and arguments String
getBytes() Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array byte[]
getChars() Copies characters from a string to an array of chars void
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found occurrence of specified characters in a string int
intern() Returns the canonical representation for the string object String
isEmpty() Checks whether a string is empty or not boolean
lastIndexOf() Returns the position of the last found occurrence of specified characters in a string int
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular expression, and returns the matches boolean
offsetByCodePoints() Returns the index within this String that is offset from the given index by codePointOffset code points int
regionMatches() Tests if two string regions are equal boolean
replace() Searches a string for a specified value, and returns a new string where the specified values are replaced String
replaceFirst() Replaces the first occurrence of a substring that matches the given regular expression with the given replacement String
replaceAll() Replaces each substring of this string that matches the given regular expression with the given replacement String
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified characters boolean
subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence
substring() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character String
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the specified value String

Java Operators

Java operators are symbols which are used to perform operations. For example addition, subtraction, division, multiplication, remainder etc. We can divide the Java operators into the following groups

Unary Operator
Arithmetic Operator
Shift Operator
Relational Operator
Bitwise Operator
Logical Operator
Ternary Operator
Assignment Operator

Java Unary Operators

The Java unary operators needs only one operand. Unary operators are used to perform many operations e.g.
Increment /decrement a number
negating an expression
inverting the value of a boolean

Java Unary Operator Increment (++) / Decrement (–) Example


class OperatorIncrementDecrementExample{
public static void main(String args[]){
int x=50;
System.out.println(x++);//Now value in x is 51
System.out.println(++x);//52
System.out.println(x--);//51
System.out.println(--x);//50
}}

Java Arithmetic Operators

To perform addition, subtraction, multiplication, and division java arithmetic operators are used. They work as basic mathematical operators.

Java Arithmetic Operators Example:


class OperatorArithmeticExample{
public static void main(String args[]){
int a1=100;
int b1=50;
System.out.println(a1+b1);//150
System.out.println(a1-b1);//50
System.out.println(a1*b1);//5000
System.out.println(a1/b1);//2
System.out.println(a1%b1);//0
}}

Java Shift Operators

There are two shift operators in java i.e. left shift operator and right shift operator

Java left shift operator

‘<<‘ is used as left shift operator in java to shift all of the bits in a value to the left side of a specified number of times.
Examples:

class JavaLeftShiftExample{
public static void main(String args[]){
System.out.println(10<<1);//10*2^1=10*2=20 (i.e. shift left by 21)
System.out.println(10<<3);//10*2^3=10*8=80 (i.e. shift left by 23)
}
}

Java Right Shift Operator

‘>>’ is used as right shift operator to move left operands value to right by the number of bits specified by the right operand.
Example:

class RightShiftExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2 (i.e shift right by 22)
System.out.println(40>>3);//40/2^3=40/8=5 (i.e. shift right by 23)
}
}

Java Type Casting

Java type casting is a way in java that converts a data type into another data type manually or automatically. Manual conversion performed by the programmer and automatic conversion is done by the compiler. In this section, we will describe java type casting.

Types of Java Type Casting

Java type casting is of two types:

Narrowing Type Casting
Widening Type Casting

Narrow Type Casting

Conversion of a larger data type into a smaller one is called narrow type casting. It is also known as explicit conversion or casting down. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Let’s see an example of narrow type casting.
MyNarrowTypeCasting.java

public class MyNarrowTypeCasting
{
public static void main(String args[])
{
double d = 203.541;
long l = (long)d; //converting double data type into long data type

int i = (int)l; //converting long data type into int data type
System.out.println("Before conversion from double to int: "+d);
//fractional part will be lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}

In the above example, we have performed the down/narrow java type casting two times. First, we have converted the double type into long data type after that long data type is converted into int type.

Widening Type Casting

Conversion from a lower data type into a higher data type is called widening type casting. It is also called implicit conversion or up casting. It is done automatically. It is safe because there is no chance to lose data. It takes place when:
Both data types must be compatible with each other.
The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between char data type to numeric or Boolean data is not done automatically because the char and Boolean data types are not compatible with each other. Let’s see an example.
MyWideningTypeCasting.java

public class MyWideningTypeCasting
{
public static void main(String[] args)
{
int a = 5;
//automatically converts the integer type into long type
long b = a;
//automatically converts the long type into float type
float c = b;
System.out.println("Before conversion, int value "+a);
System.out.println("After conversion, long value "+b);
System.out.println("After conversion, float value "+c);
}
}

Java data types

Data type specifies the type of data a variable will hold e.g. whole number, number with fractions, text. Following are example of variables declaration with java data types:

int myNumber = 5; // an Integer or whole number
float myFloatintPointNumber = 86625.111554; // Floating point number
char myLetter = 'D'; // Single charater
boolean myBoolean = true; // a true/ false value
String myText = "Hello"; // String / text value

Types of Data types in java

There are two types of data types in java:

1. Primitive data types

Primitive data types are the basic types of data types. These are used as basic building blocks for data manipulation. Following table shows the primitive data types and their size in java:

Data Type Size
boolean 1 bit
char 2 byte
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte

2. Non primitive data types

Non primitive data types are complex data types. Variables of non-primitive datatypes are composed of primitive data types. Classes, interfaces are arrays are examples of non-primitive data types.

Java Final Variables

In some cases we need to user variable as “constant” and do not want to change its value after initialization. We use final keyword for this purpose. following example shows declaration and initialization of a final variable.

final name = "John";

Now compiler will show a compile time error if we try to assign some other value in variable name because it has been declared as final