Author : MD TAREQ HASSAN | Updated : 2023/10/25
First program
Hello world:
namespace PracticeXyz
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Simple user input:
namespace PracticeXyz
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter some text: ");
string userInput = Console.ReadLine() ?? "nothing";
Console.WriteLine("You entered: " + userInput);
}
}
}
Hello world:
"use strict";
function main(){
console.log("Hello, World!");
alert("Hello, World!");
}
main();
Simple user input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple user input</title>
</head>
<body>
<input type="text" id="user-input-field" value="Hovermind">
<script>
"use strict";
function main() {
let userInputFiled = document.getElementById("user-input-field");
let userInputText = userInputFiled.value;
console.log("You entered: " + userInputText);
//alert("You entered: " + userInputText);
}
main();
</script>
</body>
</html>
Hello world:
let message: string = "Hello, World!";
console.log(message);
// Commands:
// tsc program.ts
// node program.js
Hello world:
print("Hello, World!")
Simple user input:
userInput = input("Enter some text: ")
print("You entered: " + userInput)
Hello world:
package com.company.practicexyz;
public class Program {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Simple user input:
package com.company.practicexyz;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter some text: ");
String userInput = scanner.nextLine();
System.out.println("You entered: " + userInput);
scanner.close();
}
}
Print syntax:
// Same line (no newline at end)
Console.Write("Same");
Console.Write(" Line");
// "Same Line"
// Newline at end
Console.WriteLine("Part 1");
Console.WriteLine("Part 2");
/*
"Part 1"
"Part 2"
*/
Newline and tab:
// Newline '\n'
Console.WriteLine("Part1\nPart2");
/*
"Part1
Part2"
*/
// Tab '\t'
Console.WriteLine("Part1\tPart2");
// "Part1 Part2"
Print syntax:
// Newline at end
console.log("Part 1");
console.log("Part 2");
/*
"Part 1"
"Part 2"
*/
Newline and tab:
// Newline '\n'
console.log("Part1\nPart2");
/*
"Part1
Part2"
*/
// Tab '\t'
console.log("Part1\tPart2");
// "Part1 Part2"
Print syntax:
// Newline at end
console.log("Part 1");
console.log("Part 2");
/*
"Part 1"
"Part 2"
*/
Newline and tab:
// Newline '\n'
console.log("Part1\nPart2");
/*
"Part1
Part2"
*/
// Tab '\t'
console.log("Part1\tPart2");
// "Part1 Part2"
Print syntax:
# Newline at end
print("Part 1")
print("Part 2")
"""\
"Part 1"
"Part 2"
"""
Newline and tab:
# Newline '\n'
print("Part1\nPart2");
"""\
"Part1
Part2"
"""
# Tab '\t'
print("Part1\tPart2");
# "Part1 Part2"
Print syntax:
// Same line (no newline at end)
System.out.print("Same");
System.out.print(" Line");
// "Same Line"
// Newline at end
System.out.println("Part 1");
System.out.println("Part 2");
/*
"Part 1"
"Part 2"
*/
Newline and tab:
// Newline '\n'
System.out.println("Part1\nPart2");
/*
"Part1
Part2"
*/
// Tab '\t'
System.out.println("Part1\tPart2");
// "Part1 Part2"
Comment
Single line comment:
// this is a single line comment in C#
// xyz
Multiline comment:
/*
this is a multiline comment in C#
xyz
*/
/*
* another multiline comment
* in C#
*/
Single line comment:
// this is a single line comment in JavaScript
// xyz
Multiline comment:
/*
this is a multiline comment in JavaScript
xyz
*/
/*
* another multiline comment
* in JavaScript
*/
Single line comment:
// this is a single line comment in TypeScript
// xyz
Multiline comment:
/*
this is a multiline comment in TypeScript
xyz
*/
/*
* another multiline comment
* in TypeScript
*/
Single line comment:
# this is a single line comment in python
# Xyz
Multiline comment:
# Python does not have multi-line comment
#
# Single line comment as multi-line comment
# Bla bla bla
#
# docstring comment as multi-line comment
# to avoid new line after """, use '\'
"""\
This is an example
of using multi-line docstring comment as multi-line comment
in Python
"""
Single line comment:
// this is a single line comment in Java
// xyz
Multiline comment:
/*
this is a multiline comment in Java
xyz
*/
/*
* another multiline comment
* in Java
*/
Data type and variable
Declaring variable:
// format: <data type> <variable name> = <intial value>;
int count = 0;
string name = "";
bool isValid = false;
Data types:
Built-in value types (known as primitive types): byte, sbyte, short, ushort, int, uint, long, ulong, float, double, decimal, bool, char
Built-in reference types: object, string, dynamic
To get type of a variable: .GetType()
int unknownVal = 0;
// .GetType().Name
// .GetType().FullName
if (unknownVal.GetType() == typeof(int))
{
Console.WriteLine($"unknownVal is {unknownVal.GetType().Name}"); // Int32
}
Type suffix:
uint personCount = 0U;
long bigNumber = 0L;
ulong bigPositiveNumber = 0UL;
float rectangleArea = 0.0F;
double circleArea = 0.0D;
decimal highPrecisionArea = 0.0M;
Default value:
// When creating a variable, always assign intial or default value
int x = default; // Using 'default' keyword
// Using literal
int wholeNumber = 0;
uint deviceCount = 0U;
float rectangleArea = 0.0F;
double circleArea = 0.0D;
decimal highPrecisionArea = 0.0M;
bool isValid = false;
char flag = '\0';
string name = "";
Type inference:
// `var` keywaord is used for type inference, data type is inferred from the assigned value
var count = 0; // 'int' type is inferred from value '0'
var rectangleArea = 0.0F; // 'float' type is inferred from value '0.0F'
var circleArea = 0.0D; // 'double' type is inferred from value '0.0D'
var highPrecisionArea = 0.0M; // 'decimal' type is inferred from value '0.0M'
var flag = '\0'; // 'char' type is inferred from value '\0'
var name = "Hassan"; // 'string' type is inferred from value "Hassan"
// Implicitly typed variables must be initialized with proper value
var str = null; // invalid, compiler can't figure out type of str
var str = (string) null; // compiler can infer type of 'str' variable as 'string', and assigned value is null
Declaring variable:
// format: let <variable name> = <intial value>;
let count = 0;
let name = "";
let isValid = false;
Data types:
To get the value of a variable: typeof(x)
(also there is an operator: typeof x
)
// string
let name = "";
// number : integer or double (always 64 bit)
let count = 0;
let circleArea = 0.0;
// bigint: more than 64 bit whole number, created by appending 'n' to the end of an integer
let bigNumber = 100n;
// boolean
let isValid = false;
// symbol: unique and immutable data type to be used as an identifier for object properties
let foo = Symbol();
console.log(typeof(foo)); // object
typeof(foo) === "symbol"; // true
// undefined: this data type represents value that is not assigned (a variable is declared but the value is not assigned)
// a variable without a value, has the value undefined. The type is also undefined.
let x;
console.log(x); // undefined
console.log(typeof(x)); // undefined
// null: a special value which represents nothing or empty
let x = null;
console.log(x); // null
console.log(typeof(x)); // object (it's a bug in js)
// non-primitive data type: object
const person = {
firstName: "MD TAREQ",
lastName: "HASSAN",
};
console.log(typeof(person)); // object
console.log(typeof(Math)); // object
Declaring variable:
// format: let <variable name>: <data type> = <intial value>;
let roll: number = 0;
let name: string = "";
let isValid: boolean = false;
Data types:
To check type of a variable: typeof x
(it’s an operator, not function typeof(x))
// string
let fullName: string = "";
// number
let roll: number = 0;
let circleArea: number = 0.0;
let hex: number = 0xf00d;
let binary: number = 0b1010;
// bigint
let bigNumber: bigint = 100n;
console.log(typeof(bigNumber)); // bigint
// boolean
let isValid: boolean = false;
// symbol
let foo: symbol = Symbol("foo");
console.log(typeof(foo)); // symbol
// undefined
let x;
console.log(x); // undefined
console.log(typeof(x)); // undefined
// null
let y = null;
console.log(y); // null
console.log(typeof(y)); // object (it's a bug in js)
/*
never use the following types:
- any
- unknown
- never
*/
// non-primitive data type: object
const person = {
firstName: "MD TAREQ",
lastName: "HASSAN",
};
console.log(typeof(person)); // object
console.log(typeof(Math)); // object
Declaring variable:
# format: <variable name>: <type> = <intial value>
count: int = 0
name: str = ""
isValid: bool = False
Data types:
To check type of a variable: type(x)
# str
name: str = ""
# int
count: int = 0
# float
area: float = 0.0
# complex
imaginaryNumber: complex = 1 + 2j
print(imaginaryNumber) # (1+2j)
# bytes
nihongo: bytes = b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'
print(nihongo.decode('utf-8')) # 日本語
# print("日本語".encode('utf-8')) # b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'
# print(b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'.decode('utf-8')) # 日本語
# bool
isDone: bool = False
# get type of a variable: type()
circleRadius: int = 5
circleArea: float = circleRadius * 3.1416
print(f"type of circleRadius: {type(circleRadius)}") # <class 'int'>
print(f"type of circleArea: {type(circleArea)}") # <class 'float'>
Type inference:
name = ""
print(type(name)) # <class 'str'>
count = 0
print(type(count)) # <class 'int'>
area = 0.0
print(type(area)) # <class 'float'>
isDone = False
print(type(isDone)) # <class 'float'>
nihongo = b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e'
print(type(nihongo)) # <class 'bytes'>
Declaring variable:
// Format: <data type> <variable name> = <intial value>;
int count = 0;
String name = "";
boolean isValid = false;
Data types:
Built-in value types (known as primitive types): byte, short, int, long, float, double, char, boolean
Built-in reference types: Object, String
To get type of a variable: x.getClass().getSimpleName()
(wrap primitive types into wrapper class to use .getClass()
)
Type suffix:
long bigNumber = 0l; // long
float rectangleArea = 0.0f; // float
double circleArea = 0.0d; // double
Default value:
// When creating a variable, always assign intial or default value
byte cssColorCode = 0;
int wholeNumber = 0;
long bigNumber = 0L;
float rectangleArea = 0.0f;
double circleArea = 0.0d;
boolean isValid = false;
char flag = '\0';
String name = "";
Type inference:
// Java 10+: there is 'var' keyword for type inference of local variables (use only for primitive types and string)
var count = 10;
var area = 0.0f;
var name = "";
var isDone = false;
Character
Character type variable:
char ch = '\0';
var jChar = 'j'; // char literal
var jCharFromInt = (char) 106; // 'j', from int value
Conversion to string:
Character to string
// interpolation
char ch = 'x';
string str = $"{ch}";
// string constructor
string str = new string(new char[] { 'x' });
// ToString()
char ch = 'x';
var str = ch.ToString();
// when char is int val
var val = 120;
string str = Char.ConvertFromUtf32(val); // x
String to character
string str = "Hello";
char[] characters = str.ToCharArray();
// readonly indexer of string
var str = "hovermind";
var firstChar = str[0]; // h
Conversion to integer:
Character to integer
var ch = 'x';
var val = (int)ch;
Console.WriteLine(val); // 120
integer to character
int val = 120;
char ch = Convert.ToChar(val);
Console.WriteLine(ch); // x
Character code escape sequence:
// unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code
char jCharFromUnicode = '\u006A'; // 'j'
string jStrFromUnicode = "\u006A"; // "j"
// hexadecimal escape sequence, which is \x followed by the hexadecimal representation of a character code.
char jCharFromHex = '\x006A'; // 'j'
string jStrFromHex = "\x006A"; // "j"
Character type variable:
// single letter string as character
let ch = "\0";
let jChar = "j";
// "j" from int value
let jCharFromInt = String.fromCharCode(106);
Character code escape sequence:
// unicode escape sequence, which is backslash u followed by the four-symbol hexadecimal representation of a character code
let jStrFromUnicode = "\u006A"; // "j"
// hexadecimal escape sequence, which is \x followed by hexadecimal (no leading zeros) representation of a character code.
let jStrFromHex = "\x6A"; // "j"
Character type variable:
// single letter string as character
let ch: string = "\0";
let jChar: string = "j";
// "j" from int value
let jCharFromInt: string = String.fromCharCode(106);
Character code escape sequence:
// unicode escape sequence, which is backslash u followed by the four-symbol hexadecimal representation of a character code
let jStrFromUnicode: string = "\u006A"; // "j"
// hexadecimal escape sequence, which is \x followed by hexadecimal (no leading zeros) representation of a character code.
let jStrFromHex: string = "\x6A"; // "j"
Character type variable:
# since there is no character type in python, str of length 1 will be used as character
ch: str = "\0"
jChar: str = "j" # char literal
jCharFromInt: str = chr(106) # 'j' from int value
Character code escape sequence:
# unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code
jStrFromUnicode: str = "\u006A"; # "j"
# hexadecimal escape sequence, which is \x followed by the hexadecimal representation of a character code.
jStrFromHex: str = "\x6A"; # "j"
print(jStrFromUnicode)
print(jStrFromHex)
Character type variable:
char ch = '\0';
char jChar = 'j'; // char literal
char jCharFromInt = (char) 106; // 'j', from int value
Character code escape sequence:
// unicode escape sequence, which is backslash u followed by the four-symbol hexadecimal representation of a character code
char jCharFromUnicode = '\u006A'; // 'j'
String jStrFromUnicode = "\u006A"; // "j"
String
String syntax:
// literal string
string sampleText = "This is a string";
// empty string
var emptyStr = "";
var emptyText = String.Empty; // zero-length string ""
String constructor:
// Create a string from a character array
char[] chars = { 'w', 'o', 'r', 'l', 'd' };
string text = new string(chars);
// Create a string that consists of a character repeated 20 times.
string textWithSameChar = new string('c', 20);
Verbatim string:
// use '@' to create verbatim string (no need to use escape character)
var path = @"c:\test\foo.txt"; // rather than "c:\\test\\foo.txt"
// multiline verbatim string
var html = @"
<div>
<h1>Title</h1>
<p>xyz</p>
</div>
";
Console.WriteLine($"html: {html}");
Raw string:
// single line raw string
var rawStr = """Raw text, which includes ", ' & other literals i.e. / \ etc.""";
Console.WriteLine($"rawStr: {rawStr}");
// multiline raw string
var rawStrMultiline = """
Everything between the quotes is literally interpreted,
no need for escaping of anything.
some html:
<h1>xyz</h1>
""";
Console.WriteLine($"rawStrMultiline: \n{rawStrMultiline}");
Multiline string:
use verbatim string (@
) & raw string to get multiline string
String syntax:
// literal string
let sampleText = "This is a string";
// empty string
let emptyStr = "";
String constructor:
let text = "hovermind.com";
let textObject = new String(text);
console.log(`type of text: ${typeof(text)}`);
console.log(`type of textObject: ${typeof(textObject)}`);
Verbatim string:
// js does have verbatim string, use raw string for verbatim string
// raw string as verbatim string:
let filePath = String.raw`C:\test\foo.txt`; // no escape required
Raw string:
// single line raw string
let rawStr = String.raw`Unicode for letter 'j' is \u006A`
console.log(`rawStr: ${rawStr}`);
// multiline raw string
let html = String.raw`
<div>
<h1>Title</h1>
<p>xyz</p>
</div>
`;
console.log(`html: ${html}`);
// raw string with interpolation
let hassan = "HASSAN";
let message = String.raw`Hello /\ ${hassan} /\ :)`;
console.log(`message: ${message}`);
Multiline string:
use template string (backticks “`xyz`”) & raw string to get multiline string
String syntax:
// literal string
let sampleText: string = "This is a string";
// empty string
let emptyStr: string = "";
// interpolated string
let x: number = 10;
let interpolatedStr: string = `Value of x is ${x}`;
console.log(interpolatedStr);
//tsc program.ts; node program.js
String constructor:
let text: string = "hovermind.com";
let textObject: object = new String(text);
console.log(`type of text: ${typeof(text)}`);
console.log(`type of textObject: ${typeof(textObject)}`);
//tsc program.ts; node program.js
Verbatim string:
// ts does have verbatim string, use raw string for verbatim string
// raw string as verbatim string:
let filePath: string = String.raw`C:\test\foo.txt`; // no escape required
//tsc program.ts; node program.js
Raw string:
// single line raw string
let rawStr: string = String.raw`Unicode for letter 'j' is \u006A`
console.log(`rawStr: ${rawStr}`);
// multiline raw string
let html: string = String.raw`
<div>
<h1>Title</h1>
<p>xyz</p>
</div>
`;
console.log(`html: ${html}`);
// raw string with interpolation
let hassan: string = "HASSAN";
let message: string = String.raw`Hello /\ ${hassan} /\ :)`;
console.log(`message: ${message}`);
//tsc program.ts; node program.js
Multiline string:
use template string (backticks “`xyz`”) & raw string to get multiline string
String syntax:
# literal string
sampleText: str = "This is a string"
# empty string
emptyStr: str = ""
String constructor:
# create a string from a list of character
chars: list = ["w", "o", "r", "l", "d"] # python does not have character type, use single ltter string
text: str = str("".join(chars))
print(text) # world
# converting other types to string
area: float = 13.675
areaText: str = str(area)
print(type(areaText)) # <class 'str'>
print(areaText) # "13.675"
Verbatim string:
# python does not have verbatim string, use raw string as verbatim string
filePath: str = r"C:\test\foo.txt" # no need to escape
print(filePath)
Raw string:
# single line raw string
rawStr: str = r"Raw text, which can include many things i.e. / \ etc."
print(rawStr)
# multiline raw string
rawStrMultiline: str = """
Everything between the quotes is literally interpreted,
no need for escaping of anything.
some html:
<h1>xyz</h1>
"""
print(rawStrMultiline)
Multiline string:
use tripple quote ('''
or """
) & raw string to get multiline string
String syntax:
// literal string
String sampleText = "This is a string";
// empty string
String emptyStr = "";
// interpolated string: use String.format() since java does not have string interpolation
int x = 10;
String interpolatedStr = String.format("Value of x is %d", x);
System.out.println(interpolatedStr); // Value of x is 10
String constructor:
// create a string from a character array
char[] chars = { 'w', 'o', 'r', 'l', 'd' };
String text = new String(chars);
System.out.println(text); // world
// create a string that consists of a character repeated n times.
String repeated = new String(String.valueOf('*').repeat(5));
System.out.println(repeated); // output: *****
Verbatim string:
Java does not have verbatim string
Raw string:
Java does not have raw string (use escape characters)
Multiline string:
// java has block text (triple quote), escape characters will work as in normal string
String blockText = """
This is java
block text,
we can use ", ', /, :)
""";
System.out.println(blockText);
String html = """
<div>
<h1>Title</h1>
<p>xyz</p>
</div>
""";
System.out.println(html);
String interpolation
Basic interpolation:
string wld = "World";
Console.WriteLine($"Hello, {wld}!"); // Hello, World!
var mobileNumber = 07056670111;
var interpolatedStr = $"Mobile number is {mobileNumber}";
Console.WriteLine(interpolatedStr); // "Mobile number is 7056670111"
Interpolation for verbatim string:
var folder = @"C:\test";
var file = "foo.txt";
var filePath = $@"{folder}\{file}"; // interpolated verbatim string
Console.WriteLine($"filePath: {filePath}"); // filePath: C:\test\foo.txt
Interpolation for raw string:
var name = "MD TAREQ HASSAN";
// the number of times '$' will be used ==> the number of times "{}" will be used to interpolate
var rawStrInterpolated = $$"""
{
"FullName": ""
}
""";
Console.WriteLine($"json: \n{rawStrInterpolated}");
Format specifier:
Standard numeric
var amount = 15.751503D;
// C => Currency
Console.WriteLine($"Cash: {amount:C}"); // amount: $15.75
Console.WriteLine($"Cash: {amount:C4}"); // amount: $15.7515
Console.WriteLine($"Cash: {amount:C6}"); // amount: $15.751503
Console.WriteLine($"Cash: {amount:C8}"); // amount: $15.75150300
// N => Numeric
Console.WriteLine($"Cash: {amount:N}"); // amount: 15.75
Console.WriteLine($"Cash: {amount:N4}"); // amount: 15.7515
// P => Percent
Console.WriteLine($"Percent: {amount:P}"); // Percent: 1,575.15%
Console.WriteLine($"Percent: {amount:P4}"); // Percent: 1,575.1503%
var number = 14;
// X => Hexadecimal
Console.WriteLine($"Hex: {number:X}"); // Hex: E
Console.WriteLine($"Hex: {number:X4}"); // Hex: 000E
// More format specifiers: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Standard date and time
DateTime now = DateTime.UtcNow;
Console.WriteLine($"Date: {now:G}");
Console.WriteLine($"Long date: {now:U}");
Console.WriteLine($"Time: {now:T}");
// More format specifiers: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Basic interpolation:
// `${}`
let wardCount = 23;
let capital = "Tokyo";
let message = `There are ${wardCount} special wards in ${capital}`;
console.log(message); // There are 23 special wards in Tokyo
Format specifier:
/*
js does not have format specifiers
workaround:
- Intl.NumberFormat
- Number.toLocaleString()
*/
let amount = 175;
let ratio = 0.073;
// Intl.NumberFormat -> currentcy
const currencyFomatter = new Intl.NumberFormat('ja-JP', {
style:'currency',
currency: 'JPY'
});
console.log(currencyFomatter.format(amount)); // ¥175
// Intl.NumberFormat -> percent
const percentFomatter = new Intl.NumberFormat('en-US', {
style:'percent',
maximumFractionDigits: 1,
signDisplay: "always"
});
console.log(percentFomatter.format(ratio)); // +7.3%
// Number.toLocaleString()
let amountStr = amount.toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
});
console.log(amountStr); // $175.00
Basic interpolation:
// `${}`
let wardCount: number = 23;
let capital: string = "Tokyo";
let message: string = `There are ${wardCount} special wards in ${capital}`;
console.log(message); // There are 23 special wards in Tokyo
Format specifier:
/*
js String does not have format() function, therefore TypeScript String also doe not have format() function
use template string (`${}`) to get desired output
*/
let amount: number = 12.75;
let price: string = `$${amount}`;
console.log(price); // $12.75
Basic interpolation:
wld: str = "World"
print(f"Hello, {wld}!") # Hello, World!
mobileNumber: int = 7056670111
interpolatedStr: str = f"Mobile number is {mobileNumber}"
print(interpolatedStr) # "Mobile number is 7056670111"
# using format_map() and locals()
everyone: str = "all"
coder: str = "programmer"
print("Hello {everyone}!, I am a {coder}.".format_map(locals())) # Hello all!, I am a programmer.
Interpolation for raw string:
folder: str = r"C:\test"
fileName: str = "foo.txt"
filePath: str = rf"{folder}\{fileName}" # no need to escape since 'r' flag is being used, 'f' for interpolation
print(filePath) # C:\test\foo.txt
Format specifier:
testNum = 123456789
testFloat = 7141.6247234
PI = 3.1416247234
# hex
print(f"Hex: {testNum : x}")
print(f"Hex with notation: {testNum :#x} \n")
# binary
print(f"Binary: {testNum : b}")
print(f"Binary with notation: {testNum :#b} \n")
# separator ","
print(f"Comma separated: {testNum :,}")
print(f"PI precision to 4th place: {PI :.5}")
# currency formatting
amount: float = 12.75314
currency: str = "${:,.2f}".format(amount)
print(currency) # $12.75
# date formatting
import datetime
test_date = datetime.datetime(2017, 10, 2, 16, 30, 0)
print(f"{test_date :%Y-%m-%d %H:%M:%S}")
Basic interpolation:
/*
Java lacks native support for String interpolation
workaround:
- String.format()
- MessageFormat.format()
*/
// String.format()
String wld = "World";
String message = String.format("Hello, %s!", wld);
System.out.println(message); // Hello, World!
// MessageFormat.format()
int wardCount = 23;
String capital = "Tokyo";
String msg = MessageFormat.format("There are {0} special wards in {1}", wardCount, capital);
System.out.println(msg); // "There are 23 special wards in Tokyo"
Format specifier:
// Java does not have format specifier
// workaround: use String.format() with flags
// Number
float number = 15.753721f;
System.out.println(String.format("number: %4.2f", number));
System.out.println(String.format("number: %5.3f", number));
System.out.println(String.format("number: %6.4f", number));
// Currency
float amount = 235.753721f;
System.out.println(String.format("price: $%4.2f", amount));
System.out.println(String.format("price: %4.2f円", amount));
// Currency with NumberFormat
NumberFormat jpnLocale = NumberFormat.getCurrencyInstance(Locale.JAPAN);
String jpyCurrency = jpnLocale.format(120.75d);
System.out.println(jpyCurrency);
// Date & Time
Date date = new Date();
System.out.println(String.format("date: %1$ty.%1$tm.%1$td", date)); // 1$ -> parameter index
System.out.println(String.format("time: %1$tH:%1$tM:%1$tS", date));
System.out.println(String.format("date & time: %1$ty.%1$tm.%1$td %1$tH:%1$tM:%1$tS", date));
Nullable type
Nullable variable:
// nullable value type
int? flag = null;
bool? isDone = null;
int?[] unknownInputs = new int?[10]; // An array of a nullable value type:
// nullable reference type
string? commentOne = null;
string? commentTwo = "That was great!";
if (commentTwo != null)
{
Console.WriteLine($"comment text 2: {commentTwo!}"); // ! => null forgiving ((I am sure it has value)
}
string commentText = commentOne!; // ! => exception will be thrown since commentOne is null
Default value:
// The default value of a nullable type is "null"
int?[] unknownInputs = new int?[10];
var defaultValue = (unknownInputs[0] == null) ? "null" : $"{unknownInputs[0]}";
Console.WriteLine($"default value of unknownInputs[0] => {defaultValue}"); // default value of unknownInputs[0] => null
Using nullable variable:
//
// null-coalescing operator
//
int? number = null;
var currentNumber = number ?? 1; // null-coalescing
Console.Write($"Current number => {currentNumber}");
Console.WriteLine("\n");
/*
.HasValue and .value
--------------------
Nullable<T>.HasValue: indicates whether an instance of a nullable value type has a value of its underlying type
Nullable<T>.Value: gets the value of an underlying type if HasValue is true. If HasValue is false, the Value property throws an InvalidOperationException
*/
int? flag = null;
Console.Write("Does flag have value?: ");
if (flag.HasValue)
{
Console.Write($"YES => {flag.Value}");
}
else
{
Console.Write("NO");
}
Console.WriteLine();
flag = 1;
Console.Write("Does flag have value?: ");
if (flag.HasValue)
{
Console.Write($"YES => {flag.Value}");
}
else
{
Console.Write("NO");
}
Console.WriteLine("\n");
//
// Nullable<T>.GetValueOrDefault(T)
//
int? count = null;
Console.WriteLine($"GetValueOrDefault(T) for count => {count.GetValueOrDefault()}");
bool? isValid = null;
Console.WriteLine($"GetValueOrDefault(T) for isValid => {isValid.GetValueOrDefault()}");
decimal? unknownPrice = null;
Console.WriteLine($"GetValueOrDefault(T) for unknownPrice => {unknownPrice.GetValueOrDefault()}");
decimal? unknownChar = null;
Console.WriteLine($"GetValueOrDefault(T) for unknownChar => {unknownChar.GetValueOrDefault()}");
NOT Supported
Nullable variable:
// TypeScript does not support nullable type
// Workaround: create type alias with
// NOTE: optional type in TypeScript is different than nullable type
// create nullable type (type alias with union)
type Nullable<T> = T | null;
// usage
interface Employee{
id: number;
salary: Nullable<number>;
}
Nullable variable:
# python does not have nullable type, use Optional[T]
from typing import Optional
name: Optional[str] = None
id: Optional[int]
# Optional return type
def getDatetime(arg: int = None) -> Optional[datetime]:
# body
Nullable variable:
/*
Nullable type in java:
* For built-in value types (primitive types): does not support nullable type
* For reference types: can have null value by default
*/
// int? unknownCount = null => not possible
String unknownText = null; // ok
/*
Primitive wrapper class in Java:
For each primitive type, there is a wrapper class which is reference type can have null value
*/
Integer unknownCount = null; // ok
/*
Optional<T>: T indicates reference types including primitive wrapper classes
It is a value-based Class (https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html)
*/
Optional<Integer> unknownCount = Optional.empty();
if (unknownCount.isEmpty()) {
System.out.println("unknownCount => empty");
}
unknownCount = Optional.of(5);
if (unknownCount.isPresent()) {
System.out.println("unknownCount => " + unknownCount.get());
}
Type casting
Implicit casting:
/*
Implicit Casting:
A type of type casting that happens automatically.
There is no data loss involved.
*/
int initialCount = 305275757;
long count = initialCount; // implicitly converted, no data is lost
Explicit casting:
/*
Explicit Casting:
A type of type casting that requires the programmer to explicitly specify the conversion from one data type to another.
Data loss might occur.
*/
double length = 1234.56;
int len = (int) length; // data is lost by explicitly casting (1234.56 -> 1234)
Type casting operator:
// To avoid exception: use `is` & `as` operator
if (myObject is Foo)
{
Foo foo = myObject as Foo;
}
string hassan = "Hassan";
object obj = (hassan as object);
Convert class:
var intString = "123"
// Convert class method
var intVal = Convert.ToInt32(intString);
// https://learn.microsoft.com/en-us/dotnet/api/system.convert?
Try parse:
int outVar;
string intAsString = "10";
// TryParse()
Int32.TryParse(intAsString, out outVar);
Console.WriteLine($"outVar => {outVar}");
Implicit casting:
/*
Implicit Casting:
JavaScript tries to convert one data type to another automatically.
Altough, js tries to cast/convert to the right type by itself, the result is sometimes unexpected or might be wrong
*/
/*
Implicit Conversion to String
JavaScript converts anything to a string before concatenation
*/
let str = "";
str = "5" + 2; // "52"
str = "5" + true; // "5true"
str = "5" + undefined; // "5undefined"
str = "5" + null; // "5null"
/*
Implicit Conversion to Number
js tries to convert both operands to number before performing any math operation
*/
let result = 0;
result = "5" - "2"; // 3
result = "5" - 2; // 3
result = "5" * 2; // 10
result = "5" / 2; // 2.5
result = 'hello' - 'world'; //NaN (not a number)
result = '4' - 'hello'; // NaN
result = 5 + true; // 6 (js tries to conver true to number, true becomes 1)
result = 5 - false; // 5 (js tries to conver false to number, false becomes 0)
Explicit casting:
/*
Explicit Casting:
explicit type conversions are done using built-in methods i.e. Number(), toString(), Math.floor()
*/
// to number
let result = 0;
result = Number("543"); // 543
result = Number('543e-1'); 54.3
result = Number(true); // 1
result = Number(false); // 0
result = Number(" ") // 0
result = Number('hello'); //
result = Number(null); // 0
result = Number(undefined); // NaN
result = Number(NaN); // NaN
result = Math.floor("15.03"); // 15
// to string
let str = "";
str = String(543); // "543"
str = String(true); // "true"
str = String(null); // "null"
str = String(undefined); // "undefined"
str = String(NaN); // "NaN"
str = (543).toString(); // "543"
str = true.toString(); // "true"
// to boolean
let truthyVal = "tt";
Boolean(truthyVal); // true
Boolean(55); // true
let falsyVal = "";
Boolean(falsyVal); // false
Boolean(0); // false
Implicit casting:
const PI: number = 3.1416;
let circleArea: number = PI * 5; // integer "5" is coerced into a float to perform math operation, then returns a float (number) as the result
console.log(circleArea); // 15.708
Explicit casting:
// <> operator is used for explicit casting (implicit casting is not possible in TypeScript)
let text: unknown = "Hello";
console.log((<string> text).length); // 5
Type casting operator:
// casting using 'as' keyword
let text: unknown = "Hello";
console.log((text as string).length); // 5
Implicit casting:
# Implicit casting:
# int * float = float (Python coerces the int into a float to perform operation, then returns a float as the result)
PI: float = 3.1416
circleRadius: int = 5
circleArea: float = circleRadius * PI
print(f"type of PI: {type(PI)}")
print(f"type of circleRadius: {type(circleRadius)}")
print(f"circleArea = {circleArea}")
print(f"type of circleArea: {type(circleArea)} (PI:{type(PI)} * Radius:{type(circleRadius)})")
Explicit casting:
# Explicit casting using constructor function i.e. int(), float(), str() etc.
# int => float
intVal: int = 5;
print(float(intVal)) # 5.0
# float => int
# The int() function will truncate, not round
# The int() function truncates negative numbers towards 0. It’s a true truncate function, not a floor function
floatVal: float = 5.73
print(int(floatVal)) # 5
print(int(0.573)) # 0
# str => int
# int("<whole number>" [, base])
# "<whole number>" => string representation of a whole number, there will be error if non int number is used
intStr: str = "5"
print(int(intStr, 10)) # 5
print(int(intStr)) # 5
print(int("5.73")) # ValueError: invalid literal for int() with base 10: '5.73'
# str => float
floatStr: str = "5.7"
print(float(floatStr)) # 5.7
# str => float => int
print(int(float(floatStr))) # 5
# int, float => str
intValStr: int = str(5) # "5"
floatValStr: str = str(5.73) #"5.73"
Type casting operator:
# is keyword: to test if the two variables refer to the same object
[] == [] # True
[] is [] # False
{} == {} # True
{} is {} # False
# as keyword: to create an alias while importing a module
import math as mathAlias
mathAlias.cos(mathAlias.pi)
Implicit casting:
/*
* Implicit casting: when the conversion is automatically performed by the compiler without the programmer's interference, it is called implicit type casting
* Normally, during implicit casting no data loss happens: byte -> short -> char -> int -> long -> float -> double
*/
int intVal = 15;
double wideVal = intVal; // implicit casting, no data loss
Explicit casting:
/*
* Explicit casting: when the conversion is not automatic (compiler shows error since data loss might occur), we need to cast/convert manually or forcefully
* Normally, during explicit casting data loss will occur: double -> float -> long -> int -> char -> short -> byte
*/
double lengthInMillimeter = 12.375d;
// int intVal = wideVal; // Error: cannot convert from double to int
int intVal = (int) lengthInMillimeter; // explicit casting, data loss
System.out.println(intVal); // 12
Try parse:
// String to numeric
String intValStr = "15";
int intVal = Integer.parseInt(intValStr);
System.out.println(intVal); // 15
// Numeric to string
double doubleVal = 13.75d;
String doubleStr = String.valueOf(doubleVal);
System.out.println(doubleStr); // "13.75"
Constant
Constant syntax:
const float PI = 3.2426f;
const double G = 6.67430e-11; // GRAVITATIONAL CONSTANT
const double NATUAL_LOG = Math.E; // NATUAL LOG 'e'
Console.WriteLine(NATUAL_LOG);
Readonly:
// readonly variable can be assigned only once (declaration time, in constructor or in static constructor)
// readonly fields are not the same as const variables, as const variables are evaluated at compile-time, while readonly fields are evaluated at run-time
public readonly int age = 32;
class Foo
{
private readonly int bar;
Foo(int bar)
{
this.bar = bar;
}
}
// while a const field is a compile-time constant,
// the readonly field can be used for runtime constants as in the following example:
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
Constant syntax:
const PI = 3.2426;
const G = 6.67430e-11; // GRAVITATIONAL CONSTANT
const NATUAL_LOG = Math.E; // NATUAL LOG 'e'
console.log(NATUAL_LOG);
Constant syntax:
const PI: number = 3.2426;
const G: number = 6.67430e-11; // GRAVITATIONAL CONSTANT
const NATUAL_LOG: number = Math.E; // NATUAL LOG 'e'
console.log(NATUAL_LOG);
Readonly:
// readonly => to define a property of an object or a variable that can't be reassigned once it's been initialized
interface Person {
readonly name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30
};
person.age = 31; // OK
person.name = "Mary"; // Error: Cannot assign to 'name' because it is a read-only property
Constant syntax:
# the language itself does not have a specific keyword or construct for creating constants
# conventionally, constants are written in all uppercase letters with underscores to separate words
PI: float = 3.14159
HTTP_500: str = "500"
Constant syntax:
final float PI = 3.2426f;
final double G = 6.67430e-11; // GRAVITATIONAL CONSTANT
final double NATUAL_LOG = Math.E; // NATUAL LOG 'e'
System.out.println(NATUAL_LOG);
Operator
Arithmetic operator:
// Addition : +
// Subtraction : -
// Multiplication : *
// Division : /
// Modulo remainder: %
int sum = 10 + 5;
int result = 20 - 3;
float total = 15 * 2;
float costPerPerson = 7 / 2;
int remainder = 5 % 2;
Equality operator:
// Equal to : ==
// Not equal to : !=
bool isTrue = (5 == 4);
bool isCorrect = (5 != 4);
Comparison operator:
// Greater than : >
// Less than : <
// Greater than or equal to : >=
// Less than or equal to : <=
bool isTrue = (5 > 4);
bool isFalse = (5 < 4);
bool isCorrect = (3 >= 2);
bool isRight = (3 <= 2);
Logical operator:
int score = 85;
int count = 5;
bool isCorrect = (score >= 80 && count > 0);
bool isRight = (count >= 10 || score >= 80);
bool isOk = (score != count);
Bitwise operator:
int value = 8;
int flag = 1;
int andResult = (value & flag); // Bitwise AND
int orResult = (value | flag); // Bitwise OR
int xor = (value ^ flag); // Bitwise Exclusive OR (XOR)
int complement = (~flag); // bitwise complement operator
int leftShift = value << 2; // Bitwise Left Shift
int rightShift = value >> 1; // Bitwise Right Shift
Special operator:
// C# special operators
x?.y // safe navigation / conditional access
x?[] // conditional element access
x ?? y // Null-coalescing Operator, returns x if it is not null; otherwise, returns y
/*
default(T) : returns the default initialized value of type T,
null for reference types, zero for numeric types, and zero/null filled in members for struct types
*/
static public T MyGenericMethod<T>(){
T temp = default(T);
return temp;
}
&x // address of 'x'
*x // dereferencing
/*
-> operator combines pointer dereferencing and member access
-> operator can be used only in code that is marked as unsafe
*/
x->y // is equivalent to (*x).y
// typeof
System.Type type = typeof(ref or alias); // same as ref.GetType()
// sizeof: returns the size in bytes of the type operand
int intSize = sizeof(int); // Constant value = 4 (4 bytes)
// is: checks if an object is compatible with a given type
if(obj is MyObject){ }
Arithmetic operator:
// Addition : +
// Subtraction : -
// Multiplication : *
// Division : /
// Modulo remainder: %
let sum = 10 + 5;
let result = 20 - 3;
let total = 15 * 2;
let costPerPerson = 7 / 2;
let remainder = 5 % 2;
Equality operator:
// Equal to : ==
// Not equal to : !=
let isTrue = (5 == 4);
let isCorrect = (5 != 4);
Comparison operator:
// Greater than : >
// Less than : <
// Greater than or equal to : >=
// Less than or equal to : <=
let isTrue = (5 > 4);
let isFalse = (5 < 4);
let isCorrect = (3 >= 2);
let isRight = (3 <= 2);
Logical operator:
let score = 85;
let count = 5;
let isCorrect = (score >= 80 && count > 0);
let isRight = (count >= 10 || score >= 80);
let isOk = (score != count);
Bitwise operator:
let value = 8;
let flag = 1;
let andResult = (value & flag); // Bitwise AND
let orResult = (value | flag); // Bitwise OR
let xor = (value ^ flag); // Bitwise Exclusive OR (XOR)
let complement = (~flag); // bitwise complement operator
let leftShift = value << 2; // Bitwise Left Shift
let rightShift = value >> 1; // Bitwise Right Shift
Arithmetic operator:
// Addition : +
// Subtraction : -
// Multiplication : *
// Division : /
// Modulo remainder: %
let sum: number = 10 + 5;
let result: number = 20 - 3;
let total: number = 15 * 2;
let costPerPerson: number = 7 / 2;
let remainder: number = 5 % 2;
Equality operator:
// Equal to : ==
// Not equal to : !=
let isTrue: boolean = (5 == 4);
let isCorrect: boolean = (5 != 4);
Comparison operator:
// Greater than : >
// Less than : <
// Greater than or equal to : >=
// Less than or equal to : <=
let isTrue: boolean = (5 > 4);
let isFalse: boolean = (5 < 4);
let isCorrect: boolean = (3 >= 2);
let isRight: boolean = (3 <= 2);
Logical operator:
let score: number = 85;
let count: number = 5;
let isCorrect: boolean = (score >= 80 && count > 0);
let isRight: boolean = (count >= 10 || score >= 80);
let isOk: boolean = (score != count);
Bitwise operator:
let value: number = 8;
let flag: number = 1;
let andResult: number = (value & flag); // Bitwise AND
let orResult: number = (value | flag); // Bitwise OR
let xor: number = (value ^ flag); // Bitwise Exclusive OR (XOR)
let complement: number = (~flag); // bitwise complement operator
let leftShift: number = value << 2; // Bitwise Left Shift
let rightShift: number = value >> 1; // Bitwise Right Shift
Arithmetic operator:
# Addition : +
# Subtraction : -
# Multiplication : *
# Division : /
# Modulo remainder: %
sum: int = 10 + 5;
result: int = 20 - 3;
total: float = 15 * 2;
costPerPerson: float = 7 / 2;
remainder: int = 5 % 2;
Equality operator:
# Equal to : ==
# Not equal to : !=
isTrue: bool = (5 == 4);
isCorrect: bool = (5 != 4);
Comparison operator:
# Greater than : >
# Less than : <
# Greater than or equal to : >=
# Less than or equal to : <=
isTrue: bool = (5 > 4);
isFalse: bool = (5 < 4);
isCorrect: bool = (3 >= 2);
isRight: bool = (3 <= 2);
Logical operator:
score: int = 85;
count: int = 5;
isCorrect: bool = (score >= 80 and count > 0);
isRight: bool = (count >= 10 or score >= 80);
isOk: bool = (score != count);
Bitwise operator:
value: int = 8;
flag: int = 1;
andResult: int = (value & flag); # Bitwise AND
orResult: int = (value | flag); # Bitwise OR
xor: int = (value ^ flag); # Bitwise Exclusive OR (XOR)
complement: int = (~flag); # bitwise complement operator
leftShift: int = value << 2; # Bitwise Left Shift
rightShift: int = value >> 1; # Bitwise Right Shift
print(rightShift) # 4
Arithmetic operator:
// Addition : +
// Subtraction : -
// Multiplication : *
// Division : /
// Modulo remainder: %
int sum = 10 + 5;
int result = 20 - 3;
float total = 15 * 2;
float costPerPerson = 7 / 2;
int remainder = 5 % 2;
Equality operator:
// Equal to : ==
// Not equal to : !=
boolean isTrue = (5 == 4);
boolean isCorrect = (5 != 4);
Comparison operator:
// Greater than : >
// Less than : <
// Greater than or equal to : >=
// Less than or equal to : <=
boolean isTrue = (5 > 4);
boolean isFalse = (5 < 4);
boolean isCorrect = (3 >= 2);
boolean isRight = (3 <= 2);
Logical operator:
int score = 85;
int count = 5;
boolean isCorrect = (score >= 80 && count > 0);
boolean isRight = (count >= 10 || score >= 80);
boolean isOk = (score != count);
Bitwise operator:
int value = 8;
int flag = 1;
int andResult = (value & flag); // Bitwise AND
int orResult = (value | flag); // Bitwise OR
int xor = (value ^ flag); // Bitwise Exclusive OR (XOR)
int complement = (~flag); // bitwise complement operator
int leftShift = value << 2; // Bitwise Left Shift
int rightShift = value >> 1; // Bitwise Right Shift
Math
Math function:
//
// Common math functions
//
/*
Power : Pow()
Square root : Sqrt()
Absolute : Abs()
Round : Round()
Floor: Floor()
Ceiling: Ceiling()
*/
double powResult = Math.Pow(7, 2);
Console.WriteLine(powResult); // 49
double sqrtResult = Math.Sqrt(16);
Console.WriteLine(sqrtResult); // 4
double absResult = Math.Abs(-11);
Console.WriteLine(absResult); // 11
double roundResult = Math.Round(13.4);
Console.WriteLine(roundResult); // 13
double floorResult = Math.Floor(13.4);
Console.WriteLine(floorResult); // 13
double ceilingResult = Math.Ceiling(13.4);
Console.WriteLine(ceilingResult); // 14
//
// Special math functions
//
double eBasedLog = Math.Log(3); // natural log
Console.WriteLine(eBasedLog); // 1.0986122886681098
double binaryLog = Math.Log2(8); // binary log
Console.WriteLine(binaryLog); // 3
double tenBasedLog = Math.Log10(100); // 10 based log
Console.WriteLine(tenBasedLog); // 2
double sine = Math.Sin(45); // sine
Console.WriteLine(sine); // 0.8509035245341184
double cosine = Math.Cos(45); // cosine
Console.WriteLine(cosine); // 0.5253219888177297
Math constant:
// natural logarithmic base 'e'
Console.WriteLine(Math.E); // 2.718281828459045
// pi
Console.WriteLine(Math.PI); // 3.141592653589793
Math function:
//
// Common math functions
//
let powResult = Math.pow(7, 2);
console.log(powResult); // 49
let sqrtResult = Math.sqrt(16);
console.log(sqrtResult); // 4
let absResult = Math.abs(-11);
console.log(absResult); // 11
let roundResult = Math.round(13.4);
console.log(roundResult); // 13
let floorResult = Math.floor(13.4);
console.log(floorResult); // 13
let ceilingResult = Math.ceil(13.4);
console.log(ceilingResult); // 14
//
// Special math functions
//
let eBasedLog = Math.log(3); // natural log
console.log(eBasedLog); // 1.0986122886681098
let binaryLog = Math.log2(8); // binary log
console.log(binaryLog); // 3
let tenBasedLog = Math.log10(100); // 10 based log
console.log(tenBasedLog); // 2
let sine = Math.sin(45); // sine
console.log(sine); // 0.8509035245341184
let cosine = Math.cos(45); // cosine
console.log(cosine); // 0.5253219888177297
// More Math Static methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math#static_methods
Math constant:
// natural logarithmic base 'e'
console.log(Math.E); // 2.718281828459045
// pi
console.log(Math.PI); // 3.141592653589793
// More Math Static properties: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math#static_properties
Math function:
//
// Common math functions
//
let powResult: number = Math.pow(7, 2);
console.log(powResult); // 49
let sqrtResult: number = Math.sqrt(16);
console.log(sqrtResult); // 4
let absResult: number = Math.abs(-11);
console.log(absResult); // 11
let roundResult: number = Math.round(13.4);
console.log(roundResult); // 13
let floorResult: number = Math.floor(13.4);
console.log(floorResult); // 13
let ceilingResult: number = Math.ceil(13.4);
console.log(ceilingResult); // 14
//
// Special math functions
//
let eBasedLog: number = Math.log(3); // natural log
console.log(eBasedLog); // 1.0986122886681098
let sine: number = Math.sin(45); // sine
console.log(sine); // 0.8509035245341184
let cosine: number = Math.cos(45); // cosine
console.log(cosine); // 0.5253219888177297
// https://www.w3schools.blog/math-object-typescript
Math constant:
// natural logarithmic base 'e'
console.log(Math.E); // 2.718281828459045
// pi
console.log(Math.PI); // 3.141592653589793
// https://www.w3schools.blog/math-object-typescript
Math function:
import math
absResult: float = abs(-11);
print(f"abs(-11) => {absResult}")
roundResult: float = round(13.4);
print(f"round(13.4) => {roundResult}")
# Common math functions
powResult: float = math.pow(7, 2);
print(f"math.pow(7, 2) => {powResult}")
sqrtResult: float = math.sqrt(16);
print(f"math.sqrt(16) => {sqrtResult}")
floorResult: float = math.floor(13.4);
print(f"math.floor(13.4) => {floorResult}")
ceilingResult: float = math.ceil(13.4);
print(f"math.ceil(13.4) => {ceilingResult}")
# Special math functions
eBasedLog: float = math.log(3);
print(f"math.log(3) => {eBasedLog}")
sine: float = math.sin(45);
print(f"math.sin(45) => {sine}")
cosine: float = math.cos(45);
print(f"math.sin(45) => {cosine}")
# https://www.w3schools.com/python/module_math.asp
Math constant:
import math
# natural logarithmic base 'e'
print(f"math.e => {math.e}")
# pi
print(f"math.pi => {math.pi}")
# https://www.w3schools.com/python/module_math.asp
Math function:
//
// Common math functions
//
/*
Power : pow()
Square root : sqrt()
Absolute : abs()
Round : round()
Floor: floor()
Ceiling: ceil()
*/
double powResult = Math.pow(7, 2);
System.out.println(powResult); // 49.0
double sqrtResult = Math.sqrt(16);
System.out.println(sqrtResult); // 4.0
int absResult = Math.abs(-11);
System.out.println(absResult); // 11
long roundResult = Math.round(13.4);
System.out.println(roundResult); // 13
double floorResult = Math.floor(13.4);
System.out.println(floorResult); // 13.0
double ceilingResult = Math.ceil(13.4);
System.out.println(ceilingResult); // 14.0
//
// Special math functions
//
double eBasedLog = Math.log(3); // natural log
System.out.println(eBasedLog); // 1.0986122886681098
double tenBasedLog = Math.log10(100); // 10 based log
System.out.println(tenBasedLog); // 2.0
double sine = Math.sin(45); // sine
System.out.println(sine); // 0.8509035245341184
double cosine = Math.cos(45); // cosine
System.out.println(cosine); // 0.5253219888177297
Math constant:
// natural logarithmic base 'e'
System.out.println(Math.E); // 2.718281828459045
// pi
System.out.println(Math.PI); // 3.141592653589793
If statement
Simple if:
int age = 18;
if (age >= 18)
{
Console.WriteLine("Adult");
// code here
}
If else:
int age = 17;
if (age >= 18)
{
Console.WriteLine("Can vote");
}
else
{
Console.WriteLine("CANNOT vote");
}
If else ladder:
int age = 15;
if (age < 3)
{
Console.WriteLine("Infant");
}
else if (age >= 3 && age < 13)
{
Console.WriteLine("Child");
}
else if (age >= 13 && age < 18)
{
Console.WriteLine("Teenager");
}
else
{
Console.WriteLine("Adult");
}
Nested if:
bool isValid = true;
int score = 80;
if (isValid)
{
if (score >= 80)
{
Console.WriteLine("Premium");
}
else
{
Console.WriteLine("Normal");
}
}
else
{
Console.WriteLine("Invalid");
}
Simple if:
let age = 18;
if (age >= 18)
{
console.log("Adult");
}
If else:
let age = 17;
if (age >= 18)
{
console.log("Can vote");
}
else
{
console.log("CANNOT vote");
}
If else ladder:
let age = 15;
if (age < 3)
{
console.log("Infant");
}
else if (age >= 3 && age < 13)
{
console.log("Child");
}
else if (age >= 13 && age < 18)
{
console.log("Teenager");
}
else
{
console.log("Adult");
}
Nested if:
let isValid = true;
let score = 80;
if (isValid)
{
if (score >= 80)
{
console.log("Premium");
}
else
{
console.log("Normal");
}
}
else
{
console.log("Invalid");
}
Simple if:
let age = 18;
if (age >= 18)
{
console.log("Adult");
}
If else:
let age = 17;
if (age >= 18)
{
console.log("Can vote");
}
else
{
console.log("CANNOT vote");
}
If else ladder:
let age = 15;
if (age < 3)
{
console.log("Infant");
}
else if (age >= 3 && age < 13)
{
console.log("Child");
}
else if (age >= 13 && age < 18)
{
console.log("Teenager");
}
else
{
console.log("Adult");
}
Nested if:
let isValid = true;
let score = 80;
if (isValid)
{
if (score >= 80)
{
console.log("Premium");
}
else
{
console.log("Normal");
}
}
else
{
console.log("Invalid");
}
Simple if:
age: int = 18
if age >= 18:
print("Adult")
If else:
age: int = 19
if age >= 18:
print("Can vote")
else:
print("CANNOT vote")
If else ladder:
age: int = 15
if age < 3:
print("Infant")
elif age >= 3 && age < 13:
print("Child")
elif age >= 13 && age < 18:
print("Teenager")
else:
print("Adult")
Nested if:
isValid: bool = True
score: int = 80
if isValid:
if score >= 80:
print("Premium")
else:
print("Normal")
else:
print("Invalid")
Simple if:
int age = 18;
if (age >= 18)
{
System.out.println("Adult");
}
If else:
int age = 17;
if (age >= 18)
{
System.out.println("Can vote");
}
else
{
System.out.println("CANNOT vote");
}
If else ladder:
int age = 15;
if (age < 3)
{
System.out.println("Infant");
}
else if (age >= 3 && age < 13)
{
System.out.println("Child");
}
else if (age >= 13 && age < 18)
{
System.out.println("Teenager");
}
else
{
System.out.println("Adult");
}
Nested if:
bool isValid = true;
int score = 80;
if (isValid)
{
if (score >= 80)
{
System.out.println("Premium");
}
else
{
System.out.println("Normal");
}
}
else
{
System.out.println("Invalid");
}
Switch statement
Switch syntax:
// integer case
int roll = 5;
switch (roll)
{
case 1:
Console.WriteLine("Top student -> First (roll 1)");
break;
case 2:
Console.WriteLine("Top student -> Second (roll 2)");
break;
case 3:
Console.WriteLine("Top student -> Third (roll 3)");
break;
default:
Console.WriteLine("NOT TOP student");
break;
}
// string case
string continent = "abc";
switch (continent)
{
case "america":
// code
Console.WriteLine("AMERICA");
break;
case "europe":
// code
Console.WriteLine("EUROPE");
break;
case "asia":
// code
Console.WriteLine("ASIA");
break;
case "africa":
// code
Console.WriteLine("AFRICA");
break;
default:
// code
Console.WriteLine("XXX");
break;
}
Multiple case fall through:
int roll = 1;
switch (roll)
{
case 1:
case 2:
case 3:
// code
Console.WriteLine("TOP Student");
break;
case 4:
case 5:
case 6:
case 7:
// code
Console.WriteLine("DESCENT Student");
break;
default:
// code
Console.WriteLine("NOT GOOD Student");
break;
}
// or
int roll = 5;
switch (roll)
{
case 1 or 2 or 3:
// code
Console.WriteLine("TOP Student");
break;
case 4 or 5 or 6 or 7:
// code
Console.WriteLine("DESCENT Student");
break;
default:
// code
Console.WriteLine("NOT GOOD Student");
break;
}
// when
int roll = 5;
switch (roll)
{
case var n when (n >= 1 && n <= 3):
Console.WriteLine("TOP student");
break;
case var n when (n >= 4 && n <= 7):
Console.WriteLine("DESCENT student");
break;
default:
Console.WriteLine("NOT GOOD student");
break;
}
Switch syntax:
// integer case
let roll = 3;
switch (roll)
{
case 1:
console.log("Top student -> First (roll 1)");
break;
case 2:
console.log("Top student -> Second (roll 2)");
break;
case 3:
console.log("Top student -> Third (roll 3)");
break;
default:
console.log("NOT TOP student");
break;
}
// string case
let continent = "asia";
switch (continent)
{
case "america":
console.log("AMERICA");
break;
case "europe":
console.log("EUROPE");
break;
case "asia":
console.log("ASIA");
break;
case "africa":
console.log("AFRICA");
break;
default:
console.log("XXX");
break;
}
Multiple case fall through:
let roll = 1;
switch (roll)
{
case 1:
case 2:
case 3:
console.log("TOP Student");
break;
case 4:
case 5:
case 6:
case 7:
console.log("DESCENT Student");
break;
default:
console.log("NOT GOOD Student");
break;
}
Switch syntax:
// integer case
let roll: number = 3;
switch (roll)
{
case 1:
console.log("Top student -> First (roll 1)");
break;
case 2:
console.log("Top student -> Second (roll 2)");
break;
case 3:
console.log("Top student -> Third (roll 3)");
break;
default:
console.log("NOT TOP student");
break;
}
// string case
let continent: string = "asia";
switch (continent)
{
case "america":
console.log("AMERICA");
break;
case "europe":
console.log("EUROPE");
break;
case "asia":
console.log("ASIA");
break;
case "africa":
console.log("AFRICA");
break;
default:
console.log("XXX");
break;
}
Multiple case fall through:
let roll: number = 1;
switch (roll)
{
case 1:
case 2:
case 3:
console.log("TOP Student");
break;
case 4:
case 5:
case 6:
case 7:
console.log("DESCENT Student");
break;
default:
console.log("NOT GOOD Student");
break;
}
Switch syntax:
python does not have switch => use hack:
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 is default if x not found
Switch syntax:
// integer case
int roll = 2;
switch (roll)
{
case 1:
System.out.println("Top student -> First (roll 1)");
break;
case 2:
System.out.println("Top student -> Second (roll 2)");
break;
case 3:
System.out.println("Top student -> Third (roll 3)");
break;
default:
System.out.println("NOT TOP student");
break;
}
// string case
String continent = "abc";
switch (continent)
{
case "america":
// code
System.out.println("AMERICA");
break;
case "europe":
// code
System.out.println("EUROPE");
break;
case "asia":
// code
System.out.println("ASIA");
break;
case "africa":
// code
System.out.println("AFRICA");
break;
default:
// code
System.out.println("XXX");
break;
}
Multiple case fall through:
int roll = 1;
switch (roll)
{
case 1:
case 2:
case 3:
// code
System.out.println("TOP Student");
break;
case 4:
case 5:
case 6:
case 7:
// code
System.out.println("DESCENT Student");
break;
default:
// code
System.out.println("NOT GOOD Student");
break;
}
// Multiple cases with comma (',')
int roll = 1;
switch (roll)
{
case 1, 2, 3:
// code
System.out.println("TOP Student");
break;
case 4, 5, 6, 7:
// code
System.out.println("DESCENT Student");
break;
default:
// code
System.out.println("NOT GOOD Student");
break;
}
Array
1D array:
public class Program
{
static void Main(string[] args)
{
// Create array
int[] my1DArray = new int[3]; // dimension: 3
// Assign value
my1DArray[0] = 13;
my1DArray[1] = 17;
my1DArray[2] = 9;
// Print array
for (int i = 0; i <= my1DArray.Length - 1; i++)
{
Console.WriteLine($"index {i} => value: {my1DArray[i]}");
}
//
// Initializing array, while creating
//
string[] names = new string[] { "Xxx", "Yyy", "Zzz" };
for (int j = 0; j <= names.Length - 1; j++)
{
Console.WriteLine($"name-{j} => {names[j]}");
}
}
}
2D array:
// Create array
int rowCount = 2;
int columnCount = 3;
int[,] my2DArray = new int[rowCount, columnCount];
Console.WriteLine($"Dimension of my2DArray => {my2DArray.Length}");
// Assign value
my2DArray[0, 0] = 15;
my2DArray[0, 1] = 11;
my2DArray[0, 2] = 17;
my2DArray[1, 0] = 9;
my2DArray[1, 1] = 3;
my2DArray[1, 2] = 8;
// Print array
for (int i = 0; i <= rowCount - 1; i++)
{
for (int j = 0; j <= columnCount -1; j++)
{
Console.WriteLine($"at [{i}, {j}] => value: {my2DArray[i, j]}");
}
}
//
// Initializing array, while creating
//
int[,] matrix = new int[,] { { 2, 4 }, { 1, 3 } }; // 2 rows, 2 columns
for (int i = 0; i <= 2 - 1; i++)
{
for (int j = 0; j <= 2 - 1; j++)
{
Console.WriteLine($"value: {matrix[i, j]} at [{i}, {j}]");
}
}
1D array:
//
// Array using new keyword
//
let cities = new Array(3); //Length: 3
cities[0] = "Tokyo";
cities[1] = "Osaka";
cities[1] = "Nagoya";
// Print array
for (let i = 0; i <= cities.length - 1; i++) {
console.log(`index ${i} => value: ${cities[i]}`);
}
//
// Array using "[]"
//
let my1DArray = []; // empty array
// Assign values
my1DArray[0] = 13;
my1DArray[1] = 17;
my1DArray[2] = 9;
//
// Initializing array, while creating
//
let words = ["Apple", "Orange", "Banana", "Grape"];
console.log(words);
for (let i = 0; i <= words.length - 1; i++) {
console.log(`index ${i} => value: ${words[i]}`);
}
2D array:
//
// 2D array using new keyword
//
let rowCount = 5;
let columnCount = 3;
let numbers = new Array(rowCount).fill(new Array(columnCount).fill(0));
console.table(numbers);
let users = new Array(rowCount).fill(new Array(columnCount));
// Now assign values
users[0] = ["U1", 1, 16];
users[1] = ["U2", 2, 13];
users[2] = ["U3", 3, 17];
users[3] = ["U4", 4, 19];
users[4] = ["U5", 5, 11];
console.table(users);
//
// 2D array using []
//
let my2DArray = [
[1, 3, 5],
[2, 4, 6, 8],
[100, 200, 300, 400, 500, 600, 700]
];
console.table(my2DArray);
console.log(`my2DArray lenght: ${my2DArray.length}`);
// Print array
for (let i = 0; i <= my2DArray.length - 1; i++) {
let rowLength = my2DArray[i].length; // get length of each row
for (let j = 0; j <= rowLength - 1; j++) {
console.log(`at [${i}, ${j}] => value: ${my2DArray[i][j]}`);
}
}
1D array:
//
// Array using new keyword
//
let cities: Array<string> = new Array(3);
cities[0] = "Tokyo";
cities[1] = "Osaka";
cities[1] = "Nagoya";
for (let i = 0; i <= cities.length - 1; i++) {
console.log(`index ${i} => value: ${cities[i]}`);
}
// Initializing array, while creating
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
console.table(fruits);
//
// Array using "[]"
//
let numbers: number[] = []; // empty array
// Assign values
numbers[0] = 13;
numbers[1] = 17;
numbers[2] = 9;
for (let i = 0; i <= numbers.length - 1; i++) {
console.log(`index ${i} => value: ${numbers[i]}`);
}
// Initializing array, while creating
let words: string[] = ["Xxx", "Yyy", "Zzz"];
console.table(words);
//
// Multi-type array
//
let values: (string | number)[] = ['Xxx', 1, 2, 'Yyy', 3, 4, 'Zzz'];
console.table(values);
2D array:
let marks: number[][] = [];
marks[0] = [1, 75];
marks[1] = [2, 83];
marks[2] = [3, 91];
console.table(marks);
let my2DArray: string[][] = [
["X1", "Y1", "Z1"],
["X2", "Y2", "Z2"],
["X3", "Y3", "Z3"]
];
console.table(my2DArray);
console.log(`my2DArray lenght: ${my2DArray.length}`);
for (let i = 0; i <= my2DArray.length - 1; i++) {
let rowLength = my2DArray[i].length; // get length of each row
for (let j = 0; j <= rowLength - 1; j++) {
console.log(`at [${i}, ${j}] => value: ${my2DArray[i][j]}`);
}
}
1D array:
import array as arr
#
# format: array.array(typecode[, initializer])
# typecode i => signed int
# typecode d => double
# typecode f => float
# typecode u => Unicode character (wchar_t)
#
# int array
intArray = arr.array('i', [1, 2, 3, 4, 5])
print("Int array:")
for x in intArray:
print(x, end = " ")
print("\n") # new line
# double array
doubleArray = arr.array('d', [1.1, 3.5, 4.7])
print("Double array:")
for x in doubleArray:
print(x, end = " ")
words = arr.array('u', 'hello world')
print(f"Number of characters: {len(words)}");
print("\nCharacter array (string):")
for i in range(0, len(names)):
print(f"{words[i]}", end = "")
2D array:
#
# There is no 2d array in python, use list to get 2d array
#
matrix = [[1, 3, 5], [2, 4, 6]] # lsit as 2d array
for i in range(0, len(matrix)):
rowLength = len(matrix[i])
for j in range(0, rowLength):
print(f"matrix[{i}, {j}] => {matrix[i][j]}")
1D array:
// Create array
int[] my1DArray = new int[3]; // dimension: 3
// Assign value
my1DArray[0] = 13;
my1DArray[1] = 17;
my1DArray[2] = 9;
// Print array
for (int i = 0; i <= my1DArray.length - 1; i++)
{
System.out.println(String.format("index %d => value: %d", i, my1DArray[i]));
}
//
// Initializing array, while creating
//
String[] names = new String[] { "HASSAN", "SALMA", "SOHRAF" };
for (int j = 0; j <= names.length - 1; j++)
{
System.out.println(String.format("name-%d => %s", j, names[j]));
}
2D array:
// Create array
int rowCount = 2;
int columnCount = 3;
int[][] my2DArray = new int[rowCount][columnCount];
System.out.println(String.format("Dimension of my2DArray => %d", my2DArray.length));
// Assign value
my2DArray[0][0] = 15;
my2DArray[0][1] = 11;
my2DArray[0][2] = 17;
my2DArray[1][0] = 9;
my2DArray[1][1] = 3;
my2DArray[1][2] = 8;
// Print array
for (int i = 0; i <= rowCount - 1; i++)
{
for (int j = 0; j <= columnCount -1; j++)
{
System.out.println(String.format("at [%d, %d] => value: %d", i, j, my2DArray[i][j]));
}
}
//
// Initializing array, while creating
//
int[][] matrix = new int[][] { { 2, 4 }, { 1, 3 } }; // 2 rows, 2 columns
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
System.out.println(String.format("value: %d at [%d, %d]", matrix[i][j], i, j));
}
}