Some Remark
Java
-
Class
- Declare your class
final
- Prevents extension of the class since extending a static class makes no sense - Make the constructor
private
- Prevents instantiation by client code as it makes no sense to instantiate a static class - Make all the members and functions of the class
static
- Since the class cannot be instantiated no instance methods can be called or instance fields accessed - Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member
- Declare your class
-
Difference between
assert
andexception
The main difference is that
assert
is not guaranteed to be processed, unless assertions are explicitly enabled (either via the-ea
option tojava
, or programmatically). On the other hand, throwing anew AssertionError()
will always work. -
variable = expression;
(*) The type of the expression, and the type of the variable, must be compatible!
-
Feature Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Car v3 = new Car(); Declared Type Vehicle Vehicle Car Actual Type Vehicle Car Car Method Calls Only Vehicle methods Only Vehicle methods (at compile-time) All Car methods + inherited Vehicle methods Runtime Behavior (for overridden methods) Vehicle 's implementation Car 's overridden implementation Car 's overridden implementation Can Call honk() directly? No No (needs casting) Yes -
```java """ Python Practical """ """ assignments variable = expression variable += expression # equivalent to variable = variables + expression variable OP= expression # equivalent to variable = variable OP expression variable: hint = expression """
my_string: str = "Hello" my_number: int = 1 my_list: list[int] = [1, 2, 3]
""" statements and body
statement = assignment | expression | if | while | for body = statement body """
print(1) print(2) print(3)
if my_string == "Hello": print("if statement 1") print("if statement 2") print("Not an if statement")
""" Conditional statements """
print("The if")
if my_string.isdigit(): print("the variable my_string is a digit") else: print("the variable my_string is not a digit")
print("If with elif")
if my_number == 0 and my_string.isdigit(): print("my_string as a digit is {}".format(int(my_string))) elif not my_number == 1: print("my_number is not 1") elif my_number == 2: print("my_number is 2") else: print("my_number is {}".format(my_number))
""" A quick stop: == vs is == will check content is will check reference equality """
import sys
first: str = sys.argv[1] second: str = sys.argv[2] second_copy: str = second
print("first({}) == second({}) results in {}".format(id(first), id(second), first == second)) print("second({}) == second_copy({}) results in {}".format(id(second), id(second_copy), second == second_copy)) print("first({}) is second({}) results in {}".format(id(first), id(second), first is second)) print("second({}) is second_copy({}) results in {}".format(id(second), id(second_copy), second is second_copy))
print("While")
i: int = 0 while i < len(sys.argv): print("sys.argv[{}] == {}".format(i, sys.argv[i])) i += 1
print("For-each, because Python doesn't have the for statement")
for argument in sys.argv: print(argument)
argument_count: int = 0
for _ in sys.argv: argument_count += 1
print("I have {} arguments".format(argument_count))
numbers_and_strings: list[(int, str)] = [(1, "One"), (2, "Two"), (3, "Three")] numbers_and_strings_and_colors: list[(int, str, str)] = [(1, "One", "Blue"), (2, "Two", "Red"), (3, "Three", "Cyan")]
for number_and_string in numbers_and_strings: print("The number {}".format(number_and_string[0])) print("Is written as {}".format(number_and_string[1]))
for (number, string, _) in numbers_and_strings_and_colors: print("The number {} is written as {}".format(number, string))
""" lists """
my_nice_list = [1, None, "String", (1, 2)] print(my_nice_list) print(my_nice_list[3]) # access a specific index of a list print(my_nice_list[2:]) # get a sublist of a list, starting from index 2
the previous one is equivalent to my_nice_list[2:len(my_nice_list)]
print(my_nice_list[1:4]) # get a sublist of a list, going from index 1 up to index 2 print(my_nice_list[-1]) # get the element at len(my_nice_list) - 1 print(my_nice_list[-2]) # get the element at len(my_nice_list) - 2
""" lists by comprehension """
even_numbers: list[int] = [x for x in range(0, 21) if x % 2 == 0] print(even_numbers)
""" function definition You can define the same function multiple times, the last definition will be the one that's going to be used """
def foo(): print("I'm foo")
def bar(x: int): print("I'm bar with {}".format(x))
def fibonacci(x: int) -> int: assert x >= 0 fib1: int = 0 fib2: int = 1 i: int = 0 while i < x: aux: int = fib1 fib1 = fib2 fib2 = aux + fib2 i += 1 return fib1
def my_range(start:int, finish:int): current: int = start while current < finish: yield current # it will return a value, but keep the function's state as it was current += 1
foo() bar(42) for i in my_range(0, 6): print(i)
""" Classes """
class Student:
def init(self: 'Student', name: str, surname: str, id: int): self.__name: str = name # the attribute will have the name _Student__name if you want to access it from outside the class self.__surname: str = surname self.__id: int = id
def get_name(self: 'Student') -> str: return self.__name
def change_name(self: 'Student', new_name: str): self.__name = new_name
def str(self: 'Student') -> str: return "{" + "{} {} id {}".format(self.__name, self.__surname, self.__id) + "}"
# The following two functions will make this class be usable with indexes, # but doing this for a Student is a very very very bad idea, don't do it!
def getitem(self: 'Student', key: int): if key == 0: return self.__name elif key == 1: return self.__surname elif key == 2: return self.__id else: raise Exception("Invalid index {}".format(key))
def setitem(self: 'Student', key: int, value): if key == 0: self.__name = value elif key == 1: self.__surname = value elif key == 2: self.__id = value else: raise Exception("Invalid index {}".format(key))
john_doe: Student = Student("John", "Doe", 42) print(john_doe) john_doe[1] = "Derp" # this is allowed by the setitem function for i in range(3): print(john_doe[i]) # this is allowed by the getitem function
``` 6. The exception is a generic class, which uses templates, here we must write everything in a header file (.hpp). 7. If i use anonymous class, then compiler will generate a new, real class of anonymous class