Java
Java
Java is a programming language developed by James Gosling and first released by Sun
Microsystems in 1995.
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
https://www.oracle.com/java/technologies/downloads/#jdk19-windows
PROGRAMMIN
G STRUCTURE
DOCUMENTATION /
COMMENT
Single-line comments: start with two forward slashes (//).
Documentation Comment: It starts with the delimiter (/**) and ends with */.
PACKAGE
A package in Java is used to group related classes.
IMPORT STATEMENT
JAVA CLASS
Every application begins with a class name, and that class must match the filename
CLASS DEFINITION
• The class is a blueprint of a Java program that contains information about user-defined methods,
variables, and constants.
• Every line of code that runs in Java must be inside a class. Without the class, we cannot create any
Java program.
11 / 85
• Every Java program has at least one class that contains the main().
• We use the class keyword to define the class.
• A class name should always start with an uppercase first letter.
MAIN METHOD CLASS
• The execution of all Java programs starts from the main() method.
• In other words, it is an entry point of the class. It must be inside the class.
• Inside the main method, we create objects and call the methods.
• public- This is the access modifier of the main method. It has to be public so that java runtime can
execute this method.
without compilation errors. But, at the time of execution JVM does not consider this new method (without
static) as the entry point of the program.
It searches for the main method which is public, static, with return type void, and a String array as an
A Java main() function does not return anything to keep things simple and has the return type
void.
After executing the main() method, the program will be terminated, and returning anything
from the main() method is useless because the JVM cannot do anything with the return value.
The following error will be thrown if we do not provide the main() method with a void return
type:
PRINT STATEMENTS
JAVA PRINT
There is also a print() method, which is similar to println().
The only difference is that it does not insert a new line at the end of the output
Double Quotes: When you are working with text, it must be wrapped inside double
You can also use the + character to add a variable to another variable:
keyword (this will declare the variable as "final" or "constant", which means
unchangeable and read-only):
JAVA DECLARE MULTIPLE
VARIABLES
To declare more than one variable of the same type, you can use a comma-separated list:
You can also assign the same value to multiple variables in one line:
JAVA IDENTIFIERS
All Java variables must be identified with unique names called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Names should start with a lowercase letter and it cannot contain whitespace
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like Java keywords, such as int or boolean) cannot be used as names
3 TYPES OF VARIABLE
Static variable: A variable that is declared as static is called a static variable. It cannot be local.
Memory allocation for static variables happens only once when the class is loaded in the memory. It is
the variable that should be initialized first, especially before an instance variable is initialized.
Instance variable: A variable declared inside the class but outside the body of the method, is called an
Local variable: A variable declared inside the body of the method is called local variable. A local
Static variable:
Instance methods:
main method :
Primitive types are predefined (already Non-primitive types are created by the programmer and is not
defined) in Java defined by Java (except for String).
primitive type starts with a lowercase letter while non-primitive types starts with an uppercase letter
size of a primitive type depends on the data non-primitive types have all the same size
type
TYPE CASTING
JAVA TYPE CASTING
Type casting is when you assign a value of one primitive data type to another type. In Java, there are
Narrowing Casting
JAVA OPERATORS
JAVA OPERATORS
Operators are used to perform operations on variables and values.
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Bitwise operators
ARITHMETIC OPERATORS
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
ASSIGNMENT OPERATORS
COMPARISON OPERATORS
Comparison operators are used to compare two values (or variables).
The return value of a comparison is either true or false. These values are known as Boolean
values.
LOGICAL OPERATORS
Logical operators are used to determine the logic between variables or values. You can also
A String in Java is actually an object, which contain methods that can perform certain
operations on strings.
Method Description Return Type
charAt() Returns the character at the specified index (position) char
contentEquals() Checks whether a string contains the exact same sequence of boolean
characters of the specified CharSequence or StringBuffer
endsWith() Checks whether a string ends with the specified character(s) boolean
equals() Compares two strings. Returns true if the strings are equal, and boolean
false if not
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
indexOf() Returns the position of the first found occurrence of specified int
characters in a string
Method Description Return Type
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
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() Returns a new string which is the substring of a specified string String
Method Description Return Type
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
replace() Searches a string for a specified value, and returns a new string where the String
specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that matches the given regular String
expression with the given replacement
replaceAll() Replaces each substring of this string that matches the given regular expression String
with the given replacement
JAVA NUMBERS AND STRINGS
If you add a number and a
Java uses the + operator for both addition and concatenation.
string, the result will be a
Numbers are added. Strings are concatenated.
string concatenation:
If you add two numbers, the result will be a number:
error:
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
Escape sequences
PROGRAMS ON STRING
METHODS
The indexOf() method returns the index (the position) of the first occurrence of a specified text in a
string (including whitespace):
lastIndexOf(int ch) returns last index position for the given char value
STRING CONCATENATION
The + operator can be used between strings to combine them. This is called concatenation:
You can also use the concat() method to concatenate two strings:
SUBSTRING
String substring(int startIndex, int endIndex)
startIndex specifies the beginning index, and endIndex specifies the stopping point.
returns a copy of the substring that begins at startIndex and runs to the end of the
invoking string.
substring(1,3) [1,2]=he
The Java String class equals() method compares the two given strings based on the content of the string. If any
character is not matched, it returns false. If all characters are matched, it returns true.
Compares the given string with the current string lexicographically. It returns a positive
if s1 == s2, it returns 0
If second string is an empty string, the method returns a positive number that is the length of
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
}
compareToIgnoreCase() :
System.out.println(string1.compareToIgnoreCase(string2));
System.out.println(string1.compareToIgnoreCase(string3));
System.out.println(string1.compareToIgnoreCase(string4));
System.out.println(string1.compareToIgnoreCase(string5));
}}
S1=B S2 =A
65<66
contains() method searches the sequence of characters in this string. It returns true if the sequence
of char values is found in this string otherwise returns false.
class ContainsExample
{
String name="what do you know about me";
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
The Java String class isEmpty() method checks if the input string is empty or not
true if length is 0 otherwise false.
System.out.println(replaceString);
}
public class ReplaceStringMain
System.out.println(resultStr);
}
endsWith(): The Java String class endsWith() method checks if this string ends with a given
suffix. It returns true if this string ends with the given suffix; else returns false.
System.out.println(s1.endsWith("t"));
System.out.println(s1.endsWith("point"));
}
equals() method compares the two given strings based on the content of the string. If any
character is not matched, it returns false. If all characters are matched, it returns true.
String name="javat";
char ch=name.charAt(4); //returns the char value at the 4th index
System.out.println(ch);
Output :t
Greater index value-throws StringIndexOutOfBoundsException at run time
PRACTICE PROGRAMS
A person wants to name his newborn baby boy by considering his grandfather and great grandfather's names.
Newborn baby boy name length is seven characters out of these seven characters first three characters are
taken from the first three characters of grandfather's name and the last four characters are taken from the last
four characters of his great grandfather's name. Write a java program to find the newborn baby boy's name by
considering the person's grandfather and great grandfather names.
Sample input:
Output:
{
String st1="Rammurthy";
String st2="Sidhayya";
System.out.println(st1.substring(0,3)+st2.substring(st2.length()-4));
}
MATH FUNCTIONS IN JAVA
https://www.javatpoint.com/java-math
ARRAYS IN JAVA
ARRAYS
Java Arrays are used to store multiple values of same datatype in a single variable, instead
String[ ] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you
cars[0] = "Opel";
To find out how many elements an array has, use the length property:
System.out.println(cars.length); // Outputs 4
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
class Main class Main
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int[ ] age = {12, 4, 5}; int[ ] age = {12, 4, 5};
System.out.println("Using for Loop:"); System.out.println("Using for-each Loop:");
for(int i = 0; i < age.length; i++) for(int a : age)
{ {
System.out.println(age[i]); System.out.println(a);
} }
} }
} }
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
complete array sequentially without using an index variable.
PRINT AN ARRAY USING FOR
LOOP
public class Array {
System.out.println(Arrays.toString(array));
}
}
PRINT A MULTI-DIMENSIONAL
ARRAY
import java.util.Arrays;
System.out.println(Arrays.deepToString(array));
}
}
MULTIDIMENSIONAL ARRAYS
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of
other arrays.
Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.
To create a two-dimensional array, add each array within its own set of curly braces.
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
JAGGED / RAGGED ARRAY
Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D
In a multidimensional array, each element in each dimension has the same, fixed size as the other elements
in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size.
class TestJaggedArray{
public static void main(String[] args){
int arr[][] = new int[3][]; //declaring a 2D array with odd columns
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
It belongs to java.util package. It is used to read the input of primitive types like int,
Conditional statement -
https://www.w3resource.com/java-exercises/conditional-statement/i
ndex.php#google_vignette