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

Java Complete Guide

Complete Java

Uploaded by

hemmalathagandhi
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)
34 views8 pages

Java Complete Guide

Complete Java

Uploaded by

hemmalathagandhi
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

Java Complete Guide (Interview Edition)

1. Introduction to Java
Java is a high-level, class-based, object-oriented programming language that is designed to have
as few implementation dependencies as possible. It is platform-independent, which means code
written in Java can run anywhere with the JVM.

2. Basic Syntax
Every Java program starts with a class definition and a main method. Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

3. Data Types and Variables


Java has two categories of data types: - Primitive (int, double, char, boolean, etc.) - Non-primitive
(Strings, Arrays, Objects).
int age = 25;
double price = 99.99;
char grade = 'A';
boolean isJavaFun = true;

4. Object-Oriented Programming (OOP)


Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, Abstraction. Example of
Class & Object:
class Car {
String brand;
int year;

Car(String brand, int year) {


this.brand = brand;
this.year = year;
}

void display() {
System.out.println(brand + " - " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car("Tesla", 2024);
car1.display();
}
}

5. Exception Handling
Java provides try-catch blocks to handle runtime errors gracefully.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}

6. Collections Framework
The Java Collections Framework provides data structures like List, Set, Map. Example:
import java.util.*;

public class CollectionExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

for(String fruit : list) {


System.out.println(fruit);
}
}
}

7. Multithreading
Java supports multithreading to run multiple tasks simultaneously.
class MyThread extends Thread {
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

8. Real-Time Example: Selenium WebDriver with Java


Example of using Selenium WebDriver with Java to open Google and search.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;

public class GoogleSearchTest {


public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();

driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("Java Tutorial");
driver.findElement(By.name("q")).submit();

System.out.println("Page Title: " + driver.getTitle());


driver.quit();
}
}

9. Generics in Java
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces,
and methods. This provides stronger type checks at compile-time and eliminates the need for
typecasting.
class Box<T> {
private T content;

public void setContent(T content) {


this.content = content;
}

public T getContent() {
return content;
}
}

public class Main {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.setContent(123);
System.out.println(intBox.getContent());
}
}

10. Java Streams & Lambda Expressions


Lambda expressions and Streams make it easier to process collections in a functional style.
import java.util.*;
import java.util.stream.*;

public class StreamExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Tom", "Jerry");

names.stream()
.filter(n -> n.startsWith("J"))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}

11. JDBC (Java Database Connectivity)


JDBC is used to connect and execute queries with databases.
import java.sql.*;

public class JdbcExample {


public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root"
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

while(rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}

12. Design Patterns in Java


Design patterns are proven solutions to common problems in software design. Some popular
patterns in Java include Singleton, Factory, and Observer.
// Singleton Pattern Example
class Singleton {
private static Singleton instance;

private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

public class Main {


public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
System.out.println(obj1 == obj2); // true
}
}

13. Java 8+ Features


Java 8 and beyond introduced key features like: - Functional Interfaces - Default & Static Methods
in Interfaces - Streams API - Optional Class - New Date & Time API (java.time).
import java.time.LocalDateTime;

public class DateTimeExample {


public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current DateTime: " + now);
}
}

14. Unit Testing with JUnit


JUnit is a popular framework to write and run repeatable automated tests in Java.
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CalculatorTest {


@Test
public void testAddition() {
Calculator calc = new Calculator();
assertEquals(10, calc.add(5, 5));
}
}

class Calculator {
public int add(int a, int b) {
return a + b;
}
}

15. Real-Time Project Example: Selenium with Page Object Model


The Page Object Model (POM) is a design pattern in Selenium that enhances test maintenance and
reduces code duplication.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

class LoginPage {
WebDriver driver;

@FindBy(id="username")
WebElement usernameField;

@FindBy(id="password")
WebElement passwordField;
@FindBy(id="loginBtn")
WebElement loginButton;

LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}

public void login(String user, String pass) {


usernameField.sendKeys(user);
passwordField.sendKeys(pass);
loginButton.click();
}
}

public class LoginTest {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");

LoginPage login = new LoginPage(driver);


login.login("admin", "password123");

driver.quit();
}
}

16. Java Interview Q&A;


Here are some frequently asked Java interview questions with answers and code snippets.

Q1: Difference between == and .equals()?


- == checks reference equality (whether two references point to the same object). - .equals() checks
value equality (whether two objects are meaningfully equal).
String a = new String("Java");
String b = new String("Java");

System.out.println(a == b); // false (different references)


System.out.println(a.equals(b)); // true (same content)

Q2: What is the difference between final, finally, and finalize()?


- final: Used to declare constants, prevent method overriding, or inheritance. - finally: A block used
in exception handling, always executes. - finalize(): A method called by Garbage Collector before
object destruction.

Q3: Explain Checked vs Unchecked Exceptions.


- Checked exceptions: Must be declared/handled at compile-time (e.g., IOException,
SQLException). - Unchecked exceptions: Occur at runtime (e.g., NullPointerException,
ArithmeticException).

Q4: Coding Challenge - Find the first non-repeated character in a


String.
This is a common string manipulation interview question.
import java.util.*;

public class FirstNonRepeated {


public static void main(String[] args) {
String input = "programming";
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

for(char c : input.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}

for(Map.Entry<Character, Integer> entry : map.entrySet()) {


if(entry.getValue() == 1) {
System.out.println("First non-repeated: " + entry.getKey());
break;
}
}
}
}

Q5: Coding Challenge - Reverse a Linked List.


Reversing a linked list is a very common data structure question.
class Node {
int data;
Node next;
Node(int d) { data = d; }
}

public class ReverseLinkedList {


public static Node reverse(Node head) {
Node prev = null, curr = head, next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}

public static void main(String[] args) {


Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head = reverse(head);

while (head != null) {


System.out.print(head.data + " ");
head = head.next;
}
}
}

Q6: Coding Challenge - Implement Singleton Design Pattern


(Thread Safe).
Interviewers often ask about Singleton pattern implementation.
class Singleton {
private static volatile Singleton instance;
private Singleton() {}

public static Singleton getInstance() {


if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
End of Interview Edition
This guide now includes Java basics, advanced concepts, real-time Selenium integration, and
interview Q&A; with coding challenges.

You might also like