0% found this document useful (0 votes)
1K views

Java Quick Reference Guide

This document provides a quick reference guide for Java programming concepts. It defines common Java operators, data types, input/output methods, conditional and loop structures, arrays, and methods. Key points covered include the different forms of if/else statements, for and while loop syntax, primitive vs. reference types, and how to create and access array elements.

Uploaded by

kaz92
Copyright
© Attribution Non-Commercial (BY-NC)
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)
1K views

Java Quick Reference Guide

This document provides a quick reference guide for Java programming concepts. It defines common Java operators, data types, input/output methods, conditional and loop structures, arrays, and methods. Key points covered include the different forms of if/else statements, for and while loop syntax, primitive vs. reference types, and how to create and access array elements.

Uploaded by

kaz92
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 2

Java Quick Reference Guide

Arithmetic Operators + Addition Subtraction / Division (int / floating-point) 2/3 = 0, 2.0/3.0 =.666667 * Multiplication % Modulus (integer remainder) Relational Operators < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to != Not equal to Logical Operators ! NOT && AND || OR Assignment Operators = simple assignment += addition/assignment -= subtraction/assignment *= multiplication/assignment /= division/assignment %= modulus/assignment

Last Update: Friday, February 8, 2013


Forms of the if Statement Simple if
if (expression) statement;

Remember to use the methods equals( ) or compareTo( ) when comparing Strings rather than relational comparison operators. String s1 = "abc", s2 = "def"; String Comparisons: Compare for equality: s1.equals(s2) or s1.compareTo(s2) == 0 Remember the compareTo( ) method returns one of 3 values: neg number, pos number, 0 Compare for lexical order: s1.compareTo(s2) < 0 (s1 before s2) s1.compareTo(s2) > 0 (s1 after s2) Remember to distinguish between integers and real numbers (called floating-point in Java). These are stored differently in memory and have different ranges of values that may be stored. integers: floating-point: 2, 3, -5, 0, 8 2.0, 0.5, -3., 4.653

Example
if (x < y) x++;

if/else
if (expression) statement; else statement;

Example
if (x < y) x++; else x--;

The "expression" in the parentheses for an if statement or loop is often also referred to as a "condition"

if/else if (nested if)


if (expression) statement; else if (expression) statement; else statement;

Example
if (x < y) x++; else if (x < z) x--; else y++;

To conditionally execute more than one statement, you must create a compound statement (block) by enclosing the statements in braces ( this is true for loops as well ): Form
if (expression) { statement; statement; }

Example
if (x < y) { x++; System.out.println( x ); }

Increment/Decrement ( used in prefix and postfix modes ) ++ Increment prefix - inc(dec) variable, use in larger expression -Decrement postfix - use in larger expression, inc(dec) variable Object Creation: ( new ) new int[ 10 ], new GradeBook("CIS 182") The new operator creates an object and returns a reference (address of an object) Java Types [value/reference ] A value type stores a value of a primitive type int x = 3; A reference type stores the address of an object Circle c = new Circle(2); A reference variable is created using a class name: GradeBook myGradeBook; Primitive Data Types ( Java value types ) Remember: String is a reference type boolean flag / logical true. false [ boolean literals ] char character 'A', 'n', '!' [ char literals ] byte, short, int, long integral 2, 3, 5000, 0 [ int literals ] float, double floating-point 123.456, .93 [ double literals ] Default numeric literal types: integral: int floating-point: double int x = 3; double y = 2.5; //3 is an int literal //2.5 is a double literal

Input using Scanner class Scanner input = new Scanner ( System.in ); //keyboard input input methods: next(), nextLine(), nextInt(), nextDouble() Output methods for System.out or PrintWriter objects print(), println(), printf() [formatted output] Input/Output using JOptionPane class [ package javax.swing ] String numString; int num; numString = JOptionPane.showInputDialog("Enter a number"); num = Integer.parseInt(numString); JOptionPane.showMessageDialog(null, "Number is " + num); Conversion from a String to a number using Wrapper Classes
double d = Double.parseDouble(dString); float f = Float.parseFloat(fString); int j = Integer.parseInt(jString);

