mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
9.5 KiB
9.5 KiB
language | author | author_url |
---|---|---|
java | Jake Prather | http://github.com/JakeHP |
Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. Read more here: https://en.wikipedia.org/wiki/Java_(programming_language)
///////////////////////////////////////
// General
///////////////////////////////////////
// Single-line comments start with //
/*
Multi-line comments look like this.
*/
// Import Packages
import java.util.ArrayList;
import package.path.here;
// Import all "sub-packages"
import java.lang.Math.*;
// Your program's entry point is a function called main
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//stuff here
}
}
// Printing, and forcing a new line on next print = println()
System.out.println("Hello World");
System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true);
// Printing, without forcing a new line on next print = print()
System.out.print("Hello World");
System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true);
///////////////////////////////////////
// Types
///////////////////////////////////////
// Byte - 8-bit signed two's complement integer (-128 <= byte <= 127)
byte foo = 100;
// Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767)
short bar = 10000;
//Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647)
int foo = 1;
//Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
long bar = 100000L;
//Float - Single-precision 32-bit IEEE 754 Floating Point
float foo = 234.5f;
//Double - Double-precision 64-bit IEEE 754 Floating Point
double bar = 123.4;
//Boolean - True & False
boolean foo = true;
boolean bar = false;
//Char - A single 16-bit Unicode character
char foo = 'A';
//Strings
String foo = "Hello World!";
// \n is an escaped character that starts a new line
String foo = "Hello World!\nLine2!";
System.out.println(foo);
//Hello World!
//Line2!
//Arrays
//The array size must be decided upon declaration
//The format for declaring an array is follows:
//<datatype> [] <var name> = new <datatype>[<array size>];
int [] array = new int[10];
String [] array = new String[1];
boolean [] array = new boolean[100];
// Indexing an array - Accessing an element
array[0];
// Arrays are mutable; it's just memory!
array[1] = 1;
System.out.println(array[1]); // => 1
array[1] = 2;
printf("%d\n", my_array[1]); // => 2
//Others to check out
//ArrayLists - Like arrays except more functionality is offered, and the size is mutable
//LinkedLists
//Maps
//HashMaps
///////////////////////////////////////
// Operators
///////////////////////////////////////
int i1 = 1, i2 = 2; // Shorthand for multiple declarations
// Arithmetic is straightforward
i1 + i2; // => 3
i2 - i1; // => 1
i2 * i1; // => 2
i1 / i2; // => 0 (0.5, but truncated towards 0)
// Modulo
11 % 3; // => 2
// Comparison operators
3 == 2; // => 0 (false)
3 != 2; // => 1 (true)
3 > 2; // => 1
3 < 2; // => 0
2 <= 2; // => 1
2 >= 2; // => 1
// Bitwise operators!
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
if (false) {
System.out.println("I never run");
} else if (false) {
System.out.println("I am also never run");
} else {
System.out.println("I print");
}
}
// While loops exist
int ii = 0;
while (ii < 10) {
printf("%d, ", ii++); // ii++ increments ii in-place, after using its value.
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
printf("\n");
int kk = 0;
do {
printf("%d, ", kk);
} while (++kk < 10); // ++kk increments kk in-place, before using its value
// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
printf("\n");
// For loops too
int jj;
for (jj=0; jj < 10; jj++) {
printf("%d, ", jj);
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
printf("\n");
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
// Every value in C has a type, but you can cast one value into another type
// if you want.
int x_hex = 0x01; // You can assign vars with hex literals
// Casting between types will attempt to preserve their numeric values
printf("%d\n", x_hex); // => Prints 1
printf("%d\n", (short) x_hex); // => Prints 1
printf("%d\n", (char) x_hex); // => Prints 1
// Types will overflow without warning
printf("%d\n", (char) 257); // => 1 (Max char = 255)
// Integral types can be cast to floating-point types, and vice-versa.
printf("%f\n", (float)100); // %f formats a float
printf("%lf\n", (double)100); // %lf formats a double
printf("%d\n", (char)100.0);
///////////////////////////////////////
// Pointers
///////////////////////////////////////
// A pointer is a variable declared to store a memory address. Its declaration will
// also tell you the type of data it points to. You can retrieve the memory address
// of your variables, then mess with them.
int x = 0;
printf("%p\n", &x); // Use & to retrieve the address of a variable
// (%p formats a pointer)
// => Prints some address in memory;
// Pointer types end with * in their declaration
int* px; // px is a pointer to an int
px = &x; // Stores the address of x in px
printf("%p\n", px); // => Prints some address in memory
// To retreive the value at the address a pointer is pointing to,
// put * in front to de-reference it.
printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of
// You can also change the value the pointer is pointing to.
// We'll have to wrap the de-reference in parenthesis because
// ++ has a higher precedence than *.
(*px)++; // Increment the value px is pointing to by 1
printf("%d\n", *px); // => Prints 1
printf("%d\n", x); // => Prints 1
int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory
int xx;
for (xx=0; xx<20; xx++) {
x_array[xx] = 20 - xx;
} // Initialize x_array to 20, 19, 18,... 2, 1
// Declare a pointer of type int and initialize it to point to x_array
int* x_ptr = x_array;
// x_ptr now points to the first element in the array (the integer 20).
// This works because arrays are actually just pointers to their first element.
// Arrays are pointers to their first element
printf("%d\n", *(x_ptr)); // => Prints 20
printf("%d\n", x_array[0]); // => Prints 20
// Pointers are incremented and decremented based on their type
printf("%d\n", *(x_ptr + 1)); // => Prints 19
printf("%d\n", x_array[1]); // => Prints 19
// You can also dynamically allocate contiguous blocks of memory with the
// standard library function malloc, which takes one integer argument
// representing the number of bytes to allocate from the heap.
int* my_ptr = (int*) malloc(sizeof(int) * 20);
for (xx=0; xx<20; xx++) {
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
// Dereferencing memory that you haven't allocated gives
// unpredictable results
printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what?
// When you're done with a malloc'd block of memory, you need to free it,
// or else no one else can use it until your program terminates
free(my_ptr);
// Strings can be char arrays, but are usually represented as char
// pointers:
char* my_str = "This is my very own string";
printf("%c\n", *my_str); // => 'T'
function_1();
} // end main function
///////////////////////////////////////
// Functions
///////////////////////////////////////
// Function declaration syntax:
// <return type> <function name>(<args>)
int add_two_ints(int x1, int x2){
return x1 + x2; // Use return to return a value
}
/*
Functions are pass-by-value, but you can make your own references
with pointers so functions can mutate their values.
Example: in-place string reversal
*/
// A void function returns no value
void str_reverse(char* str_in){
char tmp;
int ii=0, len = strlen(str_in); // Strlen is part of the c standard library
for(ii=0; ii<len/2; ii++){
tmp = str_in[ii];
str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
str_in[len - ii - 1] = tmp;
}
}
/*
char c[] = "This is a test.";
str_reverse(c);
printf("%s\n", c); // => ".tset a si sihT"
*/
///////////////////////////////////////
// User-defined types and structs
///////////////////////////////////////
// Typedefs can be used to create type aliases
typedef int my_type;
my_type my_type_var = 0;
// Structs are just collections of data
struct rectangle {
int width;
int height;
};
void function_1(){
struct rectangle my_rec;
// Access struct members with .
my_rec.width = 10;
my_rec.height = 20;
// You can declare pointers to structs
struct rectangle* my_rec_ptr = &my_rec;
// Use dereferencing to set struct pointer members...
(*my_rec_ptr).width = 30;
// ... or use the -> shorthand
my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10;
}
// You can apply a typedef to a struct for convenience
typedef struct rectangle rect;
int area(rect r){
return r.width * r.height;
}
Further Reading
Best to find yourself a copy of K&R, aka "The C Programming Language"
Another good resource is Learn C the hard way
Other than that, Google is your friend.