Core Java Flashcards

1
Q

Primitive Types

A

A primitive data type specifies the size and type of variable values, and it has no additional methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

final

A

If you don’t want others (or yourself) to overwrite existing values, use the final keyword final int myNum = 15;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

types

A

int myNum = 5; // Integer (whole number) float myFloatNum = 5.99f; // Floating point number char myLetter = ‘D’; // Character boolean myBool = true; // Boolean String myText = “Hello”; // String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Casting

A

In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte int myInt = (int) myDouble; // Manual casting: double to int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

main, sop, comments

A

public class Main { public static void main(String[] args) { System.out.println(“Hello World”); } } Comments // and /* */

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

String

A

Method Description 1. length() Returns the length of String name. (5 in this case) 2. toLowerCase() Converts all the characters of the string to the lower case letters. 3. toUpperCase() Converts all the characters of the string to the upper case letters. 4. trim() Returns a new String after removing all the leading and trailing spaces from the original string. 5. substring(int start) Returns a substring from start to the end. Substring(3) returns “ry”. [Note that indexing starts from 0] 6. substring(int start, int end) Returns a substring from the start index to the end index. The start index is included, and the end is excluded. 7. replace(‘r’, ‘p’) Returns a new string after replacing r with p. Happy is returned in this case. (This method takes char as argument) 8. startsWith(“Ha”) Returns true if the name starts with the string “Ha”. (True in this case) 9. endsWith(“ry”) Returns true if the name ends with the string “ry”. (True in this case) 10. charAt(2) Returns the character at a given index position. (r in this case) 11. indexOf(“s”) Returns the index of the first occurrence of the specified character in the given string. 12. lastIndexOf(“r”) Returns the last index of the specified character from the given string. (3 in this case) 13. equals(“Harry”) Returns true if the given string is equal to “Harry” false otherwise [Case sensitive] 14.equalsIgnoreCase(“harry”) Returns true if two strings are equal, ignoring the case of characters. Escape character \ String Concatenation 1. + character 2. concat method firstName.concat(lastName)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Ternary Operator

A

String result = (time < 18) ? “Good day.” : “Good evening.”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Switch

A

int day = 4; switch (day) { case 1: System.out.println(“Monday”); break; default: System.out.println(“Looking forward to the Weekend”); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Math

A

Math.max(5, 10); Math.min(5, 10); Math.sqrt(64); Math.abs(-4.7); Math.random(); //returns a random number between 0.0 (inclusive), and 1.0 (exclusive):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

If Else

A

if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

while

A

while (condition) { // code block to be executed }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

for , for each

A

for (int i = 0; i < 5; i++) { System.out.println(i); } “for-each” loop, which is used exclusively to loop through elements in an array String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”}; for (String i : cars) { System.out.println(i); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

methods

A

method must be declared within a class void means no return static void myMethod(String fname, int age) { // code to be executed }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Method overloading

A

int myMethod(int x) float myMethod(float x) double myMethod(double x, double y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Classes and Objects

A

public class Main { int x = 5; } Main myObj = new Main();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Static Methods

A

can be accessed using class name only

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Constructor

A

Constructor name must match the class name, and it cannot have a return type (like void) constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Access Modifiers

A

Classes public The class is accessible by any other class default The class is only accessible by classes in the same package. This is used when you don’t specify a modifier. For attributes, methods and constructors public private default - The code is only accessible in the same package. protected - The code is accessible in the same package and subclasses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Non-Access Modifiers

A

Classes final - The class cannot be inherited by other classes abstract - The class cannot be used to create objects For attributes and methods, you can use the one of the following: final Attributes and methods cannot be overridden/modified static Attributes and methods belongs to the class, rather than an object abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. transient Attributes and methods are skipped when serializing the object containing them synchronized Methods can only be accessed by one thread at a time volatile The value of an attribute is not cached thread-locally, and is always read from the “main memory”

20
Q

Encapsulation

A

declare class variables/attributes as private

21
Q

Inheritance

A

class Car extends Vehicle

22
Q

Polymorphism

A

Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object

23
Q

Inner Classes

A

class OuterClass
{
int x = 10;
class InnerClass { int y = 5; }
}

OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass();

24
Q

Abstract Classes and Methods

A

abstract class Animal { public abstract void animalSound(); public void sleep() { System.out.println(“Zzz”); } }

25
Q

Interface

A

interface Animal { public void animalSound(); // interface method (does not have a body) public void run(); // interface method (does not have a body) }

26
Q

Enums

A

Special Class that represents a group of constants. You can also have an enum inside a class enum Level { LOW, MEDIUM, HIGH } Level myVar = Level.MEDIUM; Looping through enums for (Level myVar : Level.values()) { System.out.println(myVar); }

27
Q

Scanner

A

The Scanner class is used to get user input, and it is found in the java.util package. Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println(“Enter username”); String userName = myObj.nextLine(); // Read user input

28
Q

Date

A

import the java.time package LocalDate - Represents a date (year, month, day (yyyy-MM-dd)) LocalTime - Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) LocalDateTime - Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) DateTimeFormatter - Formatter for displaying and parsing date-time objects now() method from all the above objects to get Date, or DateTime or Time LocalDateTime myDateObj = LocalDateTime.now(); System.out.println(“Before formatting: “ + myDateObj); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss”); String formattedDate = myDateObj.format(myFormatObj); System.out.println(“After formatting: “ + formattedDate); Before Formatting: 2024-01-08T15:06:22.731538 After Formatting: 08-01-2024 15:06:22

29
Q

Date

A

LocalDate Represents a date (year, month, day (yyyy-MM-dd)) LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) DateTimeFormatter Formatter for displaying and parsing date-time objects use its now() method to get the date or time or date time LocalDateTime myDateObj = LocalDateTime.now(); System.out.println(“Before formatting: “ + myDateObj); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss”); String formattedDate = myDateObj.format(myFormatObj); System.out.println(“After formatting: “ + formattedDate); Before Formatting: 2024-01-08T17:19:52.558030 After Formatting: 08-01-2024 17:19:52

30
Q

Wrapper Classes

A

int Integer long Long

31
Q

Exception

A

try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println(“Something went wrong.”); } finally { System.out.println(“The ‘try catch’ is finished.”); }

32
Q

Java Regex

A

Pattern pattern = Pattern.compile(“w3schools”, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(“Visit W3Schools!”); Matcher object which contains information about the search that was performed boolean matchFound = matcher.find(); As a general rule, we’ll almost always want to use one of two popular methods of the Matcher class: find() matches() find() method tries to find the occurrence of a regex pattern within a given string. If multiple occurrences are found in the string, then the first call to find() will jump to the first occurrence. Thereafter, each subsequent call to the find() method will go to the next matching occurrence, one by one. Pattern stringPattern = Pattern.compile(“\d\d\d\d”); Matcher m = stringPattern.matcher(“goodbye 2019 and welcome 2020”); assertTrue(m.find()); assertEquals(8, m.start()); assertEquals(“2019”, m.group()); assertEquals(12, m.end()); assertTrue(m.find()); assertEquals(25, m.start()); assertEquals(“2020”, m.group()); assertEquals(29, m.end()); assertFalse(m.find()); The start() method will give the start index of the match, end() will return the last index of the character after the end of the match, and group() will return the actual value of the match. matches() the matches() method tries to match the whole string against the pattern Pattern stringPattern = Pattern.compile(“\d\d\d\d”); Matcher m = stringPattern.matcher(“goodbye 2019 and welcome 2020”); assertFalse(m.matches()); This is because it will try to match “\d\d\d\d” against the whole string “goodbye 2019 and welcome 2020”

33
Q

Regular Expression

A

MetaCharacters | Find a match for any one of the patterns separated by | as in: cat|dog|fish . Find just one instance of any character ^ Finds a match as the beginning of a string as in: ^Hello $ Finds a match at the end of the string as in: World$ \d Find a digit \s Find a whitespace character \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Brackets - Range of characters [abc] Find one character from the options between the brackets [^abc] Find one character NOT between the brackets [0-9] Find one character from the range 0 to 9 Quantifiers n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n n{x} Matches any string that contains a sequence of X n’s n{x,y} Matches any string that contains a sequence of X to Y n’s n{x,} Matches any string that contains a sequence of at least X n’s

34
Q

Threads

A

Extending the Thread class and overriding its run() method: Another way to create a thread is to implement the Runnable interface: Running Threads If the class extends the Thread class - call start() method If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object’s constructor and then calling the thread’s start()

35
Q

Lambda Expressions

A

numbers.forEach( (n) -> { System.out.println(n); } ); Lambda expressions can be stored in variables if the variable’s type is an interface which has only one method.A single method interface is also sometimes referred to as a functional interface. The lambda expression should have the same number of parameters and the same return type as that method.

36
Q

Files

A

File myObj = new File(“filename.txt”); The File class has many useful methods for creating and getting information about files. For example: canRead(),delete(),exists(),getAbsolutePath(),length(),mkdir()

37
Q

Read/Write Files

A

Read Files with Scanner File myObj = new File(“filename.txt”); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data); } myReader.close(); Write Files with FileWriter FileWriter myWriter = new FileWriter(“filename.txt”); myWriter.write(“Files in Java might be tricky, but it is fun enough!”); myWriter.close();

38
Q

Annotations

A

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code @Override You can create your custom annotations as well

39
Q

Generics

A

public class Printer <T> { T thingToPrint; public Printer(T thingToPrint) { this.thingToPrint =thingToPrint; } Printer<Integer> printer = new Printer<> (23)</Integer></T>

40
Q

Generics Subclass and Super Class Restrictions

A

public class Printer <T> { List<? super Number></T>

41
Q

Generic Methods

A

Just before the return type of the method, you need to declare parameters type of the method like <T> below private static <T> void shout (T thingToShout) { private static <T,V> void shout (T thingToShout, V somethingElseToShout) {</T></T>

42
Q

Generics Wildcards

A

private static void printList(List<object> myList) { But if you call the printList with the intList ,it will fail as List<Integer> is not a subclass of List<object> even though Integer is a subclass of Object Note that however, you can call a method which accepts List<String> as argument with ArrayList<String>. So the subclassing issue happens with the parameterized type. Not with the class type. To make printList accept any argument you need to change the signature to private static void printList(List<?> myList)</String></String></object></Integer></object>

43
Q

Invoking static methods in generic classes

A

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");</String>

44
Q

Super Keyword

A

Super can be used to call the parent class method from the child class’s method, if for some reason you need to execute the parent class’s code In case you are calling super from a constructor 1.the call to super constructor should be the first statement in the constructor 2.If you do not call the super constructor, Java injects a call to the parameter less constructor into the the first line of the constructor. So if you are defining your own constructor make sure that you create a parameter less constructor in the parent class

45
Q
A