Skip to content

Instantly share code, notes, and snippets.

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 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]
boolean isOdd;
int num = 7;
isOdd = (num%2==1) ? true : false;
System.out.println(isOdd);
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");
// 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 (+,-,*,/)");
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));
// 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());
// Program to perform Type Casting in Java
int num = 1000;
// Leads to loss of information
byte narrowCasting = (byte) num;
// No loss of information
double wideCasting = (double) num;
System.out.println("Original integer : " + num); // Prints 1000
// Code to show different primitive data types in Java
boolean isStudent = true;
short age = 22;
long stipend = 50000;
char section = 'D';
System.out.printf("The details are: %b, %d, %d %c", isStudent, age, stipend, section);
package com.invictalabs.helloworld;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}