web analytics

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

Java Variables

Java variables are containers which hold values during execution of java program. These are names of a memory locations where values are temporarily saved.
A variable can hold:
simple text called String
Single character represented as char
a whole number called integer and represented by int
a number with fraction such as 2.65 called floating point numbers and represent as float
values with two states: true or false represented as boolean

How to create or Declare a variable

To use a variable in java we first need to declare it. To declare a variable first of all data type of variable is mentioned e.g. int, String, char, double followed by variable name and a termination character i.e. semicolon (;).

Syntax:


DataType variableName ;

Example

Following java code will create a variable named age with data type int and put a value “10” into it.

int age;
age = 10;

We can create and assign values in a single statement as follows:

int age = 10;

Java Comments

We can add comments in java code. They are not compiled. Java compiler simply ignores the java comments and only compiles the java code. There are two types of java comments.

Single line java comments

Multiline java comments

Single line java comments

Any line in java code starting with // is a java comment and java compile will ignore it while compiling.
Following example shows a single line java comment:

// This is a comment
System.out.println("Hello World");

We can add java comments at the end of a java code statement. Following example shows a single line java comment at the end of a java code statement:

System.out.println("Hello World"); // This is a comment

Java Multi-line Comments

We can add comments in a java program which span more than one lines.

Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by Java.
Following example shows multi-line java comments:

/* It is a multi-line java comment
It is second line of java comment
It is third line of java comment
You can add as much lines of java comments as you want */
System.out.println("Hello World");

Java basic Syntax

In previous post we created a java file named FirstJavaProgram.java which prints “Hello Word” on screen when we run it using java command  after compilation using javac command.


class FirstJavaProgram {

public static void main(String args[]){

System.out.println("Hello World");

}

}

FirstJavaProgram.java explained

In Java every line of code must be inside a class. In above example, we named the class FirstJavaProgram. It is good programming practice to start each word in the class name with an uppercase letter.
Java is case-sensitive therefore “FirstClass” and “firstClass” has different meaning.

Java class name and file name in should be same . 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

Main Method in Java Program


public static void main(String[] args)

Java program execution starts from main method. public, static, void are keywords of java which will be explained later. String[] args are command line arguments which be explained later in detail. For now you should only remember that main method is necessary for every java program with above syntax.

The code line System.out.println(“Hello World”); prints a line of text on command line. You can note a semicolon ( ; ) at the end of the statement. It is mandatory at the end of each java statement. The curly braces {} are used to start and stop a class and method name. You can note starting and ending curly braces of class and main method separately.

Java Getting Started

All applications in java begin with a class name, and that class must match the filename. Now let’s create our fist java program. Name of class will be FirstJavaProgram and name of file will FirstJavaProgram.java. We can do it in any text editor like notepad or an IDE like Netbeans. It will contain a main method which will print “Hello Word” on screen.

class FirstJavaProgram {

public static void main(String args[]){

System.out.println("Hello World");

}

}

Save the file as FirstJavaProgram.java
Open terminal, point it to directory where you have saved the above java file and type following command:
javac FirstJavaProgram.java
above command will compile the java file and create an new file named FirstJavaProgram.class. Now let’s run this file by type following command on termial:
java FirstJavaProgram.class
the above command will print the string “Hello World” on screen and will be terminated.

Java Environment Setup

In this section we will describe the process to setup Java on your local machine.

Option 1 setting path to use javac compiler:

You can write java program in any text editor, compile it using javac command and run by java command on command line. To install java environment go to here and follow the instructions. For windows operating system download latest jdk version install it and setup path as follows:

Assuming you have installed Java in c:\Program Files\java\jdk directory −

        • Right-click on ‘My Computer’ and select ‘Properties’.
        • Click the ‘Environment variables’ button under the ‘Advanced’ tab.
        • Now, alter the ‘Path’ variable so that it also contains the path to the Java executable. Example, if the path is currently set to ‘C:\WINDOWS\SYSTEM32’, then change your path to read ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.

Option 2 using an IDE

use the IDE and leave the rest to IDE to set java path. Following are some popular java IDEs you can freely download and use to write and compile the java programs.