-
Programmers 2차원 동전 뒤집기
Question https://school.programmers.co.kr/learn/courses/30/lessons/77885 Explanation For 2차원 동전, bitmask iterating through just 1«rows does not travel all the possibilities. 1«rows is just a single bitmask where leftmost bit is 1 and to its right is all 0. We should instead do range(1«rows) which now considers all bitmasks with row bits. Al... Read More
-
Programmers 2개 이하로 다른 비트
Question https://school.programmers.co.kr/learn/courses/30/lessons/77885 First try I did just like the question example where I incremented each number by 1 and counted bit difference. This worked for most except 2 test cases which I assume is a very long list and thus caused runtime error. Improvement I googled and there is a pattern. http... Read More
-
Programmers 기능개발
기능개발 https://school.programmers.co.kr/learn/courses/30/lessons/42586 Explanation Well, technically it is a stack question but zipping through the list is easier. We first set the first progress count with the first element in the progress list. If we see a value less than this count, we just increment count but when we have a greater value, th... Read More
-
Programmers 같은 숫자는 싫어
같은 숫자는 싫어 https://school.programmers.co.kr/learn/courses/30/lessons/12906 Explanation I first thought since there are no duplicates allowed, we can use set but we have to preserve the order. So let’s use stack from collections import deque def solution(arr): stack =deque() for i in arr: if stack and stack[-1]==i: co... Read More
-
Programmers 선입 선출 스케줄링
징검다리 건너기 https://school.programmers.co.kr/learn/courses/30/lessons/64062 Explanation initial wrong solution where I was setting wrong condition for if def solution(stones, k): start = 0 end = 200000000 while start <= end: mid = (start + end) // 2 temp = [0 if i - mid < 0 else i - mid for i in stones] ... Read More
-
Programmers 선입 선출 스케줄링
선입 선출 스케줄링 https://school.programmers.co.kr/learn/courses/30/lessons/12920 Explanation Firstly, before we do anything, if n is less than length than length of cores, than we can just return n. But the problem is finding when n is bigger and we have to find the index. I think it is binary search but how do I know what to guess? Surely I cannot g... Read More
-
Programmers 징검다리
징검다리 https://school.programmers.co.kr/learn/courses/30/lessons/43236 Explanation This was my first attempt at binary search on a question that is not as simple as finding a value in a sorted list. Binary search is basically guessing the answer value by putting your guess as mid. There are 2 points you need to know. After sorting, we append the... Read More
-
Programmers 입국심사
입국심사 https://school.programmers.co.kr/learn/courses/30/lessons/43238 Explanation Remember I said binary search is literally guessing the answer value and seeing if all of the logic and condition can be processed within that answer value. Now we are guessing the time for all tasks to be completed and for a given guess of time, if more tasks ... Read More
-
Limitations of subquery in Querydsl
Issue insert into select can ~ be done via querydsl with JPAExpressions https://www.inflearn.com/questions/34751/%EC%84%9C%EB%B8%8C%EC%BF%BC%EB%A6%AC-insert%EC%97%90-%EB%8C%80%ED%95%9C-%EC%B2%98%EB%A6%AC BUT insert into with group by functionality + select CANNOT be done via querydsl. So as recommended in link, try with JPQL and if cannot, no ... Read More
-
How to set JDK in bash profile in linux
Solution I was confused with how to set jdk in my bash profile. Do I find a specific .jdk file or just a jdk folder? Solution When I depressed my compressed jdk files with tz format, some folders looked like openlogic-openjdk-bla but the official jdk that I downloaded from Oracle looked like jdk1.8.0_371. This is the valid one and we just ... Read More
-
ExpressionUtils.sum() not allowed in querydsl
Issue ok so in querydsl, there isnt a ExpressionUtils.sum() like queryFactory .select(ExpressionUtils .sum(Expressions .when(log.statusCode.isNull()) .then(1) .otherwise(0)) .add(stats.relayFailCount) .as(relayFailCount)) .from(log) .fetch(); Sequence number is not allowed here... Read More
-
error no property "some_method_name" not found for type "entity"
Issue Actually the solution is easy cuz I have been ignoring the method that I used QueryDsl on is not being recognised by other java class files, as shown in method name highlighted in grey colour. The solution: https://velog.io/@3210439/querydsl-No-property-found-for-type When you use querydsl, the repo name has to follow a certain conventio... Read More
-
What and how to use SQL coalesce
Example of coalesce For example, I have declared successCount as Integer (ref type) that allows null unlike primitive types. I am trying to increment this field in my querydsl update query. In this case, we can use coalesce() to set a default value for that field if it is null (which it would be at the start). Like this with querydsl public... Read More
-
Ajax button not showing up
Issue $('#iarlogs-table tbody').on('click', '.iarReqMsgBtn', function(e) { e.preventDefault(); // Prevents the default click behavior of the button const data = $('#iarlogs-table').DataTable().row($(this).closest('tr')).data(); $('#detailIarLogsModal').modal('show'); // Perform some action with the data, such as displaying it on ... Read More
-
OracleDatabaseException table or view does not exist error when generate-ddl is set to none
Issue I was mismatching entity’s table name (@Table(name = “IAR_LOG”)) with the DB’s table name which is IAR_SERVICE_LOG. So I was making a query using querydsl like queryFactory.select(Projections.fields(IarLogsWithPartnerDto.class, iarLogs.id, iarLogs.createdAt)) .from(iarLogs) .fetch(); This querydsl function gave me Orac... Read More
-
SQL Trigger and a possible error
Issue and solution When i select some fields from my log table, it worked perfectly fine But when i selected those fields from my log table and try inserting into a new stat table, i came across stat id null error. Its not that you need id of the log table. The target table (stat) should have an auto-incrementing primary key or else you need ... Read More
-
Solve insertion type and select type at position 9 are not compatible error
Issue and solution This only applies when you are trying to use native sql instead of querydsl and forcing fields into a pure sql query. The types of entity’s fields need to be considered whether they match the constraints of the DB you are using. The field type that I was trying to get and insert by performing outer joining does not seem to ma... Read More
-
How to set environment variable in bash profile in linux
Solution no space in between! when setting environment variable in bash profile, VERY IMPORTANT DON’T PUT space in between anything. There should be no space like env_var=blah, not env_var = blah. For example, Export LD_LIBRARY_PATH=${LD_LIBRARY}:/home/brian/bitch Export JAVA_HOME=/home/brian/jdk/jdk1.8.0_371 Export PATH=$JAVA_HOME/bin:$PATH ... Read More
-
BooleanExpression in Querydsl and use booleanexpression over booleanbuilder
Link very useful tips for spring boot and especially booleanexpression over booleanbuilder https://velog.io/@youngerjesus/%EC%9A%B0%EC%95%84%ED%95%9C-%ED%98%95%EC%A0%9C%EB%93%A4%EC%9D%98-Querydsl-%ED%99%9C%EC%9A%A9%EB%B2%95 BooleanExpression Using SprintUtils.hasText() to compare strings So comparing strings in BooleanExpression is easy we jus... Read More
-
Permissions 0777 for 'your_key.pem' are too open
Issue Permissions 0777 for 'your_key.pem' are too open. It is required that your private key files are NOT accessible by others. Solution https://rainbound.tistory.com/entry/%EC%9C%88%EB%8F%84%EC%9A%B0-ssh-%EC%97%B0%EA%B2%B0-%EC%97%90%EB%9F%ACpermissions-too-open%EB%93%B1 Read More
-
Spring Legacy and some precautions
Issue (Spring Legacy) Always take note of your output directory (배포 파일). For example, I had 4 ojdbc files in my output directory file so there were conflicts of multiple versions. JVM always executes the one that is the “oldest” so even though I added the correct new one, it is not updated properly. I thought I was adding it properly via Lib... Read More
-
Different strategies of mapping PK (identity, sequence, automatic)
Explained Different ways of mapping PK: 직접할당: you set it urself 자동 생성: identity (key generation responsibility is to the db), sequence(uses db sequence to generate PK), table(creates a separate key generation table) 직접할당 직접할당: @Id @Column private Long id This strategy is where before you persist your entity via em.persist(), you allocate t... Read More
-
UniqueConstraints annotation and for multiple column conditions(제약조건) where Column annotation is insufficient
Issue @Table( uniqueConstraints={ @UniqueConstraint( columnNames={"column1"}) } ) @Table( uniqueConstraints = { @UniqueConstraint(name = "UniqueNumberAndStatus", columnNames = {"personNumber", "isActive"}), @UniqueConstraint(name = "UniqueSecurityAndDepartment", columnNames = {"securityNumber", "departmentCode"}) } ... Read More
-
Unique constraint error in Oracle db
Issue I was making a test case and making an entity with id field of 1000L when I came across this issue. I checked the DB but 1000L was not used in DB, only up till 100L. Very strange, I tested with 1L which WAS in DB and Hibernate sent an update query, updating the column with id =1. That is strange cuz update was allowed but insert result... Read More
-
String and methods in Python and practice questions
split() maxsplit parameter .split(maxsplit=1) This maxsplit parameter determines max number of splits to perform. Default is -1 but if you set value like 1, split operation will be done only once and hence, maxsplit (literally). So it will create at most 2 substrings. If I have a string like hey = "I love eating pizza and pasta." print(hey.sp... Read More
-
Difference between split() and strip() in Python
Difference split and strip has different usages. Split splits string into a list of substrings while strip removes any leading or trailing whitespaces like String sample = " hola " split() maxsplit parameter .split(maxsplit=1) This maxsplit parameter determines max number of splits to perform. Default is -1 but if you set value like 1, s... Read More
-
ThreadLocal to change Hibernate's query manually
##Issue Let’s say you need to change the parameter name while Hibernate makes the sql query for you. How do you do that? For example, we want to change some_log_table to some_log_table_20230303. How? We use ThreadLocal to pass in the parameter to Hibernate’s interceptor as such threadLocal.set(formattedDate) And once the formattedDate is fi... Read More
-
What is SQL truncate? What is its use?
What is SQL trunc? Whilst it has many usages, SQL trunc can be used to truncate(delete) part of your date/timestamp to a specified level of precision. For my case, my localdatetime was too precise to the point of milliseconds, while I needed just the date precision so I did TRUNC(log.CREATED_AT) Read More
-
Floyd Warshall algorithm
Floyd Warshall algorithm Floyd Warshall is used not only in finding shortest path between all edges but we can also use it to find transitive closure. Transitive closure of a directed graph represents basically the reachability between every pair of nodes in graph. Like from node a is it possible to reach till node m through paths. For example,... Read More
-
Greedy algorithms and practice questions
Greedy stack 2 pointer approach balloon question (sorting by end index) Practice question 큰 수 만들기 https://school.programmers.co.kr/learn/courses/30/lessons/42883 My first approach was not greedy but to generate all possibilities of combinations and sort and get the highest value. But time complexity was really bad here def solution(number, k... Read More
-
Kruskal algorithm for minimal spanning tree (MST)
Before Kruskal Before Kruskal, we need to understand how union find works. https://techblog-history-younghunjo1.tistory.com/257 is a good reference. Kruskal https://techblog-history-younghunjo1.tistory.com/262 This algorithm works on the principle that if parent of a is not equal to parent of b, then it does not form a cycle. Firstly we sort t... Read More
-
defaultdict(list) vs just dictionary
Difference The difference between graph = {} and graph = defaultdict(list) lies in the behavior when accessing a non-existing key in the dictionary. graph = {}: When using graph = {} to create a dictionary, if you try to access a key that does not exist in the dictionary, a KeyError will be raised. For example: graph = {} print(gra... Read More
-
Sorting and practice questions
Sorting 정렬 Often we use .sorted(some_array) and a lambda function together. When used together, sorted() and lambda functions provide a way to define custom sorting criteria. The lambda function is used as the key parameter of sorted() to specify the sorting key for each element in the iterable. The key function takes an element as input and... Read More
-
List and practice questions
.index() We use this to find which position this value is in a list. It returns the FIRST occurrence index of that value. for multiple indexes But if you have multiple occurrences and want to find multiple indexes, you can’t use .index() because it will just return the first occurrence. Instead we should go through the entire list with enumera... Read More
-
Queue and practice questions
Queue Declare deque We can declare queue with no initial data, or with a starting position. queue = deque() queue = deque([start_index, end_index]) queue = deque(some_list) .peek() = deque[0] We peek queue’s front-most element via deque[0]. Btw for stack it is [-1]. popleft() If using it as a queue, popleft() removes the front-most element. F... Read More
-
Stack (with deque) and practice questions
Stack Declare stack We can declare stack with no initial data, or with a starting position. stack = deque() stack = deque([start_index, end_index]) stack = deque(some_list) .peek() = deque[-1] Normally before you pop it like from a stack, you need to peek at the value. In Python, we just do deque[-1] pop() If using it as a stack, pop() remove... Read More
-
Dijkstra template and practice questions
Dijkstra Template It is very similar to BFS, but we use heap Practice questions 합승 택시 요금 https://school.programmers.co.kr/learn/courses/30/lessons/72413 def solution(n, s, a, b, fares): distance = [int(10e9) for _ in range(n+1)] graph = [[] for _ in range(n+1)] for fare in fares: start,end,cost = fare graph[start]... Read More
-
JPA cannot resolve column or table
Issue My yml file has set ddl to none. It should be create. I set it to none to save all the data when restarting server as not to wipe it out but when I made some entity relationships and want to make new tables, I need to set it to create so that it create the changes. Read More
-
What if we don't add @Column annotation to our fields? How are they mapped then?
No @Column Automatically @Column properties are applied but it is applied differently to Java primitive types where it blocks entering null values to primitive types Actually this goes back to the basics of Java where primitive types like int cannot hold value of null whereas reference or object wrapper class can hold null values. E.g. int da... Read More
-
Declaring role in SecurityFilterChain (I struggled with this a lot)
Problem Fuck this /listAdminView. So in my SecurityFilterChain, I explicitly specified only the roles of Admin to be able to access this page. I thought there was something wrong with my implementation so I tried all sorts like .antMatchers(“/users/listViewAdmin”).hasRole(ADMIN.getValue)) I checked my DB and UserStatus of ADMIN was saved j... Read More
-
Dictionary (+Counter) and practice questions
Dictionary Counter Counter is a subclass of dictionary and thus has all methods of dictionary. We can actually compare Counter object with dictionary with == for i in range(len(discount)-9): if dic == Counter(discount[i:i+10]): answer += 1 And Counter is a dictionary-like object, which means it looks something like Counter({'misl... Read More
-
return new String(array) when you modified array
Precautions If you modified string to a char array, and you want to return the modified char array, do return new String(array), not just return s. Technically s is not modified - it is the char array that is changed. This example public class Solution { public String reverseVowels(String s) { Set<Character> set = new... Read More
-
Using helper functions in python and updating return value
Error Let’s look at this helper function. I have declared count_iter outside my function and this recursive function calls upon itself. At the last recursion, after check() is done, we return count_iter and it would have incremented throughout the recursion process up to like 4. We return 4 and count_iter value is 4. Then, that process is popp... Read More
-
List index out of range (list initialised wrong!)
Error Actually this all arises from initialised a list in the wrong way. parent = [0 * (length+1)] for i in range(1,length+1): parent[i]=i The expression 0 * length+1 is a single element ‘0’. So when I try to access beyond the first index, I get the “index out of range error”. The right way should be parent = [i for i in range(length+1)] Read More
-
Convert dto to entity and vice versa with MapStruct
Dilemma At work and toy project, I have been manually implementing methods to convert DTOs to entities and vice versa by mapping each field manually. But there is tool that can aid this burdensome process - ModelMapper and Mapstruct. But I heard Mapstruct is better in terms of API speed, no reflection and certain fields (like phone number th... Read More
-
List as method argument and parameter in Python
Explained I was confused with Python cuz in Java, you need to delcare the data type in your method parameter like public int hola(int bitch, List<Integer> list){ } But in Python, be it list or any other data types, you don’t need to. # you can call your bfs function like this, inserting method argument of # place and list of row... Read More
-
Appending return value to list in Python
Appending return value to list in Python Let’s take a look at this example where I am doing a DFS search where if a certain condition is met like if node is already visited or dx dy is out of the grid, I want to return False. If it passes all checks, it is worthy to return True. I just want one return value for that one particular DFS search po... Read More
-
Python coding test prep for Java main users
List Comprehension Without: def solution(n): for i in range(1,n): if n%i ==1: return i With: def solution(n): return next(i for i in range(1, n) if n % i == 1) # or def solution(n): answer = min([x for x in range(1, n+1) if n % x == 1]) return answer List append() = append() Same as java, it is append() to a ... Read More
-
When should your repoImpl extend Querydsl querydslrepositorysupport?
Issue Your repoimpl should extend querydslrepositorysupport when you need some advanced querydsl functionalities - BooleanExpression and Predicate class to make your custom queries. For example if you need filtered search queries on certain conditions passed by your conditiondto like select(logs.*, clientInfo.clientId, client.clientName) .fr... Read More
-
Appending list to list in Python will not work
Lists are mutable objects in Python Take a look at this example nums = [1,2,3] visited = [False for _ in range(len(nums))] ans = [] path =[] def dfs(nums,path,visited): for i in range(len(nums)): if len(path) == len(nums): # issue here ans.append(path) return if not visited[i]: ... Read More
-
Querydsl noSuchMethodException
Issue querydsl expressionexception iarstatisticswithpartnerdto with root cause java.lang.nosuchmethodexception So I was encountering that exception error when I was using querydsl in my repo. I have placed @Data annotation on my DTO, which I have been doing for my toy project as well and found no problem. But upon googling, I found that ... Read More
-
insert number does not match select in Querydsl JPA
Issue So i was trying to insert into columns of my stats table the data taken from serviceLog when I saw this error. I first checked if there is an extra field that I was trying to insert. But the field number was the same at 14. Then I just deleted all fields except one field just to test if just a single field can be inserted without prob... Read More
-
How to set up Querydsl in your Spring Boot gradle project
Set-up Querydsl setting and getting all columns of User entity except password column Follow this guide https://velog.io/@peppermint100/JPA%EC%99%80-QueryDSL And this https://data-make.tistory.com/728 yml file plugins { id 'org.springframework.boot' version '2.6.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' // 2... Read More
-
Error - no ParameterResolver registered for parameter error
Error I got this error while running a test case. Turns out I was passing a method parameter that was not used anywhere in the test code block. Once I removed it, the error was gone. Read More
-
Mockito
Intro of Mockito (to be added) 더 간단하게 표현하자면, @InjectMocks는 테스트 클래스에서 테스트의 대상이 되는 인스턴스를 생성할 때 사용한다. @Mock은 해당 테스트를 진행하는데 보조적으로 필요한 부분들에 대해 mock 객체를 생성할 때 사용한다. Read More
-
NullPointer with Spring Security's loadUserByUsername
Problem Spring Security login error of invalid username and password and a NullPointerException that loadUserByUsername was getting null. Solution So the issue is that my User entity, I am using “userId” as a field, not “username”. But Spring security login requires the explicit naming of “username”, not “userId”. I tried changing the userId... Read More
-
Careful with Spring Security's SecurityFilterChain (front slash for url!)
ALWAYS put front slash at start of URL For Spring security’s SecurityFilterChain, PLEASE PLEASE PLEASE be careful with the url. The url has to start with front slash / like “/users/listViewAdmin”. I did not place front slash in front of my url like .antMatchers(“users/listViewAdmin”).permitAll() //should be /users/listViewAdimin so I was conf... Read More
-
Comparing 2 strings in thymeleaf
String comparison in Java As you know in Java, we cannot compare 2 strings with the == equal operator. The == operator is used to compare object references, not the primitive values. So effectively it checks if they have the same memory address, which they don’t. String comparison in Thymeleaf If you want to compare 2 strings in thymeleaf with ... Read More
-
Error Neither BindingResult nor plain target object for bean name '...' available as request attribute
Solution Controller.java 에서 @ModelAttribute 있는지 확인. @RequestMapping(value="/register") public String join(@ModelAttribute("memberVO") @Valid MemberVO memberVO, BindingResult bindingResult){ BTW no need to initialise name for @ModelAttribute(“memberVO”) because it automatically takes the parameter as its name (key). But if you want another... Read More
-
Spring Security's default Login page feature
Initial confusion when using spring security, whenever I start the Java application it kept prompting me to a /login page that prompted me to enter a username and password. But I have never made this html file before so I was confused. Spring Security comes with default login feature Actually, this is the default page that you HAVE to authen... Read More
-
Error - preparing SQL statement
Error At the repository level, I usually place @DataJpaTest instead @SpringBootTest as it is lighter than running everything with @SpringBootTest. But I got this error Error - preparing SQL statement. I was using H2 DB. Solution Change @DataJpaTest to @SpringBootTest as recommended here. https://velog.io/@jwkim/spring-boot-datajpatest-error T... Read More
-
Set up directories in your Spring project properly
The error How I knew about this was through an error in test case. @Autowired was not working for my test case. The error of “could not autowire no beans of type repository found test case” kept popping up. StackOverflow recommended a @ComponentScan(basePackages=”com.gbc.atdd.repository”) but still, it didnt work. Solution Turns out, th... Read More
-
Setting up H2 database
Set up H2 DB First create jdbc:h2:~/test (최초 한번). Follow this exact format. This creates file directory to initialise H2 DB. Then 이후부터는 jdbc:h2:tcp://localhost/~/test 이렇게 접속. For example, jdbc:h2:tcp://localhost/~/codingmates Read More
-
How to cleanly convert Dtos to Entities and vice versa
Solution Simple, use builder patterns and inner static methods. For example in my toy project, let’s say we are sharing bi-directional @ManyToOne relationship between project and recruitment. @Entity @Getter @NoArgsConstructor(access = PROTECTED) public class Project extends BaseTimeEntity { @Id @GeneratedValue(strategy = IDENTITY) ... Read More
-
JPA 양방향 연관관계 편의 메소드
Intro fuck I have been so confused with 양방향 mapping, even more so with the usage of Dtos but here it is Explained What I mean by 연관관계 편의 메소드 is that let’s say project and recruitment shares a @ManyToOne relationship like this @Entity @Getter @NoArgsConstructor(access = PROTECTED) public class Project extends BaseTimeEntity { @Id @Gen... Read More
-
What is ArrayList<Integer>[] or StringBuilder[]? What is this square bracket's role?
Explanation It was hard to google it because google search doesnt work well with symbols. However, I found out that ArrayList<Integer>[] G = new ArrayList[n]; StringBuilder[] st= new StringBuilder[numRows]; is actually just making an array of ArrayLists or StringBuilders. The main difference between ArrayList[] and ArrayList is that th... Read More
-
Java regex
W It matches any non-word character like * or # or whatever. It can be used with other methods like //paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." String[] words = p.toLowerCase().split("\\W+"); s It matches any whitespace character. We can use with .split() to split string via whitespaces like: String str = "Hello, Wo... Read More
-
Deducing ternary operator in Java
Deduction I was solving maximum subarray question when I found a useful explanation to break down and deduce ternary operator. public int maxSubArray(int[] nums) { int n = nums.length; int[] dp = new int[n]; dp[0] = nums[0]; int max = dp[0]; for(int i=1;i<nums.length;i++){ //this is deduction of ternary operator ... Read More
-
Useful Java data conversion tricks
Character.isDigit() boolean isDigit(char ch) checks if this character is a digit while(!queue.isEmpty()){ char c = queue.poll(); if(Character.isDigit(c)){ num = num*10 + c - '0'; } check if char char c >= '0' s.charAt(i)-‘0’ When converting character (e.g. ‘3’) to integer to use as index in array, have to subtract ASCII... Read More
-
Bucket sort
Issue While I was solving this, I came across the need to somehow solve this in linear time. The question requires sorting the map’s value, which stores the frequency of that integer. This reference explanation explained really well. Without bucket sort (using PQ) class Solution { public int[] topKFrequent(int[] nums, int k) { Map&... Read More
-
Double brace initialisation in Java
Tada Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); is same as: //Map<Integer, Integer> map = new HashMap<>();; How? It is actually called double brace initalisation which is discussed in https://leetcode.com/problems/continuous-subarray-sum/solutions/99499/java-o-n-time-o-k-space/?orderBy=most_votes com... Read More
-
How to change and run different configurations in multi-module Spring project?
Solution For my toy project, the default configuration that the app runs is test. But I want to change to “dev” to check if it works before building and deploying jar file onto AWS. How do I change the configurations? And under active profile, type “dev”. No need to type every dev profile like member-dev, project-dev, etc. Just dev. Read More
-
Spring Interview Questions
Let’s go What is Spring framework? It is an open-source framework that allows convenient Java programming. 1) Can maintain Java objects (beans) as a lightweight container Each object(bean)’s lifecycle like creation and destruction is maintained and a wanted object can be received from Spring. 2) Through IoC, allows decoupling of application... Read More
-
Java Interview Questions
Let’s go Serialisation Serialization is the conversion of the state of an object into a byte stream; deserialization does the opposite. Stated differently, serialization is the conversion of a Java object into a static stream (sequence) of bytes, which we can then save to a database or transfer over a network. Read More
-
Useful Java data type functions for coding test
Library import java.util.*; import java.io.*; Declare variables int len = hola.length; String[] arr = new String[len]; int[] arr2 = {1,2,3}; Arrays int arr[] = {10, 8, 11, 2, 3, 0}; // 1. ascending {0, 2, 3, 8, 10, 11} Arrays.sort(arr1); // 2. descending {11, 10, 8, 3, 2, 0} Arrays.sort(arr1, Collections.reverseOrder()); // 3. 일부만 정렬 {2,... Read More
-
application.yml for Multi-Module (feat. AWS RDS settings)
Intro There will be multiple yml files for each of your modules. For example, in module-member, I have 3 yml (test,dev,local) and so in each module I have 3 yml files. However, let’s go back a step. Before we did multi-module, there was 1 single yml file for our application. This is located in the very bottom src folder where our mainApplicatio... Read More
-
Sliding window
There is a list of sliding window question list at the end. Explanation Sliding is commonly used in problems that involve finding a subarray or substring that satisfies specific conditions. https://learning-e.tistory.com/36 1) Subarray/Substring Sum Problems: Find a subarray or substring with a given sum, sum within a certain range, or the m... Read More
-
JPA's Transactional and precautions
Reference https://mommoo.tistory.com/92 Transaction First of all, what is transaction? Some 작업 needs to be executed without any error. But if an error does occur in the middle of execution, transaction helps roll back the changes right before the error occurred. What does transcational do 1) transaction begin, commit을 자동 수행해준다. 2) 예외를 발생시키면, ... Read More
-
Quick union (not quick find)
Concept This explains well This virtual explanation too https://techblog-history-younghunjo1.tistory.com/257 Python version Template def find_parent(parent,x): if parent[x]!=x: # path compression parent[x] = find_parent(parent,parent[x]) # without path compression return find_parent(parent, parent[x]) ... Read More
-
Bfs
layout: post title: BFS template and practice questions category: Data structure & Algorithms tags: Data structure & Algorithms Intro Use queue for BFS to find the shortest something and when weight to travel nodes is constant like one. Dijkstra is also finding the shortest something but when weights are not constant fo... Read More
-
String useful methods and practice questions
String Generally speaking, 2 pointer method is useful in String questions. split() whatever_string.split() automatically splits this string into a LIST of substrings based on whitespace characters so unlike java, no need .split(“ “) no append() or pop() method in string We cannot use append() or pop() method in strings because strings in Pytho... Read More
-
How to link domain's name server to AWS Route 53
Reference https://hannut91.github.io/blogs/route53/gabia Read More
-
What is deadlock?
Deadlock In multi-threaded programming, locks are obtained through synchronization to prevent resource use in multiple places. Two or more threads are waiting to acquire a lock, and the threads holding the lock are also blocking each other while waiting for another lock. (e.g. operation1 has lock1 and waits to acquire lock2, operation2 has lo... Read More
-
Use Deque over Stack in Java!
Explanation This reference explains why deque should always be chosen over stack. Stack extends Vector class, which is an old, deprecated class. Just use deque, I think its methods are more intuitive too. Difference in methods Let’s take this as example. It can be solved via both stack and deque. Stack: class Solution { public String rem... Read More
-
What is thread in Java? (feat. process)
Process It is an instance of program is loaded into memory and runs. It is a unit of work that allocates system resources from OS. Each process is allocated an independent memory area (code,data, stack,heap) and has at least 1 thread (main thread). Each process also runs in a separate address space so to access variables, etc, they need to co... Read More
-
DFS and practice questions
Precautions Btw if input is given like [“X591X”,”X1X5X”,”X231X”, “1XXX1”] and we should convert it to 2d graph representation like this def convert_to_graph(lst): graph = [] for row in lst: graph.append(list(row)) return graph Also really important for the boundary check of 2x2 graph. The problem lies in the condition nex... Read More
-
General approach to backtracking + template
I was solving palindrome partitioning when I decided to compile some notes for backtracking. Backtracking There are 3 main steps in backtracking - choose, explore, unchoose. For this problem: 1) we choose each substring 2) we explore the remaining substring 3) do opposite operation of choose Normally, we make a helper() function to accept mo... Read More
-
GarbageCollection in Java (feat. stack and Heap)
숨참고 love dive~ Garbage Collection We have talked about stack and heap and how heap stores all the objects that are created, and stack stores the methods and local variables. But what happens when we destroy objects once we are done using them? Unlike C/C++ languages, Java does not require developers to explicitly free objects. It is also a g... Read More
-
Spring ConstraintViolationException error solution
When I was making a test case for saving a project post in my ProjectRepository, this error popped up: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement Dafuq? I googled and the... Read More
-
Linux ln -s (Symbolic link)
Intro Symbolic link is basically Window’s shortcut icon. If you have a file path or name that is very long, it helps to register that name with a simple short name. How to use ln -s [that long file path or name] [short name u wanna give] Example If you need to frequently access this file ~/test/test2/test3/test4/example_documents_of_symbolic_... Read More
-
How to save time in for loop?
Issue I was solving this leetcode and my code is: class Solution { public int integerBreak(int n) { int[] dp = new int[n+1]; dp[1]=1; for(int i=2; i<=n; i++){ for(int j=1; j<=i/2; j++){ dp[i] = Math.max(dp[i], Math.max(j,dp[j]) * Math.max(i-j, dp[i-j])); } } ... Read More
-
How does reference variable work when adding it to list
Issue I was solving this leetcode when I was baffled by the solution. class Solution { public int[][] merge(int[][] intervals) { Arrays.sort(intervals, (a,b)->Integer.compare(a[0],b[0])); int[] newInterval = intervals[0]; List<int[]> list = new ArrayList<>(); list.add(newInterval); for(... Read More
-
Applying SSL cert on AWS Load Balancer
Let’s apply SSL cert on AWS ALB Target group Assign your EC2 instance(s) as target group for the load balancer to distribute traffic. Also, HTTPS works only for domains like codingmates.com. It does not work for pure IP addresses like 3.18.bla bla. Domain has to be linked with the IP address of the EC2 server. I thought domain has to be linke... Read More
-
Protected annotation
Protected JPA allows Protected as constructor of entity to prevent other ways of creating new object. This can be replaced with Lombok’s @NoArgsConstructor. @NoArgsConstructor(access = AccessLevel.PROTECTED) Read More
-
How to build graph with lambda?
Approach I was solving this to build a graph, given some edges. here Without lambda, for each edge, we create a temporary list and add the edges both ways (e.g. [0,1] and [1,0]). Then, we add that list to our HashMap called graph, the key being the starting and ending point of edge. private Map<Integer, List<Integer>> createGraph(i... Read More
-
Dynamic Programming error
Approach This example my solution: class Solution { public int minimumTotal(List<List<Integer>> triangle) { int row = triangle.size(); int col = triangle.get(row-1).size(); int[] dp = new int[col]; dp[0] = triangle.get(0).get(0); for(int i=1; i<row;i++){ List<Integer>... Read More
-
Does HashMap allow duplicate keys when putting same key with different value?
Explanation This reference explains really well. HashMap does NOT allow duplicate keys so when we try to Map mymap = new HashMap(); mymap.put("1","one"); mymap.put("1","not one"); mymap.put("1","surely not one"); System.out.println(mymap.get("1")); We get “surely not one”, the latest value. Why? The map simply drops its reference to the v... Read More
-
How to convert ArrayList to array?
Example Suppose we have a ArrayList of type integer array like this: List<int[]> list = new ArrayList<>(); we use .toArray method to convert List instance to array list.toArray(new int[list.size()][]); If list.size() is 4, it creates an array of size 4. Read More
-
ASCII value in Java and how to store in array of size 128 or 256?
ASCII value ASCII represents a numeric value for each character, like 65 is a value of A. ASCII is a 7-bit character set having 128 characters, i.e., from 0 to 127. Storing in integer array of size 128 int[] array = new int[128]; for(int i=0; i<s.length();i++){ array[s.charAt(i)] = i+1; } Using string.charAt() method, we can store ea... Read More
-
What is DTO and its difference between VO?
Diff between DTO and VO VO has the same concept as DTO, but has read only properties. VO is an object that contains specific business values, and DTO is an object that comes and goes for the purpose of communication between layers. Why use DTO? 1) Circular referencing can be prevented - if you use bidirectional references 2) Can encapsulate int... Read More
-
XOR in Leetcode string or character
Read this first This visual explanation explains really well Explanation So a XOR a becomes 0 because you know 1^1 = 0 (exclusive OR). So when you want to find the extra character in t that s does not have, c ^= s, c^= t will rearrange itself to c ^= 5^5 ^ 1^1 ^ 2^2 ^4 which XOR with itself gets cancelled out, leaving that extra character beh... Read More
-
Classappend and No-operation (_) in Thymeleaf
Purpose of th:classappend and no-operation (_) Referring back to my previous example of checking validity of input fields by user Observe this html with no-operation (_) <input type="text" th:classappend= "${errors?.containsKey('itemName')} ? 'field-error' : _" class="form-control"> Through classappend, if there is an error with a pa... Read More
-
How to handle entity inside DTO?
ManyToOne relationship between projects and member. I want to include member entity inside ProjectDto to be passed to controller. How do I do this? initial,wrong code: @Getter @Setter @NoArgsConstructor public class ProjectDto { private String title; private String content; private Blob contentBig; private Long views; priv... Read More
-
Safe Navigation Operator (?) in Thymeleaf to prevent NullPointerException
Intro Let’s say we made a item register form for users to input 2 fields - price and quantity. We want to validate these 2 fields if they indeed make sense. The server will check this validation logic when POST /add comes and if it passes, it will use PRG pattern and redirect users to Redirect /items/{id}. If it fails, the form will be shown ag... Read More
-
Mistake in dealing with HashMap
Example This example My initial solution: class Solution { public boolean canConstruct(String ransomNote, String magazine) { Map<Character,Integer> map = new HashMap<>(); for(char c:magazine.toCharArray()){ map.put(c, map.getOrDefault(c,0)+1); } for(char c:ransomNote.toCharArray()){ ... Read More
-
Could not resolve placeholder 'test.name' in value "${test.name}"
Error When I was setting up S3 with my toy project in Spring Boot, this dreadful error kept popping up. Could not resolve placeholder ‘test.name’ in value “${test.name}” I met this dreadful error many times when setting up values of JWT token by getting them from application.yml file so I was annoyed. Solution Here was my wrong applicatio... Read More
-
5 main Dynamic Programming patterns and templates
Pattern This leetcode post explains the 5 main patterns. 1) Minimum (Maximum) Path to Reach a Target 2) Distinct Ways 3) Merging Intervals 4) DP on Strings 5) Decision Making Min/Max path to reach a target Read More
-
Binary Search explained
Binary search original template start vs start -1 Ok before this lemme explain what start really means in binary search. We are NOT going to use end pointer cuz it is complicated and start pointer is sufficient. So firstly, we have the 2 common templates - start<end or start<=end. If you start with start<end, when that search ends, at... Read More
-
What is Dependency Injection and how to do it via constructor?
DI It refers to a specific implementation of Spring’s IOC container that is used to reduce dependencies between objects. A reminder of IOC is that the IOC container, not the developer, manages the instance from creation to destruction. This IOC container is injected through DI. Java bean Java objects created and (destroyed eventually) managed... Read More
-
How to upload files to S3 on Spring Boot project (from set-up to controller)
Intro This easy reference is an easy guide but it provides really basic logic so I plan to add on more complex logic here. This guide is separated to 2 parts - AWS and Spring AWS Let’s get it Make S3 bucket on AWS One thing to note is don’t block all public access because if we do, we can’t access it from our Spring Boot project. Once S3 has ... Read More
-
Error in declaring variables in 1 line
Error I was solving some Leetcode when I declared variables in 1 line like this: int len=0, min=Integer.MAX_VALUE, from=0; All my logic was right but strangely it didn’t work. Turns out the error is probably due to that min being declared in the middle Like this works int sum=0, from =0, min= Integer.MAX_VALUE; Read More
-
Difference between Spring filter and interceptor?
Diff There is a difference at the time of execution. Filter is executed before a request goes to the dispatcherServlet, and an interceptor is executed before a request goes to the controller. Normally, to use them commonly, we just use them to process tasks before entering controller but still, there is a difference at the time they are actuall... Read More
-
Uploading your local source code to Github repo
Reference Btw you have to create a repo FIRST before you can do git init. https://coding-factory.tistory.com/244 Read More
-
Spring Events and what are they?
Why do we use @EventListener? We use it to separate layers of business logics that are highly dependent on one another. For example, let’s say when A Service runs A business logic, it requires B Service’s B business logic. In this case, we need to DI B Service into A service, placing B logic into A logic. This is not ideal because it is becom... Read More
-
How to use .gitignore to hide sensitive files in Spring Boot
Introduction I made a horrible mistake in uploading my AWS secret key and access key in my application.yml file to github repo. All chaos followed suit as both AWS and Github sent me emails that my keys have been exposed. And there were hacking attempts by bots to use my keys. Thus, it is a lesson to be learnt and I will discuss how to prevent ... Read More
-
Authorisation with Redis
Why Redis? Let’s look at this example: Long memberId = tokenProvider.getMemberIdByToken(jwtToken); Member member = memberRepository.findById(memberId); When there is minor or no change to DTOs, it is not worth and computationally unnecessary and expensive to pass DTO to DB and authorise every time. We know that this member is really that aut... Read More
-
Git upstream
Introduction reference: https://stackoverflow.com/questions/5181845/git-push-existing-repo-to-a-new-and-different-remote-repo-server How I did it 1) first go to your new repo 2) git remote rename origin upstream 3) git remote add origin URL_TO_Your_OLD_GITHUB_REPO 4) git push origin master To be explained more later.. Read More
-
Dynamic Programming explained
Approach 1) Remember to ALWAYS set default values as starting points for our DP iteration (e.g. dp[0]= sth) Template Let’s take this Fibonnaci example It is good to get the logic first and start from recursive, then implement memoisation for DP. Lastly, iterative solution would be the best. Another example is house robbers Practice questions... Read More
-
Order of operator in Java (e.g. order matters in &&)
Reference https://park-youjin.tistory.com/11 This reference lists order of all operators in Java. Let’s look at the and (&&) operator in particular in this Leetcode problem Order in && Notice this code solution class Solution { public int countBattleships(char[][] board) { int m = board.length; if(m==0) retu... Read More
-
What is Object-oriented programming (OOP)?
OOP definition It is a programming method that abstracts the data needed in programming to create objects with 1)states and 2)behaviors. It configures logic through organic interactions between those objects. Advantages of OOP Through inheritance, encapsulation and polymorphism that OOP provides: 1) Reusability of code - can import and use c... Read More
-
SOLID principles of object-oriented design
Reason for SOLID principles Design principles encourage us to create more maintainable, understandable and flexible software. Consequently, as our application grows in size, we can reduce their complexity (and saves us from headaches down the road!) The 5 concepts are: 1) Single Responsibility 2) Open/Closed 3) Liskov Substitution 4) Inter... Read More
-
Error with ModelMapper and solution - Parameter 1 of constructor in Service class required a bean of type 'org.modelmapper.ModelMapper' that could not be found.
Initial wrong code public class AppConfig { @Bean public ModelMapper modelMapper(){ return new ModelMapper(); } } Solution I have not properly registered my Bean. Whilst I declared my ModelMapper as bean method, I have not annotated my class with @Configuration. @Configuration public class AppConfig { @Bean public... Read More
-
Careful with ternary operator
Issue I was doing some Leetcode when I had Compile error regarding some arithmetic errors. java.lang.ArithmeticException: / by zero My code: //long a = leftSum / (i + 1); //long b = length-i==1 ? 0 : rightSum / (length-(i+1)); long diff = Math.abs(leftSum / (i + 1) - length-i==1 ? 0 : rightSum / (length-(i+1))); if(diff<min){ min = diff... Read More
-
A MUST check when setting up AWS RDS (or you will get Fatal Error 3000:0 - No such database found)
I have faced this problem multiple times when setting up AWS RDS. When I tried connecting to DB for the first time (via IntelliJ), there was this error: Fatal Error 3000:0 - No such database found Solution: Please please please! Make sure to initialise database name at the additional configuration section at the end of the set-up page. It is ... Read More
-
Difference between ArrayList and LinkedList
Difference between ArrayList and LinkedList The LinkedList class is a collection which can contain many objects of the same type, just like the ArrayList. The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, change items, remove items and clea... Read More
-
Basic JPA annotations you should know (e.g. PersistenceContext, Transactional, etc)
@PersistenceContext to DI EntityManager @PersistenceUnit to DI EntityManagerFactory @Transactional can add “readOnly=true” to apply to all methods in that class that are only for read usages (NOT write usages) If there is write method, need to delcare exception via adding @Transactional to that method I explained more on my previous post on ... Read More
-
Java's ListNode in Leetcode
WTF is ListNode?? I am just so frustrated with this ListNode concept in Leetcode so lemme arrange this notes. Sample Solution This is commented solution for Leetcode 19’s Remove Nth Node from end of list. class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); // 더미 노드 하나 생성 Li... Read More
-
H2 db connection with application.yml
my .yml didnt work and my h2 db table was not created when I try running the server spring: # profiles: # active: local h2: console: enabled: true datasource: url: jdbc:h2:tcp://localhost/~/codingmates # url: jdbc:h2:~/codingMates driver-class-name: org.h2.Driver username: sa password: jpa: properti... Read More
-
Overloading method
Overloading method There is no polymorphism involved here. Overloading means having 2 methods with same name but different argument list. Overloading lets you make multiple versions of a method, with different argument lists, for convenience to the callers. For example, if you have a method that takes only an int, the calling code has to conve... Read More
-
Problem of overflow with lambda
Issue I was using Lambda to sort order of elements going into my priority queue. PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]); While it will work perfectly fine in most cases, it can cause overflow issue. It should return positive number if a[2] > b[2], but if a[2] - b[2] > Integer.MAX_VALUE, then ... Read More
-
Error-BeanCreationException at AbstractAutowireCapableBeanFactory
When there were multiple .yml and .properties, .properties-local files, I got this error: Caused by: org.springframework.beans.factory.BeanCreationException at AbstractAutowireCapableBeanFactory.java I deleted all the .properties files until there was only 1 .yml file and the remaining errors were resolving the paths of values in conflicted cl... Read More
-
Nginx Basic commands
Nginx Basic commands nginx -t # nginx 설정 파일의 문법이 올바른지 확인 sudo service nginx status # nginx 상태 확인 sudo service nginx start # nginx 실행 sudo service nginx restart # 중지 후 재실행 sudo servcie nginx reload # 수정된 파일 적용하여 연결을 끊지 않고 재실행 sudo service nginx stop # nginx 중지 # 기본적으로 Nginx는 서버가 부팅될 때 자동으로 시작됩니다. sudo service disable nginx # 자동 시작 비활성화 s... Read More
-
Can we have 2 Lombok's @Builder in 1 class?
I had this class. Just take a look at the order of the @Builder. @Entity @Getter @NoArgsConstructor(access = PROTECTED) public class Project extends BaseTimeEntity { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "project_id") private Long id; @ManyToOne(fetch = LAZY) @JoinColumn(name = "member_id") private... Read More
-
JPA repository.save is Null (NullPointerException) - feat. @RunWith & @SpringBootTest & @DataJpaTest
While I was creating a test case for my JPArepository to save a post in my toy project: @Autowired private ProjectRepository projectRepository; @Test public void createPost(){ //given projectRepository.save(Project.builder() .title("hi") .content("testing") .build()); //wh... Read More
-
How to deploy Spring jar app to AWS
Finally arranging this so that I don’t have to google it again!! Intro We are using Ubuntu server with Spring jar. So the linux commands will all be “apt-get”. Build jar file On the right tab of IntelliJ, click Gradle -> Build -> Build. Click on that grid icon and jar file will be built in the libs folder. FileZilla to move jar file Onc... Read More
-
Comparator VS Lambda
Issue There is the problem of overflow with Lambda as discussed in my last post. Whilst lambda should be avoided in interviews, it can serve a simple sorting purpose than Comparator. But let’s see the difference in implementing those 2. Comparator For example, in this leetcode we are sorting the strings in string array. BTW, if s1=”9” and s2=... Read More
-
How to deploy Spring app (jar file) with Docker
Let’s dive in Intro Make a Dockerfile at the root directory Reference https://velog.io/@solchan/Docker-SpringBoot%EC%99%80-Nginx-Docker-Compose%EB%A1%9C-%EC%84%9C%EB%B9%84%EC%8A%A4-%EC%98%AC%EB%A6%AC%EA%B8%B0 Read More
-
NEVER put LocalDateTime into DTOs!
Putting LocalDateTime fields into DTOs can cause deserialisation issue. Read More
-
docker push denied - requested access to the resource is denied
Let’s dive in Issue Using default tag: latest The push refers to repository [docker.io/asdfaasdf/kubia] 6bb2a0932f1d: Preparing ab90d83fa34a: Preparing 8ee318e54723: Preparing e6695624484e: Preparing da59b99bbd3b: Preparing 5616a6292c16: Waiting f3ed6cb59ab0: Waiting 654f45ecb7e3: Waiting 2c40c66f7667: Waiting denied: requested access t... Read More
-
2 different ways to create 2D array (List vs ArrayList?)
First way List<Integer>[] graph = (ArrayList<Integer>[]) new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } for (int[] e : edges) { graph[e[0]].add(e[1]); graph[e[1]].add(e[0]); } Notice we cannot use ArrayList method’s get() like graph.get(). Instead, we manually enter the index via grap... Read More
-
Difference between NotBlank, NotEmpty and NotNull when validating DTOs
Why do we need to validate in the first place? What if we enter an age into a name field? If we don’t check the validity of incoming data into our planned appropriate fields, it may wreak havoc on the system. Example Let’s say we want a not-empty title for our post. We will use @NotEmpty which checks not just empty string and null but also emp... Read More
-
Spring MVC Basic Knowledge
Web Application Server WAS includes Web server functionalites and static resource managing Difference between web server and WAS is web server is mainly for static resource while WAS can have application logic Servlet does all except business logic Contact s... Read More
-
How does Spring MVC work?
MVC MVC pattern focuses on separating each layer’s function. Model manages data and business logic (DAO, DTO, Service) View handles the result of business logic and displays User Interface. Display can be html, jsp, Thymeleaf, etc or if the server is in REST API, JSON response Controller takes care of client’s request and connects Model with ... Read More
-
JPA 연관관계 편의 메서드
Without convenience methods Actually, JPA works just fine when we just input values into the 연관관계 주인. But it is not really Object-Oriented (OO) to just input value at the Many side. Also, until transaction.commit can be invoked and DB queries that data, the One side does not the know entity’s 연관관계 so if we try printing out the data in One side, ... Read More
-
JPA force DB query when entity is already saved in 1st cache
Solution As you know, when we em.persist(entity), we keep the PK as the key and the entity itself as the value in EntityManger. We can think of EntityManager as PersistenceContext, although it is different in some minor ways. Anyway, this entity is managed by EM and is saved in 1차 cache so that within the same database transaction, if another c... Read More
-
Jpawithoutentityrelationship
gi— layout: post title: JPA without entity relationships description: category: JPA tags: JPA Intro JPA without 연관관계 (entity relationships) like @ManyToOne ultimately cannot product object-orientated code. This is because we search up entities and update them on their primary keys. Without 연관관계 Let’s look at this example @Entity... Read More
-
JPA Table indexing
Indexing in tables Indexing makes columns faster to queries by creating pointers to where the data is stored in the database. Reference 1) how to apply indexes 2) how indexing works 3) choosing index on cardinality Read More
-
Spring Boot + JPA following Java's camelCase or DB's underscore when naming fields
Discussion Let’s see this example: @Entity public class Member{ @Id @GeneratedValue @Column(name="member_id") private Long id; private LocalDateTime orderDate; } Remember LocalDateTime is specially recognised by JPA and adds that field to be mapped to the entity? Anyway, look at this field name orderDate. The DB prefers n... Read More
-
JPA relationships in multi-module architecture (MSA)
JPA in normal cases Well in normal cases, we add JPA relationships like @ManyToOne, @OnetoMany, etc to our primary identifiers. For example in a unidirectional @ManyToOne relationship between Project and Member in my toy project: public class Project extends BaseTimeEntity { @Id @GeneratedValue(strategy = IDENTITY) @Column(name =... Read More
-
How to manage DTOs in Spring Boot well
Intro According to the API spec of project, we can have multiple forms of DTOs for Request and Response. So we can get multiple DTO files, which can be visibly messy to manage. Is there a way to combine all forms of DTOs into one file for better management? Yes, through static nested class! Note on nested class Take a look at My posted on nes... Read More
-
Java nested class
Intro A nested class is a member of its enclosing class (OuterClass). In simple terms, it is a class inside a class. This reference describes well about nested classes and its 2 types - non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. class... Read More
-
Spring Multi-module structure
Intro Place common code in the common module that can be shared by other modules. ApplicationContext error when testing When creating test cases within my module, I encountered an ApplicationContext error. That is strange, I am getting token errors like GoogleOAuth that I didn’t even use in my module. Well, even in tests, our module relies onl... Read More
-
What is Lombok's Builder and why do we use it?
Intro To know why Lombok’s @Builder annotation is developed, we first need to know the Builder Pattern. Builder Pattern It is one of the ways to create an object. When we need to create an object and several fields exist (like age, gender, name, etc), using a constructor needs to follow strict sequence of aligning method parameter. To solve thi... Read More
-
TCP port
TCP port and its importance A TCP port is just a number… a 16-bit number that identifies a specific program on the server 0–65535 ports can be made available on server. The most common is port 80, which HTTP runs on. So normally on our own server, we go with 1024 and 65535 because 0-1023 are reserved for well-known services like SSH, HTTP,... Read More
-
Docker's basic commands
Docker basic commands docker container run -p # opens up publish port where HOST:CONTAINER format docker container port name_of_container # quick port check docker container inspect --format "" webhost #check ip address of container, which is different from host. Format does the filter role like grep but is cleaner # opens up port on my mach... Read More
-
Spring JAR vs WAR
Jar vs War Jar always utilises internal server like Tomcat and does not use webapp. War can use internal server and is mostly used to deploy to external servers. If Jar is used, index.html in /resources/static serves as the Welcome page Read More
-
try/catch finally flow control
try/catch flow control Rest of the try block does not run if it fails and goes straight to the catch block. finally A finally block is where you put code that must run regardless of an exception. try { turnOvenOn(); x.bake(); } catch (BakingException e) { e.printStackTrace(); } finally { turnOvenOff(); } Without finally, you have to put t... Read More
-
Java's Exception handling
Intro So, how does a method tell you it might throw an exception? You find a throws clause in the risky method’s declaration. Risky methods that could fail at runtime declare the exceptions that might happen using “throws SomeKindOfException” on their method declaration. Try-catch to catch the exception Basically, I am gonna TRY this ris... Read More
-
Java's Optional
Intro Some operations may or may not return anything at all. To deal with this issue, use Optional! Optional is a wrapper Optional wraps the result so we can ask if that result is actually present or empty (null). Optional objects need to be asked if they conain something before you unwrap them. Otherwise, you will get an exception if there is... Read More
-
Method reference to replace lambda expressions
Sometimes don’t even need lambda via method reference Following up with my previous StreamLambda post Let’s look at the previous lambda expression for map operation Function<Song,String> getGenre = song->song.getGenre(); Instead of spelling this, you can point the compiler to a method that does the operation we want, using a method r... Read More
-
Difference between ModelAttribute and Model annotations
@ModelAttribute An object assigned with @ModelAttribute tag is automatically saved into Model. For Example: @PostMapping("/add") public String addItem(@ModelAttibute("item") Item item, Model model){ itemRepository.save(item); //model.addAttribute("item",item); // ^^this is automatically added so no need to write this return "items/it... Read More
-
IntelliJ Shortcut Windows
IntelliJ Shortcut for the cool kids using Windows Here are some useful shortcuts. Easy and common Code completion/Going to next line in the middle of code line ctrl+ shift + enter Normally to go to next line in the middle of code, you do right arrow + enter but use this shortcut above See method’s parameters ctrl + p Static import completion... Read More
-
Java Stream operation methods with examples
Intro Let’s look at some common methods Intermediary operations filling Ternary operations collect() with Collectors.toList as argument Not just to list, we have toSet and toMap. Also, if we want to ouput a collection that can’t be changed from the collect terminal operation, use Collectors.toUnmodifiableList, Collectors.toUnmodifiableSet, C... Read More
-
Java Stream with Lambda
Intro Following on my Stream post let’s create some complex pipelines with Lambda. Stream + Lambda We can customise the building blocks with Lambda Example with filter() Suppose we want to filter a list of Song objects by the genre that contains the word “Rock” and output it as a List. The filter method takes a Predicate. List<Song>... Read More
-
Java Stream Matching its values
There are 3 ways to validate elements of a sequence according to some predicate. Put it more simply, check elements for a specific condition. 1) allMatch() checks if ALL elements meet the predicate 2) anyMatch() checks if there is at least 1 element that meets predicate 3) noneMatch() checks if none meets the predicate public static void ... Read More
-
Good Spring practice to follow
Basic JPA If a business logic can be implemented in an entity class (e.g.implement in Item.java), then it is best case. This is called Domain Model Pattern. In ORM, it is not good to use @Setter to set values of variables but rather, using validation methods (usually business logic?) that set those values Read More
-
Java's Stream theory explained
Intro T is usually the Type of the object in the stream. R is usually the type of the Result of the method. How to use Stream? To use the Streams methods, we need a Stream object (obviously). If we have a collection like a List, this doesn’t implement Stream. However, the Collection interface has a method, stream(), which returns a Stream objec... Read More
-
Java's Convenience factory methods
Intro Convenience Factory Methods for Collections allow you to easily create a List, Set, or Map that’s been prefilled with known data. However, there are 2 precautions Precautions The resulting collections cannot be changed You can’t add to them or alter the values; in fact, you can’t even do the sorting The resulting collections are not the ... Read More
-
TreeSet- HashSet with sorting capability
TreeSet TreeSet is similar to HashSet in that it prevents duplicates. But it also keeps the list sorted. It works just like the sort() method in that if you make a TreeSet without giving it a Comparator, the TreeSet uses each object’s compareTo() method for the sort. But you have the option of passing a Comparator to the TreeSet constructor, to ... Read More
-
HashSet - Reference equality vs Object equality
Reference equality Two references, one object on the heap. Two references that refer to the same object on the heap are equal. Period. If you call the hashCode() method on both references, you’ll get the same result. If you don’t override the hashCode () method, the default behavior (remember, you inherited this from class Object) is that each ... Read More
-
Controller VS RestController
@RequestMapping If no HTTP method is allocated in @RequestMapping, all HTTP methods are allowed. If prohibited HTTP method is called, 405 (Method not allowed) is returned. Read More
-
Java's list, set and map
List Use when sequence matters Collection that knows index position can have more than 1 element referencing the same object (list[0]=”dog”, list[1]=”dog) Set when uniqueness matters Collection that do not allow duplicates Sets know whether something is already in the collection. You can never have more than one element referenci... Read More
-
Java Lambda
Intro With interfaces like Comparator, we only have to implement a single abstract method, SAM for short. These interfaces are so important that they have several special names: SAM Interfaces a.k.a. Functional Interfaces Functional interface is interface with Single Abstract Method If an interface has only one method that needs to be imp... Read More
-
Comparable, Comparator generics and Intro to Lambda
Intro Let’s say we want to sort a list of Song objects using Collections.sort() method. It definitely works for list of Strings but will it work for Song objects? NO! The sort method only takes list of Comparable objects. Song is not a subtype of Comparable so you cannot sort it. Not yet… A note on T extends Comparable A note is that String ... Read More
-
What is generics?
Intro Generics is often used to write type-safe collections. This means that compiler stops you from putting a Dog into a list of Ducks. All potential exceptions that may occur at runtime can be caught at compile time by restricting the instance type stored in the collection class (via diamond operator). Btw, generic means it is specified by us... Read More
-
Logging with Lombok's @Slf4j
Logging Logging level is TRACE > DEBUG > INFO > WARN > ERROR In development server, keep it at debug but in actual running business server, use info // application.properties logging.level.root = info logging.level.hello.springmvc = debug Read More
-
How to format numbers in Java (feat "%")
Format specifier A format specifier can have up to five different parts (not including the “%”). Everything in brackets [ ] below is optional, so only the percent (%) and the type are required. But the order is also mandatory, so any parts you DO use must go in this order. Btw, although type is the only required specifier, remember that if... Read More
-
What is entity and its precautions when designing in JPA?
Entity The Entity class is a class that is mapped 1:1 with tables in the actual database. It should only have columns that exist in the DB as attributes. How are entities mapped? @JoinColumn(name = “name_of_FK_joining_2_tables”) //Name is “team_id” or name of FK If you omit this attribute, JPA finds FK via Field name (team) + _ + table colum... Read More
-
Spring Controller and difference between Controller VS RestController
@Controller Issue For registering new users, I had aPostMapping controller of register function. I wanted whatever fields of UserRegisterDto were wrong, I want to have them printed out on the page itself. But whenever there was an error, i get a 404 page but the error appeared on the run console. Initial code: UserResponseDto userResponseDto... Read More
-
Primitive and how to wrap and unwrap (feat. ArrayList<Object>)
A note on primitive Sometimes you want to treat a primitive like an object. For example, collections like ArrayList only work with Objects: There’s a wrapper class for every primitive type, and since the wrapper classes are in the java.lang package, you don’t need to import them. You can recognize wrapper classes because each one is named after... Read More
-
Java's StringBuilder
StringBuilder Actually, stringbuilder can contain an array inside it as such: public String convert(String s, int numRows) { int index=0; StringBuilder[] st= new StringBuilder[numRows]; for(int i =0;i<st.length;i++){ st[i] = new StringBuilder(); } while(index < s.length()){ for(int i=0;i<numRows &... Read More
-
Final keyword on variable, method and class
Implications of final keyword A final variable means you can’t change its value. A final method means you can’t override the method. A final class means you can’ extend the class (i.e., you can’t make a subclass) If the class is final, you don’t need to mark the methods final. Think about it—if a class is final, it can never be subcla... Read More
-
yml file for setting up local, dev, production environment
Intro Without making 4 separate yml files, it is possible (and wise) to neatly combine into 1 application.yml file effectively. How to set up yml and its respective environments? //some common yml stuff for all 3 environments --- spring: profiles: active: local --- spring: profiles: active: dev --- spring: profiles: active: p... Read More
-
JPA p6spy dependency to fill JPA ? gaps
p6spy This useful external dependency helps fill in the gaps (?, ?) with the actual values. implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.5.6' Read More
-
Meaning of static variable and method and how to initialise them
Intro Methods in the Math class don’t use any instance variable values. And because the methods are “static,” you don’t need to have an instance of Math. All you need is the Math class. Java is object-oriented, but once in a while you have a special case, typically a utility method (like the Math methods), where there is no need to have an ... Read More
-
How long does object live?
Introduction Object’s life depends 100% on the life of references that refer to it. If object’s life depends on the reference variable’s life, how long does variable live? It depends if it is local variable or instance variable. Local variable 1) It lives only within the method that delcared the variable. public void read(){ int s = 42; ... Read More
-
Difference between StringBuffer and StringBuilder
A note on Strings String is immutable so it cannot be modified once it is instantiated. To modify it, we can create and use StringBuffer or StringBuilder Difference StringBuffer is actually thread-safe in a multi-threaded environment by supporting the synchronisation. It means 2 threads cant call the methods of StringBufffer at the same time.... Read More
-
JPA application.yml Hibernate settings explained
JPA Hibernate settings Let me arrange some common settings with explanation. ddl-auto jpa: hibernate: ddl-auto: none / create Setting to none persists data in the db so can keep reusing it. Setting to create refreshes db each time so no data is saved. None is useful when you feel lazy inputting data over and over while testing. Read More
-
Make good CRUD APIs (feat. DTO)
Intro The Create (C) of CRUD is done in the previous post at 2022-03-31 How to create effective APIs with DTO? Let’s do the rest. Update (with DTOs) @PutMapping("/api/v2/members/{id}") public UpdateMemberResponse updateMemberV2(@PathVariable("id") Long id, @RequestBody @Valid UpdateMemberRequest request) { memberService.update(id, request... Read More
-
JsonIgnore annotation
How not to expose an entity’s field? Let’s consider this entity: @Entity @Data public class Member{ @Id @GeneratedValue private Long id; private String name; //@JsonIgnore @OneToMany(mappedBy= "member") private List<Order> orders = new ArrayList<>(); } If we get a list of members, we see that ... Read More
-
How to create effective APIs with DTO?
Intro Exposing our entities (Member, Project, Item) to our controllers is very dangerous and is a big NO-NO! So how do we set up controllers and DTOs? API Version 1 - Using Entity as parameter @RestController @RequiredArgsConstructor public class MemberApiController { private final MemberService memberService; /** * 등록 V1: 요청 값으로 Membe... Read More
-
Prevent multiple ways to initialise/create Object
Prevent multiple ways to create Object When there are multiple ways to create Object - either via constructor or a custom-made method, it can cause confusion when additional fields are added and makes it hard to maintain. For example: // public static OrderItem createOrderItem(your parameters){ //code to create this object } // and in y... Read More
-
All about HTTP
Internet Network IP protocol has several fall-offs. Even if the receiver is out of service or non-existent, the packet is still delivered. Also, packet might not be delivered in sequence as intended because it is too big and so it is cut into pieces and delivered separately. Also, in the middle of this packet delivery, som... Read More
-
JPA cascade
JPA cascade We can use this 영속성 전이 transitive persistence functionality when we make a specific entity as managed state by EM and want the related entities to be managed as well. For example, when we save parent entity, we want to save child entity at the same time for convenience. BTW, remember that for JPA to save entities, ALL related ent... Read More
-
How to call a constructor from another constructor within the same class (not from subclass)
Invoking overloaded constructor from another constructor within the same class stack overflow explained it well but let’s look at it more closely. It is through the “this()” keyword. class Temp { // default constructor 1 Temp() { System.out.println("default"); } // parameterized constructor 2 Temp(int x) ... Read More
-
Role of superclass constructors in an object’s life
Constructors in object’s inheritance tree All the constructors in an object’s inheritance tree must run when you make a new object. That means every superclass has a constructor (because every class has a constructor), and each constructor up the hierarchy runs at the time an object of a subclass is created. Saying new starts the whole co... Read More
-
When to add business logic to domain class, not service
Introduction I was so accustomed to creating all my business logic in my service class when I came across this unraveling news. For example, public class Item{ private int quantity; } @RequiredArgsConstructor public class ItemService{ private final ItemRepository itemRepository; public int updateQuantity{ //buisness l... Read More
-
How to test exception in test cases
Testing exceptions You can do this by adding the expected exception class to the @Test annotation. @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class MemberServiceTest { @Autowired MemberService memberService; @Autowired MemberRepository memberRepository; @Test(expected = IllegalStateException.class) public v... Read More
-
Difference between method size() and length()
Perfectly answered here: https://stackoverflow.com/questions/20192843/difference-between-size-and-length-methods size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don’t see the class normally), and length() i... Read More
-
JPA FetchType
When JPA fetches data, there are 2 options of FetchType - EAGER and LAZY. Intro of JPA FetchType The default for JPA FetchType is that @xxToOne - EAGER @xxToMany - LAZY FetchType is the default value of how to bring in the connected entities in 연관관계 when JPA searches for one specific entity. Through ORM, we don’t have to create the q... Read More
-
Enumerated annotation and its EnumType types
Enum reference: https://ttl-blog.tistory.com/115 When we use @Enumerated annotation to map Java’s Enum type, we have 2 EnumType types to choose from enum Gender{ MALE,FEMALE } EnumType.ORDINAL This saves the order of enum. So MALE = 0, FEMLAE =1 values are saved in the DB. Advantage: Saved data size is small since it is just integers... Read More
-
MOOC.fi Java Programming I Part 11
Part 11! Class diagrams A class diagram is a diagram used in designing and modeling software to describe classes and their relationships. Class diagrams enable us to model software in a high level of abstraction and without having to look at the source code. commonly use Unified Modelling Language (U... Read More
-
PathVariable annotation
2 most common ways that client sends parameters thorugh URL is: 1) http://ip?index=1&page=2 2) http://ip/index/1 . 1 is normally used in posts or pages whilst 2 is used in REST API. 1) is used by @RequestParam while 2) is used by @PathVariable @PathVariable Commonly used with REST API so type 2 It takes care of incomi... Read More
-
Java inheritance in JPA
Java inheritance We have looked at Java inheritance but let’s look at how it is applied to JPA good reference: https://www.baeldung.com/hibernate-inheritance Inheritance in JPA There are multiple strategies to choose from Single table strategy The Single Table strategy creates one table for each class hierarchy. JPA also chooses this strategy... Read More
-
MOOC.fi Java Programming I Part 10
Part 10 Handling collections as streams Stream is a way of going through a collection of data such that the programmer determines the operation to be performed on each value. No record is kept of the index or the variable being processed at any given time. like lambda long numbersDivisibleByThree = inputs.stream() ... Read More
-
Tips on application.yml
Logging 1) trace allows us to see what parameter values are passed. Without this, insert into member (username, id) values (?, ?) so here we don’t know what values are passed. With this, in the log we can see binding parameter [1] etc logging: level: org.hibernate.type: trace However, an alternative to actually see the values being sub... Read More
-
Command Query Separation
Introduction of CQS Reference: https://dundung.tistory.com/183, https://hardlearner.tistory.com/383, https://www.inflearn.com/questions/35961 Command Query Separation (CQS) is all about separating command and query. The reason to separate them is when there is an issue regarding unintentional changes made in data, we can just look at the metho... Read More
-
Constructor
Introduction - how are objects created? Let’s go back to how objects are created. polymorphism post //1) declare reference variable // Tells the JVM to allocate space for a reference variable. The reference //variable is, forever, of type Dog. In other words, a remote control that //has buttons to control a Dog, but not a Cat or a Button or a ... Read More
-
MOOC.fi Java Programming I Part 9
Part 9! Class inheritance An essential idea behind object-oriented programming is that solutions rise from the interactions between objects which are created from classes. An object in object-oriented programming is an independent unit that has a state, which can be modified by using the methods that the object provides. ... Read More
-
The Stack and the Heap - where things live
숨참고 love dive~ Introduction When a JVM starts up, it gets a chunk of memory from the underlying OS and uses it to run your Java program. How much memory, and whether or not you can tweak it, is dependent on which version of the JVM (and on which platform) you’re running. The Stack and the Heap Basically, area of memory where all objects live ... Read More
-
Invoking the superclass version of a method
What gives rise to needing the superclass version of method? Q: What if you make a concrete subclass and you need to override a method, but you want the behavior in the superclass version of the method? In other words, what if you don’t need to replace the method with an override, but you just want to add to it with some additional specific cod... Read More
-
How to differentiate class, a subclass, an abstract class or an interface?
When to differentiate these 4: Make a class that doesn’t extend anything (other than Object) when your new class doesn’t pass the IS-A test for any other type. Make a subclass (in other words, extend a class) only when you need to make a more specific version of a class and need to override or add new behaviors Use a... Read More
-
MOOC.fi Java Programming I Part 8
Part 8! Getting more advanced in this sub-section now (part 3 is v hard) Short recap recap of Java Programming I Hash Map HashMap is used when data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys. .put(some key, some value) adds key-valu... Read More
-
Interface
Introduction & Deadly Diamond of Death (DDD) From pg 565 of Head First Java gives reason to why inheritance is useful. Deadly Diamond of Death (DDD) arises from 2 superclasses (multiple inheritance) where a subclass does not know which method to use, that is declared the same in both superclasses. Interface A Java interface solves your m... Read More
-
Spring Devtools
Introduction Every time you make a change to HTML file, we need to restart the server to see the changes. But once you import Devtools, it saves all the trouble. Update October 5th 2022 This doesn’t work just for HTML files, you can recompile controllers as well without restarting server. How to set up Import the dependency into your build.gra... Read More
-
MOOC.fi Java Programming I Part 7
Last part of MOOC.fi Java Programming I! Programming paradigms Object-oriented programming(OOP): info is represented as classes that descibre concepts of problem domain and logic of application. Classes define the methods that determine how information is handled. During program execution, objects are instantiated from cl... Read More
-
Casting Polymorphism
Introduction Just remember that the compiler checks the class of the reference variable, not the class of the actual object at the other end of the reference Previously, in Object Class Polymorphism, we wanted to get a Dog from ArrayList that has Dog methods. But we couldn’t because method that we can use is based on the reference type, not... Read More
-
Object Class polymorphism
Every class in Java extends class Object Class Object is the mother of all classes. It is the superclass of everything. Every class you write extends Object. Any class that doesn’t explicitly extend another class, implicitly extends Object. For example: public class Dog extends Object{ } But wait a minute, Dog already extends something... Read More
-
MOOC.fi Java Programming I Part 6
Part 6 Objects on a list and a list as part of an object Objects that contain list public class Stack { private ArrayList<String> hola; public Stack(){ this.hola = new ArrayList<>(); } public boolean isEmpty(){ return this.hola.isEmpty(); } public void add(String value){ this... Read More
-
Deeper knowledge on Polymorphism
Deeper knowledge on Polymorphism: Introduction Back in previous polymorphism article, we did: Wolf mywolf = new Wolf(); Animal myHippo = new Hippo(); But this time: can we do this? Animal myAnimal = new Animal(); Some classes should not be instantiated. But how do we deal with this? We need an Animal class, for inheritance and polymorphi... Read More
-
MOOC.fi Java Programming I Part 5
Part 5 Learning object-oriented programming Object-oriented programming is primarily about isolating concepts into their own entities or, in other words, creating abstractions. Separating a concept into its own class has advantages. Firstly, certain details (such as the rotation of a hand) can be hidden inside the class (i.e.,... Read More
-
Polymorphism
Polymorphism: Introduction Let’s first step back and look at how we declare a reference and create an object: //1) declare reference variable // Tells the JVM to allocate space for a reference variable. The reference //variable is, forever, of type Dog. In other words, a remote control that //has buttons to control a Dog, but not a Cat or a Bu... Read More
-
Inheritance
Inheritance: Introduction Subclass (square, triangle, etc) inherits from the superclass (shape). Subclass can override methods but instance variables are not overridden because they don’t need to be. They don’t define any special behavior, so a subclass can give an inherited instance variable any value it chooses. PantherMan can set his inher... Read More
-
MOOC.fi Java Programming I Part 4
Part 4~ Introduction to object-oriented programming A class defines the attributes of objects, i.e., the information related to them like what the object has and is made up of(instance variables) that specifies internal state of object, and their commands, i.e., their methods. The values of instance (i.e., object) variables define the i... Read More
-
Encapsulation in Java
Encapsulation in Java Without encapsulation, outsiders can access and manipulate instance variables. Encapsulation’s rule of thumb is to mark instance variables private and getters and setters as public. class Dog{ //instance variables as private private int size; //getters and setters as public public int getSize(){ ... Read More
-
Difference between local and instance variables
Difference between local and instance variables: Instance variables are declared inside a class but not within a method. class Horse { //instance variables private double height = 15.2; private String breed; // more code... } On the other hand, Local variables are declared within a method and MUST be in initalised. Think of it as l... Read More
-
Short-Circuit Operators ( && , || ) vs Non-Short-Circuit Operators ( &, | )
Short-Circuit Operators ( && , || ): In the case of &&, the expression will be true only if both sides of the && are true. So if the JVM sees that the left side of a && expression is false, it stops right there! Doesn’t even bother to look at the right side. Same for ||. If there is an expression with &&... Read More
-
MOOC.fi Java Programming I Part 3
Part 3! Discovering errors How to debug with comments I didn’t know this bool works this way ```java boolean check = false; if(!check) // same as if(check == false) * Difference Between If and Else If: The difference is that if the first if is true, all of the other else ifs won't be executed, even if they do evaluate to... Read More
-
How does Java code run? (feat. Compiler & JVM)
I only heard about compilers and JVMs but did not know for sure what they were, and how they relate to help run Java code. Compiler: Run your source code through compiler and it checks for errors. It won’t compile until it is satisfied that everything will run correctly. Checks variables of wrong type that stops majority of errors. But some s... Read More
-
Difference between for and while loop
Difference between for and while loop: It is a very fundamental question that I admit I didn’t 100% know how to explain. A while loop only has the boolean test; it doesn’t have a built-in initialization or iteration expression. The only way to initalise a counter is outside the while loop. A while loop is good when you don’t know how explicitl... Read More
-
MOOC.fi Java Programming I Part 2
Continuing the journey to master fundamentals of Java in MOOC.fi Java Programming I Part 2! Recurring problems and patterns to solve them print and println is different! careful that print just prints everything in 1 line, even with multiple print statements Repeating functionality Remember from part 1 that expression is the thing ... Read More
-
Difference between Array and ArrayList
1) A regular array has to be declared its size upon creation. But for ArrayList, just need to make an object of type ArrayList. You can actually give initial size to ArrayList too. int[] myList = new int[]; ArrayList<Integer> myArrayList = new ArrayList<>(); 2) To put an object in a regular array, you must assign it to a specific ... Read More
-
ArrayList
ArrayList in Java: Unlike the regular array, ArrayList is more flexible in that initial size need not be declared and that it can shrink when elements are removed. (dynamic) Also, instead of looping through the whole array, you can ask if it contains the element you are looking for. But array is faster than arraylist when it comes to primitives... Read More
-
MOOC.fi Java Programming I Part 1
My first post! One of the most popular backend languages is Java. As an aspiring Backend developer and having relatively more experience with Python (~3 years), I decided to add Java into my skill list. I looked at many online Java courses like Udemy but MOOC.fi Java Programming seems the most recommended by reviewers, particularly by Reddit. S... Read More
-
An exhibit of Markdown
This note demonstrates some of what Markdown is capable of doing. An exhibit of Markdown Note: Feel free to play with this page. Unlike regular notes, this doesn’t automatically save itself. Basic formatting Paragraphs can be written like so. A paragraph is the basic block of Markdown. A paragraph is what text will turn into when there is no... Read More
-
Table example
Table example as below For now, these extended features are provided: Cells spanning multiple columns Cells spanning multiple rows Cells text align separately Table header not required Grouped table header rows or data rows Rowspan and Colspan ^^ in a cell indicates it should be merged with the cell above. This feature is contribu... Read More
-
Mermaid example
1. Pie chart pie title Pets adopted by volunteers "Dogs" : 386 "Cats" : 85 "Rats" : 35 2. sequence diagram @startmermaid sequenceDiagram Alice -» Bob: Hello Bob, how are you? Bob–»John: How about you John? Bob–x Alice: I am good thanks! Bob-x John: I am good thanks! Note right of John: Bob thinks a longlong time, so longthat ... Read More
-
Quick markdown example
Paragraphs are separated by a blank line. 2nd paragraph. Italic, bold, and monospace. Itemized lists look like: this one that one the other one Note that — not considering the asterisk — the actual text content starts at 4-columns in. Block quotes are written like so. They can span multiple paragraphs, if you like. Use 3 dash... Read More