The switch/case Construct ( break and default are optional ) Form: switch (expression) { case int-constant : statement(s); [ break; ] case int-constant : statement(s); [ break; ] [ default : statement; ] } } Example: switch (choice) { case 0 : System.out.println( You selected 0. ); break; case 1: System.out.println( You selected 1. ); break; default : System.out.println( You did not select 0 or 1. );

Java formatted output [ printf( ) and String.format( ) methods ] 3 components: format string and optionally: format-specifiers ( fs ) and an argument list ( al ) fs: " ... % [flags] [width] [precision] format-specifier ... " al: comma separated list of expressions Format-specifiers: s (string), d (integer), f (floating-point) Example: System.out.printf("Total is %,10.2f\n", total); Java Numeric Conversions: Widening conversions are done implicitly. double x; int y = 100; x = y; // value of y implicitly converted to a double. Narrowing conversions must be done explicitly using a cast. double x = 100; int y; y = (int) x; // value of x explicitly cast to an int In mixed expressions, numeric conversion happens implicitly. double is the highest data type, byte is the lowest.

The "expression" and int-constant are usually type int or char. Java SE 7 adds the ability to use of a . Use the break keyword to exit the structure (avoid falling through other cases). Use the default keyword to provide a default case if none of the case expressions match (similar to trailing else in an if-else-if statement).

Java Quick Reference Guide


The while Loop ( pre-test loop ) Form:
init; while (test) { statement; update; }

Last Update: Friday, February 8, 2013

The for Loop ( pre-test loop ) Form:


for (init; test; update) statement; for (init; test; update) { statement; statement; }

Example:
x = 0; while (x < 10) { sum += x; x++; }

Example:
for (count=0; count<10; count++) System.out.println ( count ); for (int count=1; count<=10; count++) { System.out.print( Count is " ); System.out.println( count );

} Operator Precedence
'\n' '\t' '\"' '\'' '\\' ( ) ---------*, /, % ---------+, -

The do-while Loop ( post-test loop ) Form:


init; do { statement; update; } while (test);

Example:
x = 0; do { sum += x; x++; } while (x < 10);

Escape Sequences Special characters in Java


\n \t \" \' \\

newline character tab character double quote single quote backslash

[ mathematical ]

Logical operators: !, &&, || (1) mathematical (2) relational (3) logical

Selection and Loop Structures Selection: Unary or single selection Binary or dual selection Case structure possible when branching on a variable Simple selection One condition Compound selection Multiple conditions joined with AND / OR operators Looping: Java Pre-test loops Test precedes loop body while for Java Post-test loop Test follows loop body do-while Loop Control: 3 types of expressions that are used to control loops: initialization ( init ) test update Counter-controlled loops, aka definite loops, work with a loop control variable (lcv) Sentinel-controlled loops, aka indefinite loops, work with a sentinel value Java Loop Early Exit: break statement Note: The break statement can be used with a switch statement or a loop in Java. Loops may also use a continue statement.

Java Arrays:

Create an array ( 2 ways )

1. <type> <array-name>[ ] = new <type>[size]; 2. <type> <array-name>[ ] = { <initializer-list> };

Use the ArrayList class to create a dynamically resizable array. The Arrays class has static methods that can be used with arrays and ArrayLists to search, sort, copy, compare for equality, etc. int num[ ]; <stmts> . Create a new initialized array and assign to num. num =new int[ ]{1.2.3.4.5};

//create an array of 20 elements.


int myArray[ ] = new int[20];

//create an array of 3 elements set to the values in the initializer list.


int myArray[ ] = { 1, 2, 3 }; String stooges[ ] = { "Moe", "Larry", "Curly" };

//assign value of first element in myArray to the integer variable x.


int x = myArray[0];

//assign value of the last element in myArray to the integer variable y.


int y = myArray[ myArray.length-1 ];

All arrays have a public field named length which holds the number of elements in the array. Given this declaration: int x[][][]; x.length x[m].length x[m][n].length is the number of elements in the array in the first dimension. is the number of elements for a specific array in the second dimension. is the number of elements for a specific array in the third dimension.

Java Methods: <type> <method-name> ( [ <type> parameter1, [ <type parameter2, ] ] ) Simple procedural programs in Java will contain the static keyword and may also contain the keyword public. Methods that will not return a value will have the return type void in the method header. public static void printHeadings( ) //no parameters, return type is void { <method body> } static void printDetailLine( String name, int number, double gpa ) //3 parameters, return type is void { <method body> } Math.PI 3.141592635 int getCount( ) //no parameters, return type is int { <method body> } public double max( double x, double y ) //2 parameters, return type is double { <method body> } When a method is called, the data is passed to the parameters (if any) using arguments //Arguments: "Jack Wilson", 100, 3.50 passed to Parameters: name, number, gpa for Method: printDetailLine (see method header above) : printDetailLine( "Jack Wilson", 100, 3.50); A method may be declared with one variable length parameter. It must be the last parameter declared. The syntax of the declaration is <type>... <parameter-name>. Examples: int... numbers, double... values, String... names
//implicit array creation

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy