The Scanner class helps in reading user input from the console. You create a Scanner object to start capturing user inputs.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your name:"); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); } }
IOExceptions are errors that occur during input or output operations, such as reading from a file or writing to a file.
import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileReader reader = new FileReader("file.txt"); // Read from file reader.close(); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
Java programs need to be compiled into bytecode before they can be executed. Use `javac` command to compile and `java` command to run.
Compile: `javac MyProgram.java` Run: `java MyProgram`
FileInputStream is used to read data from a file. You can use it to open a file and read its contents.
import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream("file.txt"); int data = file.read(); while (data != -1) { System.out.print((char) data); data = file.read(); } file.close(); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
FileOutputStream is used to write data to a file. You can open a file and write data into it.
import java.io.FileOutputStream; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileOutputStream file = new FileOutputStream("file.txt"); String data = "Hello, World!"; file.write(data.getBytes()); file.close(); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
To print output in Java, you can use `System.out.println()` for printing lines and `System.out.print()` for printing without a newline.
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); System.out.print("This is on the same line."); } }
To serialize an object, the class must implement the `Serializable` interface. This allows the object's state to be converted into a byte stream.
import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; public Person(String name) { this.name = name; } }
You can save a serialized object to a file using `ObjectOutputStream` and later read it back using `ObjectInputStream`.
import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.IOException; public class Main { public static void main(String[] args) { try { Person person = new Person("John"); FileOutputStream file = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(person); out.close(); file.close(); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
You can customize the serialization process by defining `writeObject()` and `readObject()` methods in your class.
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(age); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); age = in.readInt(); } }
Serialization is converting an object's state into a byte stream so it can be easily stored or transmitted.
A `Person` object with properties `name` and `age` is serialized into a byte stream for saving to a file.
The `serialVersionUID` is a unique identifier for each class that implements `Serializable`. It helps to ensure that during deserialization, the class matches the serialized version.
public class Person implements Serializable { private static final long serialVersionUID = 123456789L; }
A class is serializable if it implements the `Serializable` interface. Its fields must also be serializable or marked as transient.
public class Person implements Serializable { private String name; private transient int age; // not serialized }
Deserialization is the reverse process of serialization, where a byte stream is converted back into an object.
import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(file); Person person = (Person) in.readObject(); in.close(); file.close(); System.out.println(person.getName()); } catch (IOException | ClassNotFoundException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
Serialization is useful for saving an object's state to a file or sending it over a network.
You can serialize a `Person` object to save its state and deserialize it later to retrieve the state.
Static fields belong to the class, not instances, so they are not serialized. Transient fields are excluded from serialization.
public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private transient int age; // not serialized }
Generics allow you to write algorithms that work with different types of data, providing flexibility and type safety.
public class GenericBox<T> { private T content; public void setContent(T content) { this.content = content; } public T getContent() { return content; } }
Generics enable you to define classes, interfaces, and methods with type parameters, which can be replaced with specific types during instantiation.
List<String> names = new ArrayList<>(); // List of Strings
Generics help to enforce type safety at compile-time and reduce the risk of ClassCastException at runtime.
Using `List` ensures that only integers can be added to the list, avoiding runtime type errors.
The diamond operator (`<>`) allows you to omit the type arguments on the right-hand side when creating instances of generic classes.
Listnames = new ArrayList<>(); // Type is inferred from the declaration
The `super` keyword is used with wildcards in generics to specify a lower bound type parameter.
List<? super Integer> list = new ArrayList<>(); // Can add Integer or its subclasses
Wildcards (`?`) represent an unknown type and can be used to define more flexible method signatures.
List> list = new ArrayList(); // List of unknown type
The `extends` keyword specifies an upper bound for wildcard type parameters.
List extends Number> list = new ArrayList(); // List of numbers or subclasses
Wrapper classes (e.g., `Integer`, `Double`) allow primitive types to be used with generic code.
Listnumbers = new ArrayList<>(); // Integer is a wrapper for int
You can create a thread by extending the `Thread` class and overriding its `run()` method.
public class MyThread extends Thread { public void run() { System.out.println("Thread is running!"); } }
Threads can also be created using lambda expressions, which provide a concise way to define thread tasks.
Runnable task = () -> System.out.println("Thread is running!"); Thread thread = new Thread(task); thread.start();
Threads help improve performance by allowing parts of a program to run concurrently, making better use of CPU resources.
Using threads to handle multiple tasks simultaneously, such as handling multiple user requests on a server.
A thread can be in various states: New, Running, Blocked, Waiting, or Terminated.
A thread starts in the New state, transitions to Running when it starts execution, and may enter Blocked or Waiting if it is waiting for resources.
Threads can communicate by sharing data or using synchronization methods like `wait()`, `notify()`, and `notifyAll()`.
One thread might use `wait()` to pause until another thread calls `notify()` to resume its execution.
Thread lifecycle methods such as `start()`, `sleep()`, `join()`, and `interrupt()` help manage thread execution.
Thread.sleep(1000); // Pause for 1 second
The `synchronized` keyword ensures that only one thread accesses a resource at a time, preventing data inconsistency.
public synchronized void method() { // Critical section }
A thread represents a separate path of execution within a program, allowing for concurrent operations.
Multiple threads can be running simultaneously, performing different tasks in parallel.
Race conditions occur when the timing of thread execution affects the outcome, potentially causing bugs or inconsistencies.
Two threads updating the same variable without synchronization can result in unexpected values.
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!