0% found this document useful (0 votes)
3 views8 pages

Recap 03062025

Uploaded by

truong giang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Recap 03062025

Uploaded by

truong giang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

3/6/2025

HelloWorld

3.1. Coding convention


Variables
4 kinds:

instance vars (non-static fields): belongs to object

class vars (static fields): belongs to class

local: belongs to method, only visible to the methods containing them

parameters: classified as variables not fields

Naming convention:
*Variables:

case-sensitive

technically, variable names can begin with: letter | $ | _. But according to convention, always begin
variable names with a letter, not $, _

subsequent characters can be: letter, digits, $, _

convention: use full words instead of cryptic abbr when naming variables

not keyword or reserved word

1-word name: all lowercase letters; >1-word name: camel case

*Packages:

3/6/2025 1
prefix of package name is written in all-lowercase, should be top-level domain names: com, edu,
gov,...

subsequent components: vary depending on organization's naming conventions

*Classes:

should be nouns, mixed case with 1st letter of word capitalized

avoid acronyms and abbrs (unless some widely used ones: HTML, URL)

*Interfaces:

same as class names

*Methods:

should be verbs, in mixed case with 1st letter lowercase, with 1st letter of each internal word
capitalized

*Constants:

all uppercase, words separated by _

3.2. Keywords, Operators


Keywords
1. switch:
- select execution of 1 of multiple code blocks based on an expression
- the condition must be: byte, char, short, int, or String object (since Java 7)
- case block doesn't have an implicit ending point => using break statement at the end of each case
block to exit switch statement

2. break:
- exit a for, while, do while, or to mark the end of a case block in switch statement
- it always exits the innermost enclosing while, for, do, switch

3. if
- indicates conditional execution of a block
- the condition must be: boolean value
- may have optional else clause

4. const, goto:
- reversed, although they are not currently used

5. public
- an access control modifier

- can be applied to a class, method, field

- public class, method, field can be referenced from any other class or package

6. protected

3/6/2025 2
- another access control modifier

- can be applied to a class, method, field


-protected class, method, field can be referenced from:

-classes in same package


-subclasses (regardless of package in which a subclass is declared)

7. private

-another access control modifier

-can be applied to a class, method, field


-a private (inner) class, method, field can be referenced from within the class in which it's declared

Operators
arithmetic operators: + (can also be used for concatenating 2 strings together), -, *, /, %

unary operators: +, -, ++, --, !

equality, relational operators: ==, !=, >, >=, <, <=

conditional operators: &&, ||, ?: (aka ternary operator)

instanceof operator: identifies the type of object at runtime

bitwise operators: &, ^, |, ~

bit shift operators: ~, <<, >> (signed), >>> (unsigned)

Demo operator:

public class Main {


public static void main(String[] args) {
//demo arithmetic operators: + (can also be used for concatenating 2 strings together), -, *, /, %
int result = 1 + 2;
System.out.println("1 + 2 = " + result); //prints: 1 + 2 = 3
String thirdString = "This is" + " a concatenated string.";
System.out.println(thirdString); //prints: This is a concatenated string.

//demo unary operators: +, -, ++, --, !


int res = +1;
System.out.println(res); // prints 1
res--;
System.out.println(res); // prints 0
res++;
System.out.println(res); // prints 1
res = -res;
System.out.println(res); // prints -1
boolean success = false;

3/6/2025 3
System.out.println(success);// false
System.out.println(!success);// true
int i = 3;
i++;
System.out.println(i);// prints 4
++i;
System.out.println(i); // prints 5
System.out.println(++i);// prints 6
System.out.println(i++);// prints 6
System.out.println(i); // prints 7

//demo equality, relational operators: ==, !=, >, >=, <, <=
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2"); //false
if(value1 != value2)
System.out.println("value1 != value2"); //true
if(value1 > value2)
System.out.println("value1 > value2"); //false
if(value1 < value2)
System.out.println("value1 < value2"); //true
if(value1 <= value2)
System.out.println("value1 <= value2"); //true

//demo conditional operators: &&, ||, ?: (aka ternary operator)


if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2"); //prints: value1 is 1 AND value2 is 2
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1"); //prints: value1 is 1 OR value2 is 1
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result); //prints: 1

//demo instanceof operator: identifies the type of object at runtime


Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent)); //obj1 instanceof Parent: true
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child)); //obj1 instanceof Child: false
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent)); //obj2 instanceof Parent: true
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child)); //obj2 instanceof Child: true

3/6/2025 4
//demo bitwise operators: &, ^, |, ~
System.out.println(0x000F & 0x2222); //2
System.out.println(0x000F | 0x2222); //8751
System.out.println(0x000F ^ 0x2222); //8749
System.out.println(~0x000F); //-16

//demo bit shift operators: <<, >>, >>>


System.out.println(4 << 2); //16
System.out.println(4 >> 2); //1
System.out.println(4 >>> 2); //1

}
}

3.3. Loop, Selection


-if/else statement
-switch statement
-while, do-while statement
-for statement

Compare while and do-while:

+while: evaluate expression first, then deciding whether to execute the statement in while block or not
based on the value of expression. Continuing this process until the expression evaluates to false
+do-while: the statements within do block are always executed at least once, then evaluating
expression

public class Main {


public static void main(String[] args) {
int count = 1;
while (count < 1) {
System.out.println("Count is: " + count);
count++;
}
System.out.println("-".repeat(20));
int count2 = 1;
do {
System.out.println("Count is: " + count2);
count2++;
} while (count2 < 1);
}
}

3/6/2025 5
Exercise 4:

import java.util.Scanner;

public class Main {


public static String firstUniqueSubstring(String s) {
for (int i = 0; i < s.length(); i++) {
boolean[] seen = new boolean[26];
StringBuilder sb = new StringBuilder();
for (int j = i; j < s.length(); j++) {
char c = s.charAt(j);
if (seen[c - 'a']) {
break;
}
seen[c - 'a'] = true;
sb.append(c);
}
if (sb.length() > 1) {
return sb.toString();
}
}
return "No such substring";
}

public static void main(String[] args) {


String s = new Scanner(System.in).nextLine();
System.out.println(firstUniqueSubstring(s));
}
}

3.4. Modifiers
access modifiers for class: public, none

access modifiers for fields: public, protected, package-private, private

remaining modifiers besides access modifiers (for methods):

abstract:

classes: can’t be instantiated directly

methods: declared without method body, must be implemented by subclasses

static:

variables: belong to class instead of instances

3/6/2025 6
methods: can be accessed via class name without needing to instantiate an instance

final:

classes: can’t be subclassed

methods: can’t be overriden by subclasses

variables: can’t be reassigned after initialization

synchronized:

methods: ensure that only one thread can execute the method at a time

native:

methods: no body. The method body will be implemented in platform-dependent code,


typically written in another programming language such as C.

Annotation and Reflection


Annotation:

metadata about the code, can be processed at compile-time or runtime

Reflection:

inspect and manipulate classes, methods, fields and components at runtime

allow inspecting and processing metadata at runtime

instantiate objects dynamically using Class.forName() and newInstance()

accessing members: access private fields and methods using setAccessible(true)

invoking methods: invoke methods using Method.invoke()

Demo Custom Annotation:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME) // exists when running program


@Target(ElementType.METHOD) // this annotation can be used at method level
public @interface MyAnnotation {
String value() default "Default Value";
}

public class MyClass {

@MyAnnotation(value = "Hello from method1")


public void method1() {
System.out.println("Executing method1");
}

3/6/2025 7
@MyAnnotation(value = "Hello from method2")
public void method2() {
System.out.println("Executing method2");
}

public void method3() {


System.out.println("Executing method3");
}
}

import java.lang.reflect.Method;

public class AnnotationProcessor {


public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method[] methods = MyClass.class.getMethods();

for (Method method : methods) {


if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Found annotation on method: " + method.getName());
System.out.println("Annotation value: " + annotation.value());
method.invoke(obj);
}
}
}
}

Result:

3/6/2025 8

You might also like