Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Basic Java Cheat Sheet

This document provides a basic cheat sheet for common Java concepts like variables, operators, data types, methods, classes, and inheritance. It includes code examples for declaring and using variables, performing arithmetic operations and string concatenation, converting between data types, comparing values, using loops and arrays, defining methods, creating classes to organize code and represent objects, and inheriting properties from parent classes. The cheat sheet is intended as a reference guide for learning core Java concepts and syntax.

Uploaded by

punyaku2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Basic Java Cheat Sheet

This document provides a basic cheat sheet for common Java concepts like variables, operators, data types, methods, classes, and inheritance. It includes code examples for declaring and using variables, performing arithmetic operations and string concatenation, converting between data types, comparing values, using loops and arrays, defining methods, creating classes to organize code and represent objects, and inheriting properties from parent classes. The cheat sheet is intended as a reference guide for learning core Java concepts and syntax.

Uploaded by

punyaku2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Basic Java Cheat Sheet

Java Variables 2
Operators in Java 3
Type Conversion in Java 4
Comparing Stuff in Java 5
Loops in Java 6
Arrays in Java 7
Methods in Java 8
Classes in Java 9
Inheritance in Java 10

Usage notes:

You can use this document alongside a learnappdevelopement.com video course.


Following completion of that course the document is intended to become a reference
guide - allowing you to look up typical Java language usage.

1
Java Variables

Variables are the smallest practical working blocks of any application. They are essentially small
pieces of data stored in special purpose containers.

Integers store a whole number, including negatives:

int a = 9;
int x = -99;

Doubles store numbers with decimals:

double b = 9.879;

Floats also store decimal numbers but they have a lower accuracy than Doubles:

float c = 10.887f; (note the ‘f’ ending)

Booleans store a true or false value:

boolean d = false

Strings store words or letters

String myText = “I like this cheat sheet”;

Variables are the basic building blocks of all software. They cannot be mixed so you cannot store
an int inside of a string or vice versa.

2
Operators in Java

Operators allow sums between numbers to take place. They also allow concatenation of strings
(adding words onto other words).

Adding a number:

int myNum = 9;

int otherNum = 10;

int result = myNum + otherNum;

(The result would be equal to 19)

Subtracting a number:

int result = myNum - otherNum;

(The result would be equal to -1)

Multiplying a number:

int result = myNum * otherNum;

(The result would be equal to 90)

Dividing a number:

int result = myNum / otherNum;

(The result would be equal to 0). Wait what? Well, ‘int’ can only hold a whole number and 9 / 10
= 0.9. Therefore ‘int result’ simply drops the ‘.9’ part! Be careful when performing arithmetic!

Adding Strings

String myText = “I like this cheat sheet”;

String myOtherText = “Oh I really do!”;

String fullSentence = myText + “. “ + myOtherText;

(Result = “I like this cheat sheet. Oh I really do!”;

3
Type Conversion in Java

You can’t mix types in Java but you can convert between them (with some limitations). If you can
avoid conversion then DO as conversions are where insidious errors can lurk - waiting to crash
your program.

Convert from most types to string:

Integer myNum = 90;

String word = myNum.toString();

(The result would be the word “90”)

Alternatively:

int myNum = 90;

String word = Integer.toString(myNum);

Convert from string to number:

String myText = “98”;

int myNum = Integer.parseInt (myText);

(Result is integer number 98);

WATCH OUT! the following throws an app crashing error:

string myText = “Grant”;

int myNum = integer.parseInt (myText); BIG ERROR HERE!

Why an error? You cant convert a word to a number so your app will kick and scream, bringing
the whole thing down. This is why you should avoid type conversion where possible.

4
Comparing Stuff in Java

What if you want to compare numbers or strings?

if else statements:

String a = "grant";
String b = "grant2";

if (a.equals(b)) {
System.out.println("equal");
}
else if (!a.equals(b)) {
System.out.println("not equal");
}
else {
System.out.println("default");
}

int a = 9;
int b = 10;

if (a == b) {
System.out.println("equal");
}
else if (a != b) {
System.out.println("not equal");
}
else {
System.out.println("default");
}

switch case statements:

int a = 4;

switch (a)
{
case 3:
System.out.println("3");
break;
case 4:
System.out.println("4");
break;
default:
System.out.println("default");
break;
}

5
Loops in Java

Round and round until we meet some condition

while loops:

int i = 0;

while (i < 100) {

(run code in here each time we go around and i is less than 100)
i++; (adds one to i each time we go around)
}

(while loop ends when i is 100 or more)

for loops:

These are kind of like while loops but with a little more control

for (int i = 0; i < 100; i++) {


(run code in here each time we go around and i is less than 100)
}

(for loop ends when i is 100 or more)

6
Arrays in Java

What if you’d like to hold a list of items, all of the same type?

Create a string array:

string [ ] myArray = new string [ ] { “Grant”, “Learn”, “App”, “Development” };

Create an integer array:

int [ ] myArray = new int [ ] { 3, 98, 9874, 236763276327 };

Get elements out of array:

var secondItem = myArray [1];

(Why do you write ‘1’ and not ‘2’ to get second element? Because all indexing in programming is
based on numbers starting at ‘0’ so our program counts - 0, 1, 2, 3 etc. )

How long is your array or how many elements does it have?

int arrayLength = myArray.Length;

7
Methods in Java

What if you want to do stuff to your variables? It would be horrible to write ‘myNum + otherNum’
EVERY time you needed it. Methods allow you to store that code in one place that can be
accessed multiple times and from multiple places.

Eg: A method to add 2 numbers:

public void addNumbers (int myNum, int otherNum) {

int result = myNum + otherNum;

public - means the method is accessible by other parts of your program.


void - means the method doesn't return anything.
(int myNum, int otherNum) - these are arguments. Arguments are values handed over to the
method, necessary for it to do what it does. A method can have no arguments if none are
needed.

Calling a method:

addNumbers (9, 10);

Can you see how this cuts down on repetitive code?

8
Classes in Java

You have variables and methods now. Where should you put them? In classes! Classes have 2
objectives - the first of which is to organise your code. Java also generally expects variables and
methods to be enclosed in classes - it’s kind of obsessive like that!

Define a class (must be contained in a Java file of the same name as the class):

public class Car


{
int speed;
String color;

public Car (int speed, String color) {


this.speed = speed;
this.color = color;
}

public int getSpeed() {


return this.speed;
}

public String getColor() {


return this.color;
}
}

The second thing classes do is become blueprints for types of objects. In this case the class
holds a blueprint for a car.

Make some cars:

Car toyota = new Car(50, "red");


Car ferrari = new Car(200, "green");

Get their top speeds:

int toyotaTopSpeed = toyota.getSpeed ( );

int ferrariTopSpeed = ferrari.getSpeed ( );

Classes are mighty useful for defining new kinds of objects and VASTLY reducing code reuse.
Making objects from classes is one of the core principles of ‘Object Oriented Programming’. You
may see this abbreviated to OOP in some places.

9
Inheritance in Java

Classes don’t have to be redefined every time you make them. They can ‘inherit’ other class
properties and methods.

Define a Vehicle class saved as Vehicle.java:

public class Vehicle


{
int topSpeed = 100;
String color = “red”;

public Vehicle () {
}
}

Make a Truck class saved as Truck.java:

public class Truck extends Vehicle


{
(truck inherits from vehicle so truck already has a topSpeed and color)

Make a Car class:

public class Car extends Vehicle


{
(car inherits from vehicle so car also has a topSpeed and color)

10

You might also like