1.Python Programming
1.Basics
Print to Console
print("Hello, World!")
# This is a comment
x = 5
name = "Alice"
Numbers
int_num = 10 Integer
float_num = 10.5 Float
str_var = "Hello"
is_active = True
my_list = [1, 2, 3, "four"]
my_tuple = (1, 2, 3)
my_dict = {"name": "Alice", "age": 25}
If Statements
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
for i in range(5):
print(i)
while x < 10:
x += 1
Defining Functions
def my_function(param1, param2):
return param1 + param2
add = lambda a, b: a + b
Importing Modules
import math
from datetime import datetime
result = math.sqrt(16)
Try/Except Blocks
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Reading a File
with open('file.txt', 'r') as file:
content = file.read()
with open('file.txt', 'w') as file:
file.write("Hello, World!")
Creating Lists
squares = [x**2 for x in range(10)]
Length of a List/String
len(my_list)
sorted_list = sorted(my_list)
if 'four' in my_list:
print("Found!")
Class Definition
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return "Woof!"
String Methods
str_var.lower()
str_var.upper()
str_var.split()
my_list.append(4)
my_list.remove(2)
2.Java Programming
1.Basic Structure of a Java Program
public class Main {
public static void main(String[] args) {
// Your code goes here
System.out.println("Hello, World!");
}
}
- Primitive Types:
- int: Integer (4 bytes)
- float: Floating-point number (4 bytes)
- double: Double precision floating-point number (8 bytes)
- char: Character (2 bytes)
- boolean: True/false (1 bit)
- byte: Small integer (1 byte)
- short: Short integer (2 bytes)
- long: Long integer (8 bytes)
3.Variables and Constants
int age = 25; // Variable declaration
final double PI = 3.14; // Constant declaration (final keyword)
- Arithmetic: +, -, *, /, %
- Comparison: ==, !=, >, <, >=, <=
- Logical: && (AND), || (OR), ! (NOT)
- Assignment: =, +=, -=, *=, /=, %=
- Increment/Decrement: ++, —
5.Control Flow
If-Else Statement:
if (condition) {
// Code if true
} else {
// Code if false
}
Switch-Case Statement:
switch (variable) {
case 1:
// Code for case 1
break;
case 2:
// Code for case 2
break;
default:
// Default case
For Loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
int[] numbers = {1, 2, 3, 4, 5}; // Array declaration
System.out.println(numbers[0]); // Accessing array element
Method Declaration:
public static returnType methodName(parameter1, parameter2) {
// Method body
return value;
}
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println(result);
}
Class Declaration:
class Person {
String name;
int age;
void display() {
System.out.println("Name: " + name);
}
}
Person p1 = new Person();
p1.name = "John";
p1.age = 30;
p1.display();
Constructor Example:
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("John", 30);
p1.display();
}
}
Extending a Class:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited method
d.bark(); // Dog method
}
}
Method Overriding:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Animal a = new Dog(); // Parent class reference, child class object
a.sound(); // Calls Dog's overridden method
Declaring an Interface:
interface Animal {
void eat();
}
class Dog implements Animal {
public void eat() {
System.out.println("Dog is eating");
}
}
public class Main {
public static void main(String[] args) {
Animal d = new Dog();
d.eat();
}
}
Try-Catch Block:
try {
// Code that may throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This block is always executed");
}
public static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be 18 or older");
}
}
ArrayList:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Accessing element
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map.get("Apple")); // Accessing value
Reading from a File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("filename.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("filename.txt");
writer.write("Hello, World!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Creating a Thread by Extending Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
16.Generics
Generic Method:
public class Main {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
printArray(intArray);
}
}