Download Java Cheat Sheet for Beginners: Core Language Constructs and Concepts and more Study notes Programming Languages in PDF only on Docsity!
Java
Cheat Sheet
Mosh Hamedani
Code with Mosh (codewithmosh.com)
1st Edition
About this Cheat Sheet
This cheat sheet includes the materials Iโve covered in my Java tutorial for
Beginners on my YouTube channel:
https://www.youtube.com/user/programmingwithmosh
Both the YouTube tutorial and this cheat cover the core language constructs and
they are not complete by any means.
If you want to learn everything Java has to offer and become a Java expert, check
out my Ultimate Java Mastery Series.
https://codewithmosh.com/courses/the-ultimate-java-mastery-series
- Basics
- Java Development Kit
- Java Editions
- How Java Code Gets Executed
- Architecture of Java Applications
- 5 Interesting Facts about Java
- Types
- Variables
- Primitive Types
- Declaring Variables
- Comments
- Reference Types
- Strings
- Useful String Methods
- Escape Sequences
- Arrays
- The Array Class
- Multi-dimensional Arrays
- Constants
- Arithmetic Expressions
- Order of Operations
- Casting
- Formatting Numbers
- Reading Input
- Control Flow
- Comparison Operators
- Logical Operators
- If Statements
- The Ternary Operator
- Switch Statements
- For Loops
- While Loops
- Do..While Loops
- For-each Loops
- Want to Become a Java Expert?
The smallest building blocks in Java programs are methods (also called functions
in other programming languages). We combine related methods in classes , and
related classes in packages. This modularity in Java allows us to break down large
programs into smaller building blocks that are easier to understand and re-use.
5 Interesting Facts about Java
1. Java was developed by James Gosling in 1995 at Sun Microsystems (later
acquired by Oracle).
2. It was initially called Oak. Later it was renamed to Green and was finally
renamed to Java inspired by Java coffee.
3. Java has close to 9 million developers worldwide.
4. About 3 billion mobile phones run Java, as well as 125 million TV sets and
every Blu-Ray player.
5. According to indeed.com, the average salary of a Java developer is just over
$100,000 per year in the US.
Types Variables
We use variables to temporarily store data in computerโs memory. In Java, the type
of a variable should be specified at the time of declaration.
In Java, we have two categories of types:
- Primitives: for storing simple values like numbers, strings and booleans.
- Reference Types: for storing complex objects like email messages. Primitive Types Declaring Variables byte age = 30; long viewsCount = 3_123_456L; float price = 10.99F; char letter = โAโ; boolean isEligible = true;
- In Java, we terminate statements with a semicolon. Type Bytes Range byte 1 [-128, 127] short (^) 2 [-32K, 32K] int (^) 4 [-2B, 2B] long (^) 8 float (^) 4 double (^) 8 char (^) 2 A, B, C, โฆ boolean (^) 1 true / false
- indexOf(โaโ)
- replace(โaโ, โbโ)
- toUpperCase()
- toLowerCase()
Strings are immutable, which means once we initialize them, their value cannot be
changed. All methods that modify a string (like toUpperCase) return a new string
object. The original string remains unaffected.
Escape Sequences
If you need to use a backslash or a double quotation mark in a string, you need to
prefix it with a backslash. This is called escaping.
Common escape sequences:
- \
- \โ
- \n (new line)
- \t (tab) Arrays
We use arrays to store a list of objects. We can store any type of object in an array
(primitive or reference type). All items (also called elements) in an array have the
same type.
// Creating and and initializing an array of 5 elements int[] numbers = new int[3]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; // Shortcut int[] numbers = { 10, 20, 30 };
Java arrays have a fixed length (size). You cannot add or remove new items once
you instantiate an array. If you need to add new items or remove existing items,
you need to use one of the collection classes.
The Array Class
The Array class provides a few useful methods for working with arrays.
int[] numbers = { 4, 2, 7 }; Arrays.sort(numbers); String result = Arrays.toString(numbers); System.out.println(result); Multi-dimensional Arrays // Creating a 2x3 array (two rows, three columns) int[2][3] matrix = new int[2][3]; matrix[0][0] = 10; // Shortcut int[2][3] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; Constants
Constants (also called final variables) have a fixed value. Once we set them, we
cannot change them.
final float INTEREST_RATE = 0.04;
By convention, we use CAPITAL LETTERS to name constants. Multiple words can
be separated using an underscore.
Arithmetic Expressions int x = 10 + 3;
// Explicit casting int x = 1; short y = (short) x;
To convert a string to a number, we use one of the following methods:
- Byte.parseByte(โ1โ)
- Short.parseShort(โ1โ)
- Integer.parseInt(โ1โ)
- Long.parseLong(โ1โ)
- Float.parseFloat(โ1.1โ)
- Double.parseDouble(โ1.1โ) Formatting Numbers NumberFormat currency = NumberFormat.getCurrencyInstance(); String result = currency.format(โ123456โ); // $123, NumberFormat percent = NumberFormat.getPercentInstance(); String result = percent(โ0.04โ); // 4% Reading Input Scanner scanner = new Scanner(system.in); double number = scanner.nextDouble(); byte number = scanner.nextByte(); String name = scanner.next(); String line = scanner.nextLine();
Control Flow Comparison Operators
We use comparison operators to compare values.
x == y // equality operator x != y. // in-equality operator x > y x >= y x < y x <= y Logical Operators
We use logical operators to combine multiple boolean values/expressions.
- x && y (AND): if both x and y are true, the result will be true.
- x || y (OR): if either x or y or both are true, the result will be true.
- !x (NOT): reverses a boolean value. True becomes false. bool hasHighIncome = true; bool hasGoodCredit = false; bool hasCriminalRecord = false; bool isEligible = (hasHighIncome || hasGoodCredit) && !isEligible; If Statements
Here is the basic structure of an if statement. If you want to execute multiple
statements, you need to wrap them in curly braces.
if (condition1) statement else if (condition2) statement else if (condition3) statement
For Loops
For loops are useful when we know ahead of time how many times we want to
repeat something. We declare a loop variable (or loop counter) and in each
iteration we increment it until we reach the number of times we want to execute
some code.
for (int i = 0; i < 5; i++) statement While Loops
While loops are useful when we donโt know ahead of time how many times we want
to repeat something. This may be dependent on the values at run-time (eg what the
user enters).
while (someCondition) { โฆ if (someCondition) break; }
We use the break statement to jump out of a loop.
Do..While Loops
Do..While loops are very similar to while loops but they executed at least once. In
contrast, a while loop may never get executed if the condition is initially false.
do { โฆ } while (someCondition); For-each Loops
For-each loops are useful for iterating over an array or a collection.
int[] numbers = {1, 2, 3, 4}; for (int number : numbers)