High level, widely used, general purpose programming language.
Other lang : Code -> Compiler -> Machine code
Java lang : Code -> Compiler -> Interpreter(JVM) -> Machine code
JDK is (JRE+devTools) - For developer contains javac,debugging tools,archieve tool(jar), javadoc
JRE is (JVM+lib) - For layman users to run java program
JVM is Interpreter execute byte code to machine code, contains JustInTime compiler
Byte code: low level representation of source code, not readable
javac -d directory javafilename.java
java myppack.javafilename
import java.util.Scanner;
class Hello{
public static void main(String[]args){
System.out.println("Hello World!");
}
}
used to name things/identify elements
value used in the code
combination of variables, identifiers, literals
Predefined meaning (68) words. Keywords list
System.out.println("Hello world");
System.out.print("Hello world");
import java.util.Scanner;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = scanner.nextInt();
char ch = scanner.next.charAt(0);
}
defines type of data, ie.Predefined memory storage
Name | Size | Range | 2n |
---|---|---|---|
byte | 1byte | -+128 | 28 |
short | 2byte | -+32,768 | 216 |
int | 4byte | -+2,14,74,83,648 | 236 |
long | 8byte | -+9,22,33,72,03,68,54,775 | 264 |
float | 4byte | . after 6 digit | 236 |
double | 8byte | . after 15 digit | 264 |
char | 2byte | A-Z a-z 0-9 0-127ASCII | 216 |
boolean | depends on jvm, 1bit | 0 1 | 2 |
Binary can be represent as adding “0b” ex: int a = 0b011;
Hexadecimel can be represnt as adding “0x” ex: int a = 0x2A;
Power can be represent by e ex: float a = 35e3f;
At the end of float number f or F is necessary otherwise when we use dot(.) it default consider as double
Named storage location. ie name for the datatype.
performs mathemetical operations on operands.
Operators | Symbols |
---|---|
Arithmetic Operator | + - * / % |
Relational Operator | <, <=, >, >=, ==, != |
Logical Operator | &&(AND), \|\| (OR), !(NOT) |
Assignment Operator | a += 4 |
Inc and Dec Operator | a++,a--,++a,--a |
Conditional Operator | exp1? exp2: exp3; |
Bitwise Operator | &, <<, >>, >>> |
Special Operator | instanceof, (.) |
Unary Operator | ~, ! |
int a=10; int b=-9;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
Arithmetic operator order: System.out.println(10*10/5+3-1*4/2);
is 21
Left shift operator: 10 << 2 is 10 * 2^2 = 40
Right shift operator: 10 >> 2 is 10 / 2^2 = 2
, when negative number it will -2
Bitwise operator & : (a>1&b<3) second condition also been check, where && wont go to second condition
control flow of program
Name | defination | syntax |
---|---|---|
If | control code | if(con){ exp1; } |
If-else | alternative for two ifs | if(con){ exp1; } else{ exp2; } |
If-elseif | for more than one else | if(con){ exp1; }else if(condition2){ exp2; }else{ exp3; } |
Tenary operator | short form of ifelse | condition ? expersion 1: expersion 2; |
Switch case | use lookup table | switch(varible){case constant: operation; break;default: operation;break;} |
Note: long float double and custom classes cannot be use in switch
repeat the execution
Name | defination | syntax |
---|---|---|
while | iterates as long as condition true | while(con){ body; } |
do-while | executes atleast once | do{ body }while(condition); |
for-loop | for(intialize counter;test condition;inc or dec counter){ body; } |
|
break | get out of loop | break; |
continue | back to continue next loop | continue; |
continue with label | Skips to next iteration of labeled loop | continue loop_label; |
goto | Jumps to a labeled statement | goto label_name; |
labelled break | Exits a labeled loop | break label_name; |
For-each | Iterates over elements of collection | for (DataType var : iterable) { body; } |
Group of similar datatype refered by single variable name
int a[];
int[] a;
int[] a = new int[4];
int[] a = new int[]{1,2,3,4};
or int[] a = {1,2,3,4};
.return new int[]{1,2};
Multi Dimensional arrays: array of arrays. int a[][]; //used to define matrix
Arrays.toString(arr);
Arrays.equals(arr1, arr2);
Arrays.asList(arr);
//conver array into immutable raw listArrays.sort(arr);
//use mergeosrt for object, and quick sort fro primitive datatypeArrays.sort(arr, new Comparator());
Arrays.binarySearch(arr, searchValue);
Arrays.compare(intArr, intArr1);
Arrays.copyOf(arr, 10);
//create new clone array, also with initial sizeArrays.copyOfRange(intArr, 1, 3);
sequence of char, immutable, uses double quotes.
s1.equals(s2);
check for each char are same or nots1==s2;
check address is same or nots1.compareTo(s2);
compare string lexicographically. ie <0,>0charAt(int index)
length()
isEmpty()
toUpperCase()
, toLowerCase()
str1.equals(str2)
, str1.equalsIgnoreCase(str2)
compareTo(str)
, compareToIgnoreCase(str)
- Lexicographical comparisoncontains(str)
startsWith(prefix)
, endsWith(suffix)
trim()
- Removes whitespace from front and back.indexOf(String str)
, lastIndexOf(String str)
replace(str1, str2)
- replace all occurrences of str1 with str2.substring(int beginIndex, int endIndex)
split(String regex)
join(delimiter, str2)
format(String format, Object... args)
-format string with argumentsmatches(regex)
create only one time, called without reference
className.variableName;
className.functionName();
import static java.lang.Math.PI;
static {}
//execute while class get loaded{ }
inside class, runs before constructor & after static block assigned only once, cannot modify once it assigned
final int maxSpeed =100;
Immutable. Declare as final static. eg: static final double PI=3.14
Note: if it is declared as private inside a class, it can be redeclare in another class
group of constant( final,static)
enum Level { LOW, MEDIUM, HIGH }
Level myVar = Level.MEDIUM;
case sensitive, not falls under any type, null==null is true
Convert one datatype to another
int a = (int) 3.14; //3
. String.valueOf(33); //"33"
Note: typecasting char to int will give unicode. A=65, a=97
Collection of similar classes, interfaces and sub packages.
Syntax : import pkg1 [.pkg2].(classname | *);
.
import java.io.*;.
Define package in program:
package packagename;
how to import whole package:
import packagename.*;
Note: we can use fully qualified name.
java.util.List<> list = new java.util.ArrayList
wrap around primitive datatype & give object appearence
int j=1;
Integer i = Integer.valueof(j); or Integer i =j;
Integer i = new Integer(7);
int = i.intValue(); or int j=i;
parameterized types
Adv: 1.Type safety, 2.Typecast not needed, 3.Compilertime checking
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
mechanism of writing obj into byte stream, implement serializable marker interface
Note: it is gonna depreacted not recommended due to security vulnerablities.
Data exchange formats: JSON, XML. these are alternatives for native serialization.
FileOuputStream file = new FileOutputStream(filename);
ObjectOuputStream out = new ObjectOuputStream(file);
out.writeObject(object); out.close(); file.close();
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.readObject(); //new object create
do file operations using File class. Stream: series/flow of data.
Scanner scanner = new Scanner(fileObj);
while (scanner.hasNextLine()) { System.out.println(dataReader.nextLine()); }
Handles Unexpected event that terminate program
try {
throw new Exception("Custom exception message");
} catch (Exception e) {
// Handle the exception
} catch (ArithmeticException | NullPointerException e) {
// This is a multi-catch block
} finally {
// Code that always executes, regardless of whether an exception was thrown or not
// Note: `finally` will not execute if the JVM exits (e.g., System.exit()) or if there's a system crash.
// only one finally block is allowed
}
Throws : indicates caller functions of that method to handling that exception. void methodName throws Exception{ }
Custom Exception class
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
Exception Type | Description | Checked/Unchecked |
---|---|---|
IOException | Occurs when an input-output operation fails or is interrupted. | Checked |
SQLException | Indicates a database access error or other issues with SQL. | Checked |
FileNotFoundException | Thrown when a file with the specified pathname does not exist. | Checked |
ClassNotFoundException | Thrown when trying to load a class that cannot be found. | Checked |
NullPointerException | Thrown when an application attempts to use null where an object is required. | Unchecked |
ArrayIndexOutOfBoundsException | Occurs when trying to access an array index that is out of bounds. | Unchecked |
ArithmeticException | Occurs during illegal arithmetic operations, such as division by zero. | Unchecked |
IllegalArgumentException | Thrown when a method receives an illegal argument. | Unchecked |
NumberFormatException | Occurs when trying to convert string into a number but the string is not valid. | Unchecked |
ClassCastException | Thrown when trying to cast an object to a subclass it is not an instance of. | Unchecked |
OutOfMemoryError | Thrown when the JVM cannot allocate more memory. | Error |
StackOverflowError | Thrown when stack space is exhausted, usually due to deep or infinite recursion. | Error |
NoClassDefFoundError | Occurs when the JVM/class loader cannot find a required class | Error |
allows runtime inspection, modification, and invocation of classes, methods, fields, and constructors
Topic | Code/Description |
---|---|
Class | Class<?> cls = Class.forName("java.lang.String"); |
Access Public | getMethods() , getFields() , getConstructors() |
Access Private | getDeclaredMethods() , getDeclaredFields() , getDeclaredConstructors() |
Invoke | method.invoke(object, args) |
Field | field.get(object) , field.set(object, value) |
Object Creation | constructor.newInstance(args) |
import java.lang.reflect.*;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("java.lang.String");
Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
Constructor<?> constructor = cls.getConstructor(String.class);
Object obj = constructor.newInstance("Hello Reflection");
Method lengthMethod = cls.getMethod("length");
int length = (int) lengthMethod.invoke(obj);
System.out.println("\nLength of string: " + length);
}
}
metadata that provides data about a program to compiler
//optional- specifies where annotation can be applied
@Target(ElementType.METHOD)
//optional- SOURCE, CLASS, RUNTIME // specify where it is accessible
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value(); int number() default 0;
}
@MyAnnotation(value = "example", number = 5)
public void myMethod() { // method implementation }
^[a-zA-Z][a-zA-Z0-9]{8,19}
str.matches("[a-z]+"); //return boolean
System.out.println(Pattern.matches(".s", "as")); //line 4
Regex | Description | Example | Matches |
---|---|---|---|
. |
Any single character | "a.b" |
"aab" , "a-b" , "a*b" , etc. |
* |
0 or more occurrences | "a*" |
"a" , "aa" , "" (empty string), etc. |
+ |
1 or more occurrences | "a+" |
"a" , "aa" , "aaa" , but not "" |
? |
0 or 1 occurrence | "a?" |
"" (empty string) or "a" |
{n} |
Exactly n occurrences |
"a{3}" |
"aaa" |
{n,} |
n or more occurrences |
"a{2,}" |
"aa" , "aaa" , "aaaa" , etc. |
{n,m} |
Between n and m occurrences |
"a{2,4}" |
"aa" , "aaa" , "aaaa" |
[abc] |
Any one of the listed characters | "[abc]" |
"a" , "b" , "c" |
[^abc] |
Any character except listed ones | "[^abc]" |
"d" , "1" , etc. |
(a|b) |
Either a or b |
"(cat|dog)" |
"cat" or "dog" |
\d |
Any digit | "\d" |
"1" , "2" , "9" , etc. |
\D |
Any non-digit character | "\D" |
"a" , "!" , " " , etc. |
\w |
Any word character | "\w" |
"a" , "Z" , "9" , "_" , etc. |
\W |
Any non-word character | "\W" |
"!" , " " , "@" , etc. |
\s |
Any whitespace character | "\s" |
" " , "\t" , "\n" , etc. |
\S |
Any non-whitespace character | "\S" |
"a" , "1" , "!" , etc. |
Examples:
^\d{10}$
- phone number^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
- email^[a-zA-Z]+$
- name