0% found this document useful (0 votes)
2 views13 pages

C++ to Java_ 1-Week Learning Guide

This 1-week learning guide helps C++ developers quickly master Java by focusing on key differences such as memory management, object-oriented principles, and exception handling. Each day covers specific topics including setup, classes, inheritance, collections, and advanced features like lambda expressions and file I/O. The guide emphasizes practical projects and best practices to aid in the transition from C++ to Java.

Uploaded by

vadersback04
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)
2 views13 pages

C++ to Java_ 1-Week Learning Guide

This 1-week learning guide helps C++ developers quickly master Java by focusing on key differences such as memory management, object-oriented principles, and exception handling. Each day covers specific topics including setup, classes, inheritance, collections, and advanced features like lambda expressions and file I/O. The guide emphasizes practical projects and best practices to aid in the transition from C++ to Java.

Uploaded by

vadersback04
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/ 13

C++ to Java: 1-Week Learning Guide

Overview
This guide leverages your C++ knowledge to quickly master Java fundamentals. Focus on differences
rather than similarities.

Day 1: Core Differences & Setup

Key Philosophical Differences


Memory Management: No pointers, no manual memory management, garbage collection handles
everything

Platform Independence: "Write once, run anywhere" via JVM


Pure OOP: Everything is a class (except primitives)
Single Inheritance: Only one parent class, but multiple interfaces

Setup & Hello World

java

// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Key Points:

Filename must match class name exactly


public static void main(String[] args) is the entry point

No #include - use import statements

Compile with javac , run with java

Primitive Types vs C++


Java C++ Equivalent Size

byte char 8-bit

short short 16-bit

int int 32-bit

long long long 64-bit

float float 32-bit

double double 64-bit

boolean bool N/A

char wchar_t 16-bit Unicode

Major Difference: All numeric types have fixed sizes across platforms.

Day 2: Object-Oriented Programming

Classes and Objects

java

public class Person {


// Instance variables (like C++ member variables)
private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name; // 'this' like C++ 'this->'
this.age = age;
}

// Getter (accessor)
public String getName() {
return name;
}

// Setter (mutator)
public void setAge(int age) {
this.age = age;
}
}
Key Differences from C++

No header files - everything in one .java file

No destructors - garbage collector handles cleanup

All methods are virtual by default (can be overridden)

final keyword prevents inheritance/overriding (like C++ final )

Access Modifiers
private : Same as C++

protected : Same as C++, plus same package access

public : Same as C++

(default): Package-private (new concept)

Day 3: Inheritance and Polymorphism

Inheritance

java
// Base class
public class Animal {
protected String name;

public Animal(String name) {


this.name = name;
}

public void makeSound() {


System.out.println("Some sound");
}
}

// Derived class
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}

@Override // Annotation (good practice)


public void makeSound() {
System.out.println("Woof!");
}
}

Interfaces (Like C++ Pure Virtual Classes)

java
public interface Drawable {
void draw(); // Implicitly public and abstract

// Java 8+: Default methods


default void print() {
System.out.println("Drawing something");
}
}

public class Circle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing circle");
}
}

Key Points:

Single inheritance with extends

Multiple interface implementation with implements


super keyword to access parent class

@Override annotation for clarity

Day 4: Exception Handling and Strings

Exception Handling

java
// Similar to C++ but mandatory for checked exceptions
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Always executes");
}

public int divide(int a, int b) throws ArithmeticException {


if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}

Types of Exceptions:

Checked: Must be caught or declared (IOException, etc.)

Unchecked: Runtime exceptions (NullPointerException, etc.)

Strings (Major Difference from C++)

java

String str1 = "Hello"; // String literal


String str2 = new String("Hello"); // String object

// Strings are immutable!


String result = str1 + " World"; // Creates new string

// StringBuilder for mutable strings (like C++ string)


StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String final = sb.toString();

Day 5: Collections Framework

Arrays

java
// Similar to C++ arrays but with bounds checking
int[] numbers = new int[5];
int[] values = {1, 2, 3, 4, 5};

// Multidimensional
int[][] matrix = new int[3][4];

Collections (Like C++ STL)

java

import java.util.*;

// ArrayList (like C++ vector)


List<String> list = new ArrayList<>();
list.add("item1");
list.add("item2");

// HashMap (like C++ unordered_map)


Map<String, Integer> map = new HashMap<>();
map.put("key1", 100);
map.put("key2", 200);

// HashSet (like C++ unordered_set)


Set<String> set = new HashSet<>();
set.add("unique1");
set.add("unique2");

Generics (Like C++ Templates, but simpler)

java
public class Box<T> {
private T content;

public void set(T content) {


this.content = content;
}

public T get() {
return content;
}
}

Box<Integer> intBox = new Box<>();


Box<String> stringBox = new Box<>();

Day 6: Advanced Features

Lambda Expressions (Java 8+)

java

// Like C++ lambdas but simpler syntax


List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Old way
names.forEach(new Consumer<String>() {
public void accept(String name) {
System.out.println(name);
}
});

// Lambda way
names.forEach(name -> System.out.println(name));
names.forEach(System.out::println); // Method reference

Streams (Functional Programming)

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

List<Integer> evenSquares = numbers.stream()


.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());

Packages (Like C++ namespaces)

java

package com.mycompany.myproject;

import java.util.List;
import java.util.ArrayList;
import static java.lang.Math.PI; // Static import

Day 7: Practical Java and Best Practices

File I/O

java

import java.io.*;
import java.nio.file.*;

// Reading a file
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

// Writing to a file
try (PrintWriter writer = new PrintWriter("output.txt")) {
writer.println("Hello, File!");
} catch (IOException e) {
e.printStackTrace();
}
Java Conventions vs C++

Naming: camelCase for methods/variables, PascalCase for classes


Constants: UPPER_SNAKE_CASE with static final

Packages: com.company.project (reverse domain)

Common Patterns

java
// Singleton Pattern
public class Singleton {
private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

// Builder Pattern (common in Java)


public class Person {
private final String name;
private final int age;

private Person(Builder builder) {


this.name = builder.name;
this.age = builder.age;
}

public static class Builder {


private String name;
private int age;

public Builder setName(String name) {


this.name = name;
return this;
}

public Builder setAge(int age) {


this.age = age;
return this;
}

public Person build() {


return new Person(this);
}
}
}

Quick Reference: C++ vs Java


Concept C++ Java

Memory Management Manual ( new / delete ) Automatic (GC)

Pointers Yes No (references only)

Multiple Inheritance Yes No (interfaces instead)

Header Files Yes No

Compilation Native code Bytecode (JVM)

Operator Overloading Yes No (except + for strings)

Unsigned Types Yes No

Preprocessor Yes No

Templates/Generics Templates Generics (type erasure)

Practice Projects for Week 1


1. Day 1-2: Simple calculator with classes
2. Day 3-4: Animal hierarchy with interfaces and exception handling

3. Day 5-6: Contact management system using collections


4. Day 7: File-based data processing with streams

Essential Java Tools


IDE: IntelliJ IDEA (recommended) or Eclipse
Build Tools: Maven or Gradle
Documentation: Oracle Java Documentation

Practice: LeetCode, HackerRank (Java sections)

Key Takeaways for C++ Developers


1. Embrace garbage collection - don't think about memory management

2. Everything is an object reference (except primitives)


3. Use interfaces extensively for flexible design
4. Exception handling is more prominent and mandatory for checked exceptions
5. Collections framework is your friend - use it heavily
6. Java is more verbose but more explicit and safer

7. Platform independence comes at the cost of some performance

Good luck with your Java journey! Your C++ knowledge gives you a strong foundation - focus on the
paradigm shifts rather than syntax details.

You might also like