Fundamentos de Java
Compartilhado por um usuário do Flashcards.gg · gerado com IA · Denunciar este conjunto
Conceitos fundamentais da linguagem de programação Java, incluindo sintaxe básica e exemplos práticos de código.
Toque no cartão para virar
Cartões · 53
- Hello World program entry point
- public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }
- Declaring primitive variables
- int age = 25; double price = 19.99; boolean active = true; char grade = 'A';
- String declaration and concatenation
- String first = "John"; String full = first + " Doe"; System.out.println(full);
- Basic if-else condition
- if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }
- Ternary operator
- int max = (a > b) ? a : b;
- Traditional for loop
- for (int i = 0; i < 5; i++) { System.out.println(i); }
- Enhanced for-each loop over an array
- int[] nums = {1, 2, 3}; for (int n : nums) { System.out.println(n); }
- While loop counter
- int count = 0; while (count < 3) { System.out.println(count); count++; }
- Do-while loop guarantee execution
- int i = 0; do { System.out.println(i); i++; } while (i < 1);
- Switch statement with yield (expression)
- String type = switch (day) { case 1, 7 -> "Weekend"; default -> "Weekday"; };
- Defining a simple class with fields
- public class User { String name; int age; }
- Class constructor definition
- public class Car { String model; public Car(String model) { this.model = model; } }
- Method with return value and parameters
- public int sum(int a, int b) { return a + b; }
- Method overloading by parameter count
- int add(int a) { return a + 1; } int add(int a, int b) { return a + b; }
- Single inheritance using extends
- class Animal {} class Dog extends Animal { void bark() { System.out.println("Woof"); } }
- Calling superclass constructor using super
- class Dog extends Animal { Dog(String name) { super(name); } }
- Overriding a method with @Override
- @Override public String toString() { return "Custom string representation"; }
- Defining and implementing an interface
- interface Flyable { void fly(); } class Bird implements Flyable { public void fly() {} }
- Default method in an interface
- interface Log { default void info(String msg) { System.out.println(msg); } }
- Abstract class and abstract method
- abstract class Shape { abstract double area(); }
- Final constant variable
- public static final double PI = 3.14159;
- Static method invocation
- class MathUtils { static int square(int x) { return x * x; } } int res = MathUtils.square(4);
- Basic try-catch block for exceptions
- try { int res = 10 / 0; } catch (ArithmeticException e) { System.err.println(e.getMessage()); }
- Try-catch-finally block
- try { doTask(); } catch (Exception e) { log(e); } finally { cleanUp(); }
- Try-with-resources for auto-closeable
- try (var reader = new BufferedReader(new FileReader("f.txt"))) { reader.readLine(); }
- Throwing a checked or unchecked exception
- if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); }
- Declaring checked exceptions in method header
- public void readFile() throws IOException { throw new IOException("Error"); }
- Instantiating and populating an ArrayList
- List<String> list = new ArrayList<>(); list.add("Java"); list.add("Kotlin");
- Instantiating and populating a HashMap
- Map<String, Integer> map = new HashMap<>(); map.put("Alice", 30); map.get("Alice");
- HashSet for unique elements
- Set<Integer> set = new HashSet<>(List.of(1, 2, 2, 3)); // Contains 1, 2, 3
- Unmodifiable list creation using List.of
- List<String> items = List.of("A", "B", "C");
- Filtering a Stream
- List<String> result = list.stream().filter(s -> s.startsWith("A")).toList();
- Mapping elements in a Stream
- List<Integer> lengths = names.stream().map(String::length).toList();
- Reducing values with Stream reduce
- int sum = numbers.stream().reduce(0, (a, b) -> a + b);
- Stream forEach with lambda
- names.stream().forEach(name -> System.out.println(name));
- Method reference syntax
- names.forEach(System.out::println);
- Optional handling to avoid null pointer
- Optional<String> opt = Optional.ofNullable(val); String result = opt.orElse("Default");
- Optional map and ifPresent
- opt.map(String::toUpperCase).ifPresent(System.out::println);
- Local variable type inference with var
- var message = "Hello, Type Inference"; var count = 42;
- Record definition for immutable data
- public record Point(int x, int y) {} Point p = new Point(10, 20); int px = p.x();
- Enum declaration with methods
- enum Level { LOW, MEDIUM, HIGH } Level current = Level.HIGH;
- Enum with constructor and fields
- enum Status { OK(200), ERR(500); final int code; Status(int c) { this.code = c; } }
- Creating a thread using Runnable and lambda
- Thread thread = new Thread(() -> System.out.println("Running")); thread.start();
- Creating an ExecutorService thread pool
- ExecutorService pool = Executors.newFixedThreadPool(2); pool.submit(() -> doWork());
- Synchronized method for thread safety
- public synchronized void increment() { this.counter++; }
- AtomicInteger for lock-free counters
- AtomicInteger counter = new AtomicInteger(0); counter.incrementAndGet();
- String formatting with formatted or String.format
- String msg = String.format("User %s has %d points", name, points);
- Multiline Text Blocks
- String json = """ { "name": "Alice" } """;
- Pattern matching for instanceof
- if (obj instanceof String s) { System.out.println(s.toUpperCase()); }
- Generic class definition
- public class Box<T> { private T val; public void set(T val) { this.val = val; } }
- Reading standard input using Scanner
- Scanner sc = new Scanner(System.in); String line = sc.nextLine();
- Sorting a List using Comparator
- list.sort((a, b) -> a.compareTo(b)); // or list.sort(Comparator.naturalOrder());
- Parsing a String to an integer
- int val = Integer.parseInt("123");