0% found this document useful (0 votes)
7 views5 pages

Java Cheat Sheet

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)
7 views5 pages

Java Cheat Sheet

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

University of Virginia, Department of Computer Science

Java Cheat Sheet

Dr. Mark R. Floryan


September 3, 2018

1 Java: General Things to Remember

1. All code must be inside of a class definition (except import and package statements).

2. Every line of code must end with a semi-colon. This excludes lines that formulate
"blocks", like if(), while(), or class declarations.

3. The name of the class in a file must match the name of the file. For example,
"public class LinkedList" must be in a file called "LinkedList.java"

4. Classes can contain a method "public static void main(String[] args)" as an entry
point to the whole program.

5. Whitespace does NOT matter in java. The compiler will completely ignore all
whitespace.

2 Primitive Data Types

The primitive variable types are:

1
1 int x = 5; // integers
double d = 3.4; // decimal values
3 char c = ’h ’; // characters . Use single quotes .
boolean b = false ; // true or false
5

/* Other much less commonly used */


7 byte b = 24 b ;
short s = -8 s ;
9 long l = 2000000;
float = 4.567;

Some examples of using these data types include:


int x ; // automatically set to 0 by default
2 x ++; // increment integer by 1
x - -; // decrement integer by 1
4

int z = 14;
6

int total = ( x + z ) * x ; // expressions


8 int remainder = x % z ; // remainder after x / z

10 /* Boolean operators */
boolean b1 = false ;
12 boolean b2 = true ;
boolean result ;
14

result = b1 && b2 ; // logical AND


16 result = b1 || b2 ; // logical OR
result = ! b1 ; // logical negation

3 Input Output

Input from the keyboard can be done like this:


1 Scanner in = new Scanner ( System . in ); // make a scanner object
int x = in . nextInt (); // read int from keyboard
3 double y = in . nextDouble (); // read double from keyboard
float f = in . nextFloat (); // read float from keyboard
5 boolean b = in . nextBoolean (); // read bool from keyboard
long l = in . nextLong (); // read long from keyboard
7 String s = in . next (); // read string from keyboard

2
Input from a file can be done like this:
1 BufferedReader in =
new BufferedReader ( new FileReader ( " inputfile . txt " ));
3 String text = in . readLine (); // reads the next line
in . close ();

Output to the console is done like this:


// prints text concatenated with x
2 System . out . print ( " The answer is " + x );

4 // prints and moves cursor to next line


System . out . println ( " something else " );

Output to a file can be done like this:


1 PrintWriter outFile =
new PrintWriter ( new FileWriter ( " outputfile . txt " )));
3 outFile . print ( " Hello " );
outFile . println ( " world " );
5 outFile . close ();

4 Strings

Strings are reference types in Java (so they are NOT primitives).
1 String s1 = " Hello " ; // example string
String s2 ; // "" empty string by default
3 String s3 = new String ( " Hi " ); // Also makes a string

Common operators on strings include:


1 String result ;

3 result = s1 + s2 ; // " hi " + " there " = " hi there "


s1 . length (); // returns length of string
5 s1 . charAt (2); // accesses the char at position 2 ( indexed from 0)
s1 . substring (1 ,3); // part of string from index 1 to 3 ( exclusive )
7 s1 . equals ( s2 ); // compare strings using this structure
s1 . toUpperCase (); // returns the string as all uppercase
9 s1 . toLowerCase (); // returns the string as all lowercase

3
5 Converting Between Data Types

In Java, we often need to convert between different types of variables. Here are some
common conversions:
1 /* int ( or any other primitive ) to string */
int x = 5;
3 String s = " " + x ; // "" + variable concatenates as a string

5 /* String version of number to int or double */


int i = Integer . parseInt ( " 123 " ); // converts string "123" into intege
7 double d = Double . parseDouble ( " 3.14 " ) // converts string "3.14" into doubl

9 /* dividing integers does integer division */


int x1 = 3;
11 int x2 = 5;
double result = x1 / x2 ; // 3/5=( int )0.6 = 0
13 result = ( double ) x1 / ( double ) x2 ; // 0.6

15 /* double to int */
double x = 3.467;
17 int y = ( int ) x ; // y is 3 , decimal truncated

6 Arrays

Three primary ways to instantiate arrays:


1 double [] dArray = new double [5]; // know the size , but not contents
int [] oddNumbers = {1 ,3 ,5 ,7 ,9}; // know the contents already
3

int x ;
5 /* Stuff here */
String [] sArray = new String [ x ]; // use variable to intialize array
7

int [][] = new int [5][4]; // two - dimensional array

Some common things we do with arrays include:


x [3] = 5; // Access array at position 3 , set to 5.
2 x . length ; // get the number of elements in array

4 /* How to loop through an array */

4
for ( int i =0; i < x . length ; i ++){
6 System . out . println ( x [ i ]);
}

7 Java Math Library

Java contains several functions inside the Math class that are useful. Among them:
1 Math . abs ( x ); // absolute value of x
Math . max (a , b ); // larger of a and b
3 Math . min (a , b ); // smaller of a and b
Math . sin ( theta ); // sin trig function
5 Math . cos ( theta ); // cos trig function
Math . tan ( theta ); // tangent trig function
7 Math . toRadians ( deg ); // convert deg to radians
Math . toDegrees ( rad ); // convert rad to degrees
9 Math . exp ( x ); // raises e ^ x
Math . log ( x ); // natural logarithm
11 Math . pow (a , b ); // raise a to power of b
Math . sqrt ( a ); // square root of a
13 Math . E ; // value of constant e
Math . PI ; // pi

You might also like