Java Summary

5.0(1)
studied byStudied by 14 people
5.0(1)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/141

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

142 Terms

1
New cards
Java
An object-oriented programming language that uses objects and classes to organize and perform tasks.
2
New cards
James Gosling
Java was developed by James Gosling at Sun Microsystems, which is now owned by Oracle Corporation.
3
New cards
Platform-Independence
Java's Platform-Independence: Java code can run on any machine that has a Java Virtual Machine (JVM) installed, which makes it platform-independent.
4
New cards
Enterprise, Web & Android
Java's Applications: Java is widely used in enterprise applications, web development, and Android app development.
5
New cards
Syntax
Java syntax is similar to C and C++. Programs are written in plain text files with the ‘.java‘ extension.
6
New cards
Variables
Variables store data and have a type (e.g., ‘int‘, ‘float‘, ‘double‘, ‘boolean‘, ‘char‘, ‘String‘).
7
New cards
Operators
Java supports arithmetic (‘+’, ‘-’, ‘\*’, ‘/’, ‘%’), comparison (‘==’, ‘! =’, ‘>’, ‘≥’, ‘
8
New cards
Classes
A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that an object can have.
9
New cards
Objects
An object is an instance of a class. It has its own state (attributes) and can perform actions (methods).
10
New cards
Methods
A method is a function defined inside a class that performs a specific task. Methods can have parameters and a return type.
11
New cards
If-else statement
Used to make decisions based on a condition. The code in the ‘if’ block will execute if the condition is true, otherwise the code in the ‘else’ block will execute.
12
New cards
Switch Statement
Allows the selection of multiple branches of code execution based on the value of a variable or expression.
13
New cards
For loop
Used to repeatedly execute a block of code a specific number of times.
14
New cards
While
Executes a block of code as long as a condition is true
15
New cards
Do-while loop
Executes a block of code at least once, and then repeats as long as a condition is true
16
New cards
Arrays
A collection of elements of the same data type, stored in contiguous memory allocations
17
New cards
Arrays Declaration
Arrays can be declared using square brackets, e.g., ‘int\[\] myArray;‘.
18
New cards
Arrays Initialization
Arrays can be initialized using the ‘new‘ keyword, e.g., ‘myArray = new int\[5\];‘, or with an initializer list, e.g., ‘int\[\] myArray = {1, 2, 3, 4, 5}
19
New cards
Arrays Accessing elements
Array elements can be accessed using indices, e.g., ‘myArray\[0\]‘ to access the first element.
20
New cards
Arrays Length
The length of an array can be obtained using the ‘.length‘ attribute, e.g., int arrayLength = myArray.length;
21
New cards
Arrays Multidimensional Arrays
Arrays can have multiple dimensions, e.g., ‘int\[\]\[\] matrix = new int\[3\]\[4\];‘ creates a 3x4 matrix
22
New cards
Standard output
‘System.out.println()‘ is used to print messages to the console with a newline character, while ‘System.out.print()‘ prints without a newline.
23
New cards
Standard input
The ‘Scanner‘ class from ‘java.util‘ package can be used to read user input from the console, e.g., ‘Scanner scanner = new Scanner(System.in);‘.
24
New cards
Reading data
‘Scanner‘ provides various methods to read different data types, e.g., ‘nextInt()‘, ‘nextFloat()‘, ‘nextLine()‘, and ‘next()‘.
25
New cards
Closing the scanner
It is important to close the ‘Scanner‘ object after use to prevent resource leaks, e.g., ‘scanner.close();‘.
26
New cards
File class
The ‘File‘ class from the ‘java.io‘ package represents a file or directory in the file system.
27
New cards
Reading from a file
The ‘FileReader‘ and ‘BufferedReader‘ classes can be used to read text from a file. The ‘BufferedReader‘ provides efficient reading with a buffer.
28
New cards
Writing to a file
The ‘FileWriter‘ and ‘BufferedWriter‘ classes can be used to write text to a file. The ‘BufferedWriter‘ provides efficient writing with a buffer
29
New cards
Handling exceptions
File I/O operations can throw exceptions, e.g., ‘FileNotFoundException‘ or ‘IOException‘. Use a ‘try‘-‘catch‘ block to handle these exceptions.
30
New cards
Closing resources
Always close file I/O resources in a ‘finally‘ block or use the try-with-resources statement, which automatically closes resources when the block exits.
31
New cards
Class Constructors
Constructors are special methods used to initialize objects. They have the same name as the class and do not have a return type, e.g., ‘public MyClass() { }‘.
32
New cards
Classes Inheritance
Classes can inherit properties and methods from other classes using the ‘extends‘ keyword, e.g., ‘class Subclass extends Superclass { }‘.
33
New cards
Objects Instantiation
Objects can be created using the ‘new‘ keyword followed by the constructor, e.g., ‘MyClass myObject = new MyClass();‘.
34
New cards
Objects Accessing Fields
Fields of an object can be accessed using the dot (‘.‘) notation, e.g., ‘myObject.myField‘
35
New cards
Objects Accessing Methods
Methods of an object can be called using the dot (‘.‘) notation, e.g., ‘myObject.myMethod();‘.
36
New cards
Method declaration
Methods of an object can be called using the dot (‘.‘) notation, e.g., ‘myObject.myMethod();‘.
37
New cards
Method Parameters
Methods can have parameters, which are specified inside the parentheses as a commaseparated list of data types and variable names, e.g., ‘public void myMethod(int x, String y) { }‘.
38
New cards
Method Return Statement
Methods with a return type other than ‘void‘ must include a ‘return‘ statement followed by an expression that matches the return type, e.g., ‘return x + y;‘.
39
New cards
Fields
Fields are variables declared inside a class. They represent the state or the properties of an object
40
New cards
Fields Declaration
Fields are declared with an access modifier (e.g., ‘public‘, ‘private‘), a data type, and a variable name, e.g., ‘private int myField;‘.
41
New cards
Fields Inialization
Fields can be initialized during declaration or inside a constructor, e.g., ‘private int myField = 42;‘ or ‘public MyClass() { myField = 42; }‘.
42
New cards
Fields Access Modifiers
Fields can have different access levels, which control their visibility and accessibility:

* ‘public‘: The field is accessible from any class.
* ‘private‘: The field is accessible only within the class itself.
* protected: The field is accessible within the class, its subclasses, and classes in the same package.
* Default (no modifier): The field is accessible within the class and other classes in the same package.
43
New cards
Static Fields
Fields can be declared as static, which means they belong to the class itself rather than to individual objects. Static fields are shared among all instances of the class, e.g., private static int myStaticField;.
44
New cards
Command Line Arguments
Command line arguments are inputs passed to a Java program when it is executed from the command line or terminal.
45
New cards
Command Line Arguments Accessing Arguments
Command line arguments are passed as an array of ‘String‘ objects to the ‘main‘ method of the program, e.g., ‘public static void main(String\[\] args) { }‘.
46
New cards
Command Line Argument Example
To access the first command line argument, use ‘args\[0\]‘. To iterate over all arguments, use a ‘for‘ loop or an enhanced ‘for‘ loop (also known as a ”for-each” loop).
47
New cards
Packages
Packages are used to group related classes and interfaces in Java. They help in organizing the code and avoiding naming conflicts.
48
New cards
Packages Declaration
Packages are declared at the beginning of a Java source file using the ‘package‘ keyword followed by the package name, e.g., ‘package com.mycompany.myproject;‘.
49
New cards
Packages Importing Classes
To use a class from another package, you can either use its fully qualified name, e.g., ‘java.util.ArrayList‘, or import the class using the ‘import‘ keyword, e.g., ‘import java.util.ArrayList;‘.
50
New cards
Default Package
If no package is specified, the class belongs to the default (unnamed) package. It is generally not recommended to use the default package for anything other than simple experiments and tests.
51
New cards
JavaDocs
a standard way to generate documentation for Java classes, methods, and fields using specially formatted comments.
52
New cards
JavaDoc comments
written using a ‘/\*\* ... \*/‘ notation and are placed immediately before the class, method, or field they document, e.g.,

Listing 1: JavaDoc Example

/∗ ∗

∗This method adds two integer.

∗ @param a t h e f i r s t i n t e g e r

∗ @param b t h e second i n t e g e r

∗ @re turn t h e sum o f a and b

∗/

public int add ( int a , int b ) { }
53
New cards
JavaDoc tags
JavaDoc comments can include tags such as ‘@param‘, ‘@return‘, ‘@throws‘, ‘@author‘, and ‘@since‘ to provide more information about the code element being documented.
54
New cards
Generating JavaDocs
JavaDocs can be generated using the ‘javadoc‘ command-line tool or through integrated development environments (IDEs) like IntelliJ IDEA or Eclipse.
55
New cards
Inheritance
allows a class to inherit properties (fields) and behaviors (methods) from another class.
56
New cards
Superclass and subclass
The class that is being inherited from is called the superclass, and the class that inherits from the superclass is called the subclass.
57
New cards
extends
Inheritance is implemented in Java using the ‘extends‘ keyword, e.g., ‘class Subclass extends Superclass { }‘.
58
New cards
Overriding methods
A subclass can override a method of the superclass by providing a new implementation with the same method signature and the java @Override tag.
59
New cards
Super
The ‘super‘ keyword can be used to call a method or constructor of the superclass from within the subclass, e.g., ‘super.myMethod();‘ or ‘super();‘.
60
New cards
Polymorphism
s the ability of an object to take on different forms or behaviors depending on the context. In Java, polymorphism is implemented through method overriding and interfaces.
61
New cards
Subtype polymorphism
Also known as dynamic method dispatch or runtime polymorphism, allows objects of a subclass to be treated as objects of the superclass. This enables a single interface to be used for a general class of actions, making the code more flexible and extensible.
62
New cards
Method overriding (Polymorphism)
When a subclass provides a new implementation for a method of the superclass, it overrides the method. At runtime, the appropriate method implementation is called based on the actual type of the object.
63
New cards
Dynamic Dispatch
the process by which the Java Virtual Machine (JVM) selects the appropriate method implementation to call at runtime, based on the actual type of the object.
64
New cards
Method Overriding(Dynamic Dispatch)
Dynamic dispatch is used when a method is overridden in a subclass. The JVM determines the correct method to call based on the object’s type at runtime, even if the reference type is that of the superclass.
65
New cards
Virtual methods
In Java, all non-static and non-private methods are considered virtual by default, which means they can be overridden in subclasses and participate in dynamic dispatch.
66
New cards
Abstract Classes
e classes that cannot be instantiated and are meant to be subclassed. They can contain both abstract and non-abstract methods.
67
New cards
Abstract Class Declaration
Abstract classes are declared using the ‘abstract‘ keyword, e.g., ‘abstract class MyAbstractClass { }‘.
68
New cards
Abstract Methods
Abstract methods are methods without a body that must be implemented by any concrete (non-abstract) subclass. They are declared using the ‘abstract‘ keyword, e.g., ‘public abstract void myMethod();‘.
69
New cards
Interfaces
a collection of abstract methods (and optionally default and static methods) that define a contract or set of behaviors that implementing classes must adhere to.
70
New cards
Interfaces Declaration
Interfaces are declared using the ‘interface‘ keyword, e.g., ‘interface MyInterface { }‘.
71
New cards
Implementing interfaces
A class can implement an interface using the ‘implements‘ keyword, e.g., ‘class MyClass implements MyInterface { }‘. The class must provide an implementation for all abstract methods in the interface.
72
New cards
Multiple inheritance
Java does not support multiple inheritance of classes, but a class can implement multiple interfaces, e.g., ‘class MyClass implements InterfaceA, InterfaceB { }‘.
73
New cards
Default Methods
Interfaces can provide default method implementations using the ‘default‘ keyword. This allows new methods to be added to interfaces without breaking existing implementations.
74
New cards
Enums
a special type of class that represents a fixed set of named constants. They are useful for representing a group of related values, such as days of the week or colors.
75
New cards
Enums Declaration
declared using the ‘enum‘ keyword, followed by the enum name and a list of named constants, e.g., ‘enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }‘.
76
New cards
Enum Methods
Enums automatically inherit several useful methods, such as ‘values()‘, which returns an array of the enum’s constants, and ‘valueOf(String)‘, which returns the enum constant with the specified name.
77
New cards
Enum Custom Behaviors
Enums can have constructors, fields, and methods, allowing them to have custom behavior associated with each constant.
78
New cards
Exceptions
e events that occur during the execution of a program, signaling an abnormal condition or error. Java provides a built-in mechanism for handling exceptions using try-catchfinally blocks and the ‘throw‘ keyword.
79
New cards
Try-catch-finally blocks
To catch and handle exceptions, surround the code that may throw an exception with a try block, followed by one or more catch blocks to handle different types of exceptions, and an optional finally block for cleanup code, e.g.,

Listing 2: Try-Catch-Finally Example

try {

// code t h a t m igh t throw an e x c e p t i o n

} catch ( IOException e ) {

// h a n dle IOExcep t ion

} catch ( Excep ti on e ) {

// h a n dle o t h e r e x c e p t i o n s

} f i n a l l y {

// cle a n u p code t h a t alw ay s runs

}
80
New cards
Throwing Exceptions
You can throw an exception using the ‘throw‘ keyword followed by an instance of the exception class, e.g., ‘throw new IllegalArgumentException(”Invalid argument”);‘.
81
New cards
Custom Exceptions
You can create custom exception classes by extending the ‘Exception‘ class or one of its subclasses.
82
New cards
Unit Testing
Unit testing is the process of testing individual units or components of a software application to ensure they work correctly. In Java, unit tests are typically written using testing frameworks like JUnit or TestNG.
83
New cards
JUnit
a widely-used testing framework for Java applications. It provides annotations, such as ‘@Test‘, ‘@Before‘, and ‘@After‘, to define test methods and setup/teardown methods.
84
New cards
Test Methods
s are annotated with ‘@Test‘ and typically follow the Arrange-Act-Assert pattern: arrange the objects and inputs, act by calling the method under test, and assert that the expected outcome occurred
85
New cards
Setup and teardown
Setup methods, annotated with ‘@Before‘, run before each test method, and teardown methods, annotated with ‘@After‘, run after each test method. These methods are useful for initializing and cleaning up resources needed for the tests.
86
New cards
Assertions
statements that check whether a condition is true, such as ‘assertEquals(expected, actual)‘, ‘assertTrue(condition)‘, or ‘assertFalse(condition)‘. If an assertion fails, the test fails, and an error is reported.
87
New cards
Generics
a language feature in Java that allows you to create classes, interfaces, and methods that work with different types while maintaining type safety. They are often used to create generic containers, like collections, that can store any type of object.
88
New cards
Type parameters
placeholders for actual types, represented by uppercase single-letter names, such as ‘T‘ for a generic type, ‘E‘ for elements in a collection, and ‘K‘ and ‘V‘ for keys and values in a map
89
New cards
Generic classes
include the type parameter in angle brackets after the class name, e.g., ‘class MyGenericClass< T > { }‘. You can then use the type parameter as a type within the class, e.g., ‘private T myField;‘.
90
New cards
Generic Methods
Methods can also have their own type parameters, which are declared before the return type, e.g., ‘ T myGenericMethod(T input) { }‘.
91
New cards
Bounded Type Parameters
You can restrict the types that can be used as type arguments by specifying an upper bound using the ‘extends‘ keyword, e.g., ‘class MyGenericClass { }‘.
92
New cards
Using Generic Classes
To use a generic class or method, provide the actual type argument in angle brackets when declaring a variable or calling a method, e.g., ‘MyGenericClass myInstance = new MyGenericClass<>();‘.
93
New cards
Type Ensure
Generics are implemented in Java using type erasure, which means that the generic type information is removed at runtime. This allows for backward compatibility with older versions of Java but can lead to some limitations, such as not being able to create an array of a generic type.
94
New cards
Collections
a group of Java classes and interfaces that provide a framework for storing and manipulating groups of objects. The Java Collections Framework is part of the ‘java.util‘ package.
95
New cards
Main interface
The primary interfaces in the Java Collections Framework are ‘Collection‘, ‘List‘, ‘Set‘, ‘Queue‘, and ‘Map‘. Each interface represents a different way of organizing and storing data.
96
New cards
Collections Common Operations
The ‘Collection‘ interface defines common operations for working with collections, such as ‘add‘, ‘remove‘, ‘contains‘, ‘size‘, and ‘isEmpty‘.
97
New cards
Lists
are ordered collections that can contain duplicate elements. Elements in a list can be accessed by their index.
98
New cards
ArrayList
a resizable array implementation of the ‘List‘ interface. It provides fast random access to elements but can be slow when inserting or removing elements in the middle of the list.
99
New cards
LinkedList
is a doubly-linked list implementation of the ‘List‘ and ‘Deque‘ interfaces. It provides fast insertion and removal of elements at the beginning and end of the list but can be slow when accessing elements by index
100
New cards
List Operations
Lists support additional operations, such as ‘get‘, ‘set‘, ‘indexOf‘, and ‘lastIndexOf‘.