DATA TYPES –EXAMPLE
[Link]
public class ByteExample {
public static void main(String[] args) {
byte a = 100; // Range: -128 to 127
[Link]("byte value: " + a);
}
}
public class ShortExample {
public static void main(String[] args) {
short b = 20000; // Range: -32,768 to 32,767
[Link]("short value: " + b);
}
}
public class IntExample {
public static void main(String[] args) {
int c = 1500000000; // Range: -2^31 to 2^31 - 1
[Link]("int value: " + c);
}
}
public class LongExample {
public static void main(String[] args) {
long d = 123456789012345L; // Must end with 'L'
[Link]("long value: " + d);
}
}
public class FloatExample {
public static void main(String[] args) {
float e = 12.34f; // Must end with 'f'
[Link]("float value: " + e);
}
}
public class DoubleExample {
public static void main(String[] args) {
double f = 123.456789;
[Link]("double value: " + f);
}
}
public class CharExample {
public static void main(String[] args) {
char g = 'A'; // Unicode character
[Link]("char value: " + g);
}
}
public class BooleanExample {
public static void main(String[] args) {
boolean h = true; // or false
[Link]("boolean value: " + h);
}
}
public class StringExample {
public static void main(String[] args) {
String message = "Hello, World!";
[Link]("String value: " + message);
}
}
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
[Link]("Array elements:");
for (int num=1;num<=n;num++) {
[Link](num);
}
}
}
Defining class
class Person {
String name = "Alice";
int age = 25;
}
// Class usage
public class ClassExample {
public static void main(String[] args) {
Person p = new Person();
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
}
}
Define an object
public class ObjectExample {
public static void main(String[] args) {
Object obj = "This is a String stored as an Object";
[Link]("Object value: " + [Link]());
}
}
Define an interface
interface Animal {
void sound();
}
// Implement the interface
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
}
// Using the interface
public class InterfaceExample {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
You use new keyword to create instances
Variable Type Where Declared Lifetime / Scope Description
Belong to an instance of the
Instance Variables Inside a class, outside any Exist as long as the
class; each object has its own
(Non-static fields) method or constructor object exists
copy
Static Variables Inside a class, declared with Exist as long as the class Shared among all instances of the
(Class variables) static keyword is loaded class
Inside methods, Exist only during Created when the method/block
Local Variables
constructors, or blocks method/block execution is called, destroyed afterward
public class Example {
int instanceVar = 10; // Instance variable
public void display() {
[Link]("Instance Variable: " + instanceVar);
}
}
public class Example {
static int staticVar = 20; // Static variable
public void display() {
[Link]("Static Variable: " + staticVar);
}
}
public class Example {
public void method() {
int localVar = 30; // Local variable
[Link]("Local Variable: " + localVar);
}
}
Conversion Example Code Notes
Automatic (Widening) int i = 10; long l = i; No explicit cast needed
Manual (Narrowing) double d = 9.99; int i = (int) d; Explicit cast required
int to String String s = [Link](123); Convert primitive to String
String to int int i = [Link]("123"); Parse string to primitive
public class AutomaticConversion {
public static void main(String[] args) {
int i = 100;
long l = i; // int to long (widening)
float f = l; // long to float (widening)
[Link]("int value: " + i);
[Link]("long value: " + l);
[Link]("float value: " + f);
}
}
public class ManualConversion {
public static void main(String[] args) {
double d = 100.04;
long l = (long) d; // double to long (narrowing)
int i = (int) l; // long to int (narrowing)
[Link]("double value: " + d);
[Link]("long value: " + l);
[Link]("int value: " + i);
}
}
int i = 123;
String s = [Link](i);
[Link]("String value: " + s);
String s = "456";
int i = [Link](s);
[Link]("int value: " + i);
Primitive Wrapper Class
int Integer
double Double
char Character
boolean Boolean
public class WrapperConversionExample {
public static void main(String[] args) {
// Autoboxing: primitive to wrapper
Double d = 45.67;
// Unboxing: wrapper to primitive
double primitiveDouble = d;
// Wrapper to String
String str = [Link]();
// String to Wrapper and primitive
Integer iObj = [Link]("123");
int iPrim = [Link]("456");
[Link]("Autoboxed Double: " + d);
[Link]("Unboxed double: " + primitiveDouble);
[Link]("Double as String: " + str);
[Link]("String to Integer Object: " + iObj);
[Link]("String to int primitive: " + iPrim);
}
}
Operation Example
Primitive → Wrapper Integer i = 10;
Wrapper → Primitive int i = new Integer(10);
Wrapper → String String s = [Link](10).toString();
String → Wrapper Integer i = [Link]("10");
String → Primitive int i = [Link]("10");
Because wrapper classes don't have direct constructors or methods to convert between each
other, you typically:
1. Unbox the original wrapper to its primitive type
2. Convert the primitive to the target wrapper type
Convert Integer to Double
public class WrapperConversion {
public static void main(String[] args) {
Integer intObj = 42;
// Step 1: Unbox Integer to int
int intValue = intObj;
// Step 2: Convert int to double primitive
double doubleValue = (double) intValue;
// Step 3: Box double primitive to Double wrapper
Double doubleObj = doubleValue;
[Link]("Integer value: " + intObj);
[Link]("Converted Double value: " + doubleObj);
}
}
Double doubleObj = 55.99;
Convert Double to int via Number method and autoboxing
Integer intObj = [Link]();
[Link]("Double value: " + doubleObj);
[Link]("Converted Integer value: " + intObj);
numeric wrappers extend Number, you can also use methods like .doubleValue(),
.intValue(), .floatValue()
Method Converts to...
intValue() int
longValue() long
floatValue() float
doubleValue() double
byteValue() byte
shortValue() short
public class WrapperTypeConversionExample {
public static void main(String[] args) {
Integer i = 100;
Double d = [Link](); // Integer → Double
Float f = [Link](); // Double → Float
Long l = [Link](); // Float → Long
[Link]("Integer: " + i);
[Link]("Double: " + d);
[Link]("Float: " + f);
[Link]("Long: " + l);
}
}
Converting Character to String and vice versa
public class CharStringConversion {
public static void main(String[] args) {
// Character to String
Character ch = 'A';
String str = [Link]();
[Link]("Character to String: " + str);
// String to Character (taking first character)
String s = "Hello";
Character ch2 = [Link](0); // no direct wrapper conversion, use charAt
[Link]("String to Character: " + ch2);
}
}
Converting Boolean to String and vice versa
public class BooleanStringConversion {
public static void main(String[] args) {
// Boolean to String
Boolean bool = true;
String str = [Link]();
[Link]("Boolean to String: " + str);
// String to Boolean
String s = "true";
Boolean bool2 = [Link](s);
[Link]("String to Boolean: " + bool2);
}
}
No Direct Conversion Between Character and Boolean
You cannot convert a Character directly to a Boolean or vice versa.
You must define your own logic depending on context.
Example: converting 'Y'/'N' to boolean:
public class CharToBooleanExample {
public static void main(String[] args) {
Character c = 'Y';
Boolean b = null;
if (c == 'Y' || c == 'y') {
b = true;
} else if (c == 'N' || c == 'n') {
b = false;
} else {
[Link]("Invalid character for boolean conversion.");
}
[Link]("Character '" + c + "' converted to Boolean: " + b);
Conversion How to do it
Character → String [Link]()
String → Character [Link](0)
Boolean → String [Link]()
String → Boolean [Link](str)
Character ↔ Boolean Custom logic (no direct conversion)
}
}
Operator Type Description Example
1. Arithmetic Operators Perform mathematical calculations +, -, *, /, %
2. Relational Operators Compare values ==, !=, >, <, >=, <=
3. Logical Operators Combine boolean expressions &&, `
4. Assignment Operators Assign values to variables =, +=, -=, *=, /=, %=
Operator Type Description Example
5. Unary Operators Perform operations on single operand +, -, ++, --, !
6. Bitwise Operators Perform bit-level operations &, `
7. Ternary Operator Conditional operator (shorthand if) condition ? expr1 : expr2
int a = 10, b = 3;
[Link]("a + b = " + (a + b)); // 13
[Link]("a % b = " + (a % b)); // 1
int a = 5, b = 10;
[Link](a > b); // false
[Link](a != b); // true
boolean x = true, y = false;
[Link](x && y); // false
[Link](x || y); // true
[Link](!x);
int a = 5;
a += 3; // same as a = a + 3
[Link](a); // 8
int a = 5;
[Link](++a); // 6 (pre-increment)
[Link](a--); // 6 (post-decrement, prints first, then decrements)
[Link](!true); // false (logical NOT)
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
[Link](a & b); // 1 (0001)
[Link](a | b); // 7 (0111)
[Link](a ^ b); // 6 (0110)
[Link](~a); // -6 (bitwise NOT)
[Link](a << 1); // 10 (1010, left shift)
[Link](b >> 1); // 1 (0001, right shift)
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Max is: " + max); // Max is: 20
INDETAIL
int a = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101
int b = 3; // binary: 0000 0000 0000 0000 0000 0000 0000 0011
a = 0101 (5)
b = 0011 (3)
--------------
& = 0001 (1)
a = 0101 (5)
b = 0011 (3)
--------------
| = 0111 (7)
a = 0101 (5)
b = 0011 (3)
--------------
^ = 0110 (6)
a = 0000 0000 0000 0000 0000 0000 0000 0101 (5)
~a = 1111 1111 1111 1111 1111 1111 1111 1010 (-6 in decimal, two's complement)
a = 0000 0101 (5)
a << 1 = 0000 1010 (10)
a << 2 = 0001 0100 (20)
a = 0000 0101 (5)
a >> 1 = 0000 0010 (2)
a >> 2 = 0000 0001 (1)
int n = -8; // binary: 1111...1000 (two's complement)
[Link](n >> 2); // keeps sign bit, result: -2
Rule: Shifts bits right, fills left with 0, regardless of sign.
For positive numbers, >> and >>> behave the same:
[Link](a >>> 1); // Output: 2 (same as a >> 1)
For negative numbers:
int n = -8;
[Link](n >>> 2);
PROGRAM
public class BitwiseOperatorsDemo {
public static void main(String[] args) {
int a = 5; // 0101
int b = 3; // 0011
[Link]("a & b = " + (a & b)); // 1
[Link]("a | b = " + (a | b)); // 7
[Link]("a ^ b = " + (a ^ b)); // 6
[Link]("~a = " + (~a)); // -6
[Link]("a << 1 = " + (a << 1)); // 10
[Link]("a << 2 = " + (a << 2)); // 20
[Link]("a >> 1 = " + (a >> 1)); // 2
[Link]("a >> 2 = " + (a >> 2)); // 1
int n = -8;
[Link]("n = " + n);
[Link]("n >> 2 = " + (n >> 2)); // -2
[Link]("n >>> 2 = " + (n >>> 2)); // large positive number
}
}
a&b=1
a|b=7
a^b=6
~a = -6
a << 1 = 10
a << 2 = 20
a >> 1 = 2
a >> 2 = 1
n = -8
n >> 2 = -2
n >>> 2 = 1073741822
CONTROL STAEMENTS
Statement Type Description
if Executes block if condition is true
if-else Executes one block if true, another if false
if-else if Tests multiple conditions
switch Selects one of many possible blocks
int age = 20;
if (age >= 18) {
[Link]("You are an adult.");
}
int number = 5;
if (number % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}
int marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 60) {
[Link]("Grade C");
} else {
[Link]("Fail");
}
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Another day");
}
Loop Type Description
for Repeats block a specific number of times
while Repeats block while a condition is true
do-while Repeats block at least once, then checks condition
for-each Iterates over arrays or collections
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
}
}
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
[Link]("Hello " + i);
i++;
}
}
}
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
[Link]("Value: " + i);
i++;
} while (i <= 2);
}
}
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int num : numbers) {
[Link]("Number: " + num);
}
}
}
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
[Link](i);
}
// Output: 1 2
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
[Link](i);
}
// Output: 1 2 4 5
ARRAYS
Type Description
1. One-Dimensional Array Simple linear array (row)
2. Multi-Dimensional Array Arrays of arrays (like a grid or matrix)
3. Jagged Array Multi-dimensional arrays with rows of unequal lengths
int[] numbers = new int[5]; // Declares array of size 5
int[] values = {10, 20, 30, 40}; // Declares and initializes
values[0] = 100; // Update value
[Link](values[2]); // Output: 30
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20};
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
[Link](matrix[1][2]); // Output: 6
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2};
jagged[1] = new int[]{3, 4, 5};
jagged[2] = new int[]{6};
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < jagged[i].length; j++) {
[Link](jagged[i][j] + " ");
}
[Link]();
}
}
}
Fixed Size: Size must be specified at creation and cannot be changed.
Indexed Access: Index starts from 0.
Homogeneous Elements: All elements must be of the same type.
Length: Accessed via [Link] (no parentheses).
Type Description
Default constructor No parameters, sets default values
Parameterized constructor Takes arguments to initialize with specific values
public class Car {
String brand;
int year;
// Default constructor
public Car() {
brand = "Unknown";
year = 0;
}
public void display() {
[Link]("Brand: " + brand + ", Year: " + year);
}
public static void main(String[] args) {
Car c1 = new Car(); // Calls default constructor
[Link](); // Output: Brand: Unknown, Year: 0
}
}
public class Car {
String brand;
int year;
// Parameterized constructor
public Car(String b, int y) {
brand = b;
year = y;
}
public void display() {
[Link]("Brand: " + brand + ", Year: " + year);
}
public static void main(String[] args) {
Car c2 = new Car("Toyota", 2020);
[Link](); // Output: Brand: Toyota, Year: 2020
}
}
public class Car {
String brand;
int year;
public Car() {
brand = "Unknown";
year = 0;
}
public Car(String b) {
brand = b;
year = 0;
}
public Car(String b, int y) {
brand = b;
year = y;
}
public void display() {
[Link]("Brand: " + brand + ", Year: " + year);
}
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("Honda");
Car c3 = new Car("Ford", 2018);
[Link](); // Brand: Unknown, Year: 0
[Link](); // Brand: Honda, Year: 0
[Link](); // Brand: Ford, Year: 2018
}
}
METHOD OVERLOADING
public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two doubles
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 10)); // Output: 15
[Link]([Link](5, 10, 15)); // Output: 30
[Link]([Link](3.5, 2.5)); // Output: 6.0
}
}
Method Signature Description
add(int a, int b) Adds two integers
add(int a, int b, int c) Adds three integers
add(double a, double b) Adds two doubles (decimals)
public class Display {
public void show(int num) {
[Link]("Integer: " + num);
}
public void show(String text) {
[Link]("String: " + text);
}
public void show(int num, String text) {
[Link]("Integer and String: " + num + ", " + text);
}
public static void main(String[] args) {
Display d = new Display();
[Link](100); // Integer: 100
[Link]("Hello"); // String: Hello
[Link](50, "World"); // Integer and String: 50, World
}
}
STRINGS
String s1 = "Hello"; // String literal
String s2 = new String("World"); // Using constructor
Method Description Example & Output
length() Returns length of string "Hello".length() → 5
charAt(int index) Returns character at given index "Hello".charAt(1) → 'e'
toUpperCase() Converts string to uppercase "Hello".toUpperCase() → "HELLO"
toLowerCase() Converts string to lowercase "Hello".toLowerCase() → "hello"
substring(int beginIndex) Returns substring from beginIndex to end "Hello".substring(2) → "llo"
Method Description Example & Output
Returns substring between begin
substring(int begin, int end) "Hello".substring(1,4) → "ell"
(inclusive) and end (exclusive)
Checks if two strings are equal (case-
equals(String another) "Hello".equals("hello") → false
sensitive)
equalsIgnoreCase(String "Hello".equalsIgnoreCase("hello") →
Case-insensitive equality check
another) true
trim() Removes leading and trailing whitespace " Hi ".trim() → "Hi"
replace(char oldChar, char Replaces all occurrences of oldChar with
"Hello".replace('l', 'p') → "Heppo"
newChar) newChar
Checks if string contains the specified
contains(CharSequence seq) "Hello".contains("ll") → true
sequence
indexOf(char ch) Returns index of first occurrence of char "Hello".indexOf('l') → 2
split(String regex) Splits string into array based on regex "a,b,c".split(",") → ["a", "b", "c"]
isEmpty() Checks if string length is zero "".isEmpty() → true
public class StringMethodsExample {
public static void main(String[] args) {
String str = " Hello World ";
[Link]("Original: '" + str + "'");
[Link]("Length: " + [Link]());
[Link]("Trimmed: '" + [Link]() + "'");
[Link]("Uppercase: " + [Link]());
[Link]("Substring (6 to 11): " + [Link](6, 11));
[Link]("Contains 'World'? " + [Link]("World"));
[Link]("Replace 'l' with 'p': " + [Link]('l', 'p'));
[Link]("Index of 'o': " + [Link]('o'));
[Link]("Is empty? " + [Link]());
// Splitting
String csv = "apple,banana,orange";
String[] fruits = [Link](",");
[Link]("Fruits:");
for (String fruit : fruits) {
[Link](fruit);
}
}
}
Original: ' Hello World '
Length: 15
Trimmed: 'Hello World'
Uppercase: HELLO WORLD
Substring (6 to 11): World
Contains 'World'? true
Replace 'l' with 'p': Heppo Worpd
Index of 'o': 7
Is empty? false
Fruits:
apple
banana
orange
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
In Java, wrapper classes are used to wrap primitive data types into objects
· To use primitives in Collections (e.g., ArrayList<Integer>)
· For utility methods (e.g., [Link]())
· For object-oriented programming — treat primitives as objects
· To use null values, which primitives can't have
public class WrapperExample {
public static void main(String[] args) {
int num = 10;
// Manually boxing the int into an Integer object
Integer boxed = [Link](num);
// Unboxing the Integer object back to int
int unboxed = [Link]();
[Link]("Boxed: " + boxed);
[Link]("Unboxed: " + unboxed);
}
}
Autoboxing
Converting a primitive to a wrapper class automatically.
int a = 5;
Integer obj = a; // Autoboxing
Unboxing
Converting a wrapper class object to a primitive automatically.
Integer obj = 10;
int b = obj; // Unboxing
Wrapper Class Methods
Integer x = [Link]("123");
int y = [Link]("456");
[Link](x); // 123
[Link](y); // 456
1. valueOf()
Returns an Integer object representing the specified value.
Integer x = [Link](10); // from int
Integer y = [Link]("20"); // from String
2. parseInt()
Parses the string and returns a primitive int.
int a = [Link]("123"); // returns int
3. intValue()
Returns the value of the Integer object as a primitive int.
Integer obj = [Link](30);
int num = [Link](); // unboxing
4. toString()
Converts the Integer (or any wrapper) to a String.
Integer num = 45;
String str = [Link](); // "45"
5. compareTo()
Compares two Integer objects.
Integer a = 100;
Integer b = 200;
int result = [Link](b); // returns negative because a < b
6. compare()
Compares two primitive int values (static method).
int result = [Link](100, 200); // returns negative
7. equals()
Checks if two Integer objects are equal in value.
Integer a = 50;
Integer b = 50;
boolean isEqual = [Link](b); // true
8. decode()
Converts a string to an Integer. Supports decimal, hexadecimal, and octal.
Integer dec = [Link]("123"); // 123
Integer hex = [Link]("0x1A"); // 26
Integer oct = [Link]("075"); // 61 (octal)
9. MAX_VALUE and MIN_VALUE
Constants that define the max and min values an int can have.
[Link](Integer.MAX_VALUE); // 2147483647
[Link](Integer.MIN_VALUE); // -2147483648
10. reverse()
Returns the value obtained by reversing the order of the bits.
int rev = [Link](12); // reverses bits
public class WrapperMethodsExample {
public static void main(String[] args) {
// valueOf()
Integer a = [Link](100);
Integer b = [Link]("200");
// parseInt()
int c = [Link]("300");
// intValue()
int d = [Link]();
// toString()
String str = [Link]();
// compareTo() and compare()
int comp1 = [Link](b); // a vs b
int comp2 = [Link](500, 400);
// equals()
boolean isEqual = [Link]([Link](100));
// decode()
Integer hex = [Link]("0x10");
// MAX_VALUE and MIN_VALUE
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
// Output
[Link]("a: " + a);
[Link]("b: " + b);
[Link]("c: " + c);
[Link]("d: " + d);
[Link]("str: " + str);
[Link]("comp1: " + comp1);
[Link]("comp2: " + comp2);
[Link]("isEqual: " + isEqual);
[Link]("hex: " + hex);
[Link]("MAX: " + max);
[Link]("MIN: " + min);
}
}
Size of int vs Integer in Java
1. int (primitive type)
Size: Always 4 bytes = 32 bits
Fixed size, defined by the Java specification.
Stored directly in memory.
2. Integer (wrapper class)
Not just a number — it’s an object.
Internally wraps an int, but adds object metadata, headers, and
methods.
The actual memory footprint is larger than 4 bytes due to:
o Object header (typically 8 to 16 bytes)
o The int value (4 bytes)
o Padding for memory alignment (possible)
📝 Approximate size of an Integer object in memory: 16 to 24 bytes,
depending on the JVM and architecture (32-bit or 64-bit).
· Use primitives when possible for better performance
· Use wrappers when:
You need to store null
You're using Collections (e.g., List<Integer>)
You need object methods
Why would you want to store null?
To represent "no value", missing data, or optional values
Especially useful in:
o Databases (nullable fields)
o Collections (e.g., List<Integer>)
o JSON serialization/deserialization
o Optional logic (e.g., something may or may not be present)
If a primitive field is missing in the JSON, it gets default values:
int → 0
boolean → false
double → 0.0