Skip to content

Instantly share code, notes, and snippets.

// Strings can be null
String string = null;
System.out.println(string);
// Strings are immutable i.e. their value once set cannot be changed;
string = "This is a string.";
System.out.println(string);
// String class also has some helpful functions
System.out.println(string.toUpperCase());
Integer integer = null;
System.out.println(integer);
// Integer objects are immutable and should be
// initialized using the valueOf method
integer = Integer.valueOf(10);
System.out.println(integer);
System.out.println(integer.equals(11));
// Program to perform mathematical operations on two numbers
double num1,num2;
String operation;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number");
num1 = scanner.nextDouble();
System.out.println("Enter second number");
num2 = scanner.nextDouble();
System.out.println("Enter the operation to perform (+,-,*,/)");
int input;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the code for the day of the week (1-7)");
input = scanner.nextInt();
switch(input) {
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
boolean isOdd;
int num = 7;
isOdd = (num%2==1) ? true : false;
System.out.println(isOdd);
// Program to add and edit names in a list
// ArrayList implements the List interface and are mutable
ArrayList<String> names = new ArrayList<>(List.of("Rahul", "Virat", "Sourav"));
// Elements can be added or removed from an ArrayList
names.add("Rohit");
// This prints the elements of the list
System.out.println(names); // [Rahul, Virat, Sourav, Rohit]
int [] ages = new int[5];
for(int i=0;i<5;i++) {
ages[i] = 20 + i;
}
for(int age:ages) { // 20 21 22 23 24
System.out.printf(age + " ");
}
System.out.println(); // new line
// Program to return average of numbers
public static double doAverage(ArrayList<Integer> marks) {
// double for more precision than Integer during division
double avg = 0.0;
for(int mark: marks) {
avg += mark;
}
// size() method returns the number of elements in array
avg = avg/marks.size();
// Extends Object Class by default
public class Animal {
public static enum FoodHabits{
CARNIVORE(0), HERBIVORE(1), OMNIVORE(2);
private int index;
public int getIndex() {
return index;
public class Tiger extends Animal {
// All data members are inherited from Animal class
// We specify additional data member specific to Tiger
String tigerSpecies;
String lastPrey;
public Tiger(int age, String tigerSpecies) {
// the constructor for the superclass must be defined
// super() must be the first line in the constructor of base class