0% found this document useful (0 votes)
6 views21 pages

Java Field Notes

This document provides an overview of Java programming, including the structure of a simple program, variable types, naming conventions, and the use of comments. It explains the concept of classes and objects, as well as the different types of variables such as instance, class, local variables, and parameters. Additionally, it covers primitive data types, initialization, literals, and the String class, along with the concept of enumerated types.

Uploaded by

Joy Sengupta
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)
6 views21 pages

Java Field Notes

This document provides an overview of Java programming, including the structure of a simple program, variable types, naming conventions, and the use of comments. It explains the concept of classes and objects, as well as the different types of variables such as instance, class, local variables, and parameters. Additionally, it covers primitive data types, initialization, literals, and the String class, along with the concept of enumerated types.

Uploaded by

Joy Sengupta
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
You are on page 1/ 21

Java Field Notes

Java's Hello, World!


/** A program to display the message
* "Hello, world!" on the standard output.
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
} // End of class HelloWorld

The command that actually displays the message is System.out.println("Hello,


world!") .
This command is an example of subroutine call statement.
A built-in subroutine is that subroutine which is defined by the program's standard
library or a part of the program and is available to be used readily in different
programs.
Comments:
The first type begins with // and extends to the end of a line. The computer
ignores the // and everything that follows it on the same line.
The second type of comment starts with /* and ends with */ , and it can extend
over more than one line. A comment that actually begins with /** , like this one
does, has special meaning; it is a “Javadoc” comment that can be used to produce
documentation for the program.
All programming in Java is done inside “classes.”
The first line in the above program , the name of the class, also serves as the name of
the program. Not every class is a program.
In order to define a program, a class must include a subroutine named main, with
a definition that takes the form:

public static void main(String[] args) {


<statements>
}

The interpreter calls this main() subroutine, and the statements that it contains are
executed.
The word “public” in the first line of main() means that this routine can be called from
outside the program. This is essential because the main() routine is called by the Java
interpreter, which is something external to the program itself.
A program is defined by a public class that takes the form:

<optional-package-declaration>
<optional-imports>

public class <program-name> {


<optional-variable-declarations-and-subroutines>
public static void main(String[] args) {
<statements>
}
<optional-variable-declarations-and-subroutines>
}

A package is a group of classes.


The <program-name> in the line that begins “public class” is the name of the
program ( <program-name>.java as filename), as well as the name of the class.
When this file is compiled, another file named <program-name>.class will be
produced with the Java bytecode.
Also note that according to the above syntax specification, a program can contain
other subroutines besides main() , as well as things called “variable declarations.”

Variables and Naming Them


Fields, identifiers, and variables, all mean the same thing.
Certain words are reserved (reserved words) for special uses in Java, and cannot be
used as identifiers.
In addition to simple identifiers, things in Java can have compound names which
consist of several simple names separated by periods. (Compound names are also
called qualified names.) Example: System.out.println . A compound name is a kind of
path to an item through one or more levels of containment.

Types of Variables
1. Instance Variables (Non-Static Variables) objects store their individual states in "non-
static fields", that is, fields declared without the static keyword. Non-static fields are
also known as instance variables because their values are unique to each instance of a
class (to each object, in other words); the currentSpeed of one bicycle is independent
from the currentSpeed of another.
2. Class Variables (Static Fields) A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in existence,
regardless of how many times the class has been instantiated. A field defining the
number of gears for a particular kind of bicycle could be marked as static since
conceptually the same number of gears will apply to all instances. The code static int
numGears = 6; would create such a static field. Additionally, the keyword final
could be added to indicate that the number of gears will never change.
3. Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0; ). There is no special keyword
designating a variable as local; that determination comes entirely from the location in
which the variable is declared — which is between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class. TL;DR: Local variables are
variables defined in the local scope of methods.
4. Parameters Similar to other languages, the argument taking variables of methods and
class constructors. The important thing to remember is that parameters are always
classified as "variables" not "fields".
A type's fields, methods, and nested types are collectively called its members.

Naming
Variable names are case-sensitive. Convention is to start with a letter.
Subsequent characters may be letters, digits, dollar signs, or underscore characters.
Convention is to use Pascal case or UpperCamelCase.

Creating Primitive Type Variables


The Java programming language is statically-typed, which means that all variables must
first be declared before they can be used.
A variable in Java is designed to hold only one particular type of data; it can legally hold
that type of data and no other. The compiler will consider it to be a syntax error if one try
to violate this rule by assigning a value of the wrong type to a variable. We say that Java
is a strongly typed language because it enforces this rule.
This involves stating the variable's type and name, eg,

int gear = 1;

A variable's data type determines the values it may contain, plus the operations that may
be performed on it.
Java has 8 primitive types.
A primitive type is predefined by the language and is named by a reserved keyword.
Primitive values do not share state with other primitive values.

The eight primitive data types supported by the Java programming language are:

byte : The byte data type is an 8-bit signed two's complement integer. It has a
minimum value of -128 and a maximum value of 127 (inclusive). The byte data type
can be useful for saving memory in large arrays, where the memory savings actually
matters.
short : The short data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive).
int : By default, the int data type is a 32-bit signed two's complement integer, which
has a minimum value of -231 and a maximum value of 231-1.
long : The long data type is a 64-bit two's complement integer. The signed long has a
minimum value of -263 and a maximum value of 263-1.
float : The float data type is a single-precision 32-bit IEEE 754 floating point. As with
the recommendations for byte and short , use a float (instead of double ) if one
needs to save memory in large arrays of floating point numbers. This data type should
never be used for precise values, such as currency. For that, one will need to use the
java.math.BigDecimal class instead.
double : The double data type is a double-precision 64-bit IEEE 754 floating point. For
decimal values, this data type is generally the default choice. As mentioned above, this
data type should never be used for precise values, such as currency.
boolean : The boolean data type has only two possible values: true and false . Use
this data type for simple flags that track true/false conditions. This data type represents
one bit of information, but its "size" isn't something that's precisely defined.
char : The char data type is a single 16-bit Unicode character. It has a minimum value
of \u0000 (or 0) and a maximum value of \uffff (or 65,535 inclusive).

Other important pointers,

In Java SE 8 and later, int data type can be used to represent an unsigned 32-bit
integer, which has a minimum value of 0 and a maximum value of 232-1. Use the
Integer class to use int data type as an unsigned integer. Same with, long data
type.
Java supports for character strings via the java.lang.String class. Enclosing
character string within double quotes will automatically create a new String object; for
example:

String s = "this is a string";

String objects are immutable, which means that once created, their values cannot
be changed.
The String class is not technically a primitive data type.

Initialising a Variable with a Default Value


It is not always necessary to assign a value when a field is declared. Fields that are declared
but not initialized will be set to a reasonable default by the compiler.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char \u0000

String (or any object) null


boolean false

Local variables are slightly different; the compiler never assigns a default value to an
uninitialized local variable

Literals
A literal is the source code representation of a fixed value; literals are represented directly in
the code without requiring computation. It is possible to assign a literal to a variable of a
primitive type. TL;DR: RHS values are known as literals.

boolean result = true;


char capitalC = 'C'; // Character Literal
byte b = 100; // Integer Literal
float i = 100.80; // Float Literal
String name = "A" // String Literal

\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \"


(double quote), \' (single quote), and \\ (backslash).
There is also a special null literal that can be used as a value for any reference type.
The null literal may be assigned to any variable, except variables of primitive types.
The “e12” and “e-108” represent powers of 10, so that, 1.3e12 means 1.3 times 1012
and 12.3737e-108 means 12.3737 times 10−108 .
Finally, there is also a special kind of literal called a class literal, formed by taking a type
name and appending .class ; for example, String.class . This refers to the object
that represents the type itself, of type Class .

Using underscore characters in numeric literals,


One can place underscores only between digits; one cannot place underscores in the
following places:

At the beginning or end of a number


Adjacent to a decimal point in a floating point literal
Prior to an F or L suffix
In positions where a string of digits is expected

Example,

// Invalid: cannot put underscores


// adjacent to a decimal point
float pi1 = 3_.1415F;
// Invalid: cannot put underscores
// adjacent to a decimal point
float pi2 = 3._1415F;
// Invalid: cannot put underscores
// prior to an L suffix
long socialSecurityNumber1 = 999_99_9999_L;

// OK (decimal literal)
int x1 = 5_2;
// Invalid: cannot put underscores
// At the end of a literal
int x2 = 52_;
// OK (decimal literal)
int x3 = 5_______2;

// Invalid: cannot put underscores


// in the 0x radix prefix
int x4 = 0_x52;
// Invalid: cannot put underscores
// at the beginning of a number
int x5 = 0x_52;
// OK (hexadecimal literal)
int x6 = 0x5_2;
// Invalid: cannot put underscores
// at the end of a number
int x7 = 0x52_;

Variables in Programs
A variable can be used in a program only if it has first been declared .
A variable declaration statement is used to declare one or more variables and to give
them names. When the computer executes a variable declaration, it sets aside memory
for the variable and associates the variable’s name with that memory.
Variable declaration syntax,

<type-name> <variable-name>;
The <variable-name-or-names> can be a single variable name or a list of variable
names separated by commas.
Good programming style is to declare only one variable in a declaration statement,
unless the variables are closely related in some way.

Example,

int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;

Local variables: Variables declared inside a subroutine are called local variables for that
subroutine. They exist only inside the subroutine, while it is running, and are completely
inaccessible from outside.

Subroutines in Java
A subroutine is designed to perform some task. To get that task performed in a program,
one can “call” the subroutine using a subroutine call statement.
Every subroutine is contained either in a class or in an object.
One of the purposes of a class is to group together some variables and subroutines,
which are contained in that class. These variables and subroutines are called static
members of the class.
When a class contains a static variable or subroutine, the name of the class is part of the
full name of the variable or subroutine. For example, the standard class named System
contains a subroutine named exit .

System.exit(0)

Calling System.exit will terminate the program and shut down the Java Virtual
Machine.
Now, any subroutine performs some specific task, but for some subroutines, the task is
to compute or retrieve some data value. Subroutines of this type are called functions.
A function always returns a value.
Finally, subroutines in Java are often referred to as methods. Generally, the term
“method” means a subroutine that is contained in a class or in an object. Since this is
true of every subroutine in Java, every subroutine in Java is a method. The same is not
true for other programming languages.

Classes & Objects


Classes used to describe objects.
In this role, the class is a type, in the same way that int and double are types.
An object is a collection of variables and subroutines and has the type of its "Class".

Enumerated Types
This large collection of types is not sufficient to cover all the possible situations that a
programmer might have to deal with. So, an essential part of Java, just like almost any
other programming language, is the ability to create new types. Enum helps with that.
Technically, enum is a class.
An enum is a type that has a fixed list of possible values, which is specified when the
enum is created.
Definition of enum,

enum <enum-type-name> { <list-of-enum-values> }

Example,

enum Season { SPRING, SUMMER, FALL, WINTER }


Season vacation;
vacation = Season.SUMMER;
System.out.println(vacation)
// SUMMER

An enum value is a constant; that is, it represents a fixed value that cannot be changed.
The possible values of an enum type are usually referred to as enum constants.
Since enum is technically a class, the enum values are technically objects. As objects,
they can contain subroutines. One of the subroutines in every enum value is named
ordinal() - it returns the ordinal number of the value in the list of values of the enum.

System.out.println(vacation.ordinal())
// 1

String & String Literals


Java has other types in addition to the primitive types, but all the other types represent
objects rather than “primitive” data values.
There is one predefined object type that is very important: the type String . (String is a
type, but not a primitive type; it is in fact the name of a class)
Single quotes are used for char literals and double quotes for String literals! There is a
big difference between the String "A" and the char ’A’.
Within a string literal, special characters can be represented using the backslash
notation (mentioned earlier).
Values of type String are objects.
That object contains data, namely the sequence of characters that make up the string. It
also contains subroutines. All of these subroutines are in fact functions.

Operations on String
The String class defines a lot of functions. Assume that s1 and s2 are variables of type
String :

s1.equals(s2) is a function that returns a boolean value. It returns true if s1 consists


of exactly the same sequence of characters as s2 , and returns false otherwise.
s1.equalsIgnoreCase(s2) is another boolean-valued function that checks whether s1
is the same string as s2 , but this function considers upper and lower case letters to be
equivalent. Thus, if s1 is “cat”, then s1.equals("Cat") is false, while
s1.equalsIgnoreCase("Cat") is true.
s1.length() is an integer-valued function that gives the number of characters in s1 .
s1.charAt(N) , where N is an integer, returns a value of type char. It returns the Nth
character in the string. Positions are numbered starting with 0, so s1.charAt(0) is
actually the first character, s1.charAt(1) is the second, and so on. The final position is
s1.length() - 1 . For example, the value of "cat".charAt(1) is ’a’. An error occurs if
the value of the parameter is less than zero or is greater than or equal to s1.length() .
s1.substring(N,M) , where N and M are integers, returns a value of type String. The
returned value consists of the characters of s1 in positions N, N+1,. . . , M-1. Note that
the character in position M is not included. The returned value is called a substring of
s1 . The subroutine s1.substring(N), with just one parameter, returns the substring of s1
consisting of characters starting at position N up until the end of the string.
s1.indexOf(s2) returns an integer. If s2 occurs as a substring of s1 , then the
returned value is the starting position of that substring. Otherwise, the returned value is
-1. One can also use s1.indexOf(ch) to search for a char, ch , in s1 . To find the first
occurrence of x at or after position N , one can use s1.indexOf(x,N) . To find the last
occurrence of x in s1 , use s1.lastIndexOf(x) .
s1.compareTo(s2) is an integer-valued function that compares the two strings. If the
strings are equal, the value returned is zero. If s1 is less than s2 , the value returned is
a number less than zero, and if s1 is greater than s2 , the value returned is some
number greater than zero. There is also a function s1.compareToIgnoreCase(s2) . (If
both of the strings consist entirely of lower case letters, or if they consist entirely of upper
case letters, then “less than” and “greater than” refer to alphabetical order. Otherwise,
the ordering is more complicated; it compares individual characters using their Unicode
code numbers.)
s1.toUpperCase() is a String -valued function that returns a new string that is equal to
s1 , except that any lower case letters in s1 have been converted to upper case. For
example, "Cat".toUpperCase() is the string "CAT". There is also a function
s1.toLowerCase() .
s1.trim() is a String -valued function that returns a new string that is equal to s1
except that any non-printing characters such as spaces and tabs have been trimmed
from the beginning and from the end of the string. Thus, if s1 has the value "fred ", then
s1.trim() is the string "fred", with the spaces at the end removed.

One can also use the plus operator, +, to concatenate two strings.

Text Blocks
Java 17 defines a new kind of string literal that makes it easier to represent multi-line strings.
A text block starts with a string of three double-quote characters, followed by optional white
space and then a new line. The white space and newline are not part of the string constant
that is represented by the text block. The text block is terminated by another string of three
double-quote characters.

String poem = """


As I was walking down the stair,
I met a man who wasn’t there.
He wasn’t there again today.
I wish, I wish he’d go away!""";

Arrays
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed.
Each item in an array is called an element, and each element is accessed by its
numerical index.

Example,

class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;

// allocates memory for 10 integers


anArray = new int[10];

// initialize first element


anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: "


+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}

An array declaration has two components:


The array's type. An array's type is written as type[], where type is the data type of
the contained elements; the brackets are special symbols indicating that this
variable holds an array.The size of the array is not part of its type (which is why the
brackets are empty).
The array's name.
One way to create an array is with the new operator.

// create an array of integers


anArray = new int[10];

Multi-Dimensional Array As an array can hold any reference, and since an array is itself
a reference, one can easily create arrays of arrays.
Array of arrays are also known as a multidimensional array. One can declare them by
using two or more sets of brackets, such as String[][] names.

class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}

One can use the built-in length property defined on any array to determine the size of
this array.

System.out.println(anArray.length);

Copying Arrays The System class has an arraycopy() method that one can use to
efficiently copy data from one array into another:

public static void arraycopy(Object src, int srcPos,


Object dest, int destPos, int length)

The two Object arguments specify the array to copy from and the array to copy to. The
three int arguments specify the starting position in the source array, the starting
position in the destination array, and the number of array elements to copy.

Manipulating Java Arrays

, Java SE provides several methods for performing array manipulations (common tasks,
sch as copying, sorting and searching arrays) in the java.util.Arrays class.
For instance, copying of array can be used with method of the java.util.Arrays
class, as one can see in the ArrayCopyOfDemo example. The difference is that using the
java.util.Arrays method does not require one to create the destination array before
calling the method, because the destination array is returned by the method:

class ArrayCopyOfDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto",
"Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo",
"Macchiato",
"Marocchino", "Ristretto" };

String[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);


for (String coffee : copyTo) {
System.out.print(coffee + " ");
}
}
}

Other useful operations,

Searching an array for a specific value to get the index at which it is placed (the
binarySearch() method).
Comparing two arrays to determine if they are equal or not (the equals() method).
Filling an array to place a specific value at each index (the fill() method).
Sorting an array into ascending order. This can be done either sequentially, using the
sort() method, or concurrently, using the parallelSort() method introduced in Java
SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential
array sorting.
Creating a stream that uses an array as its source (the stream() method). For
example, the following statement prints the contents of the copyTo array in the same
way as in the previous example:

java.util.Arrays.stream(copyTo)
.map(coffee -> coffee + "")
.forEach(System.out::print);

Converting an array to a string. The toString() method converts each element of the
array to a string, separates them with commas, then surrounds them with brackets. For
example, the following statement converts the copyTo array to a string and prints it:

System.out.println(java.util.Arrays.toString(copyTo));
// [Cappuccino, Corretto, Cortado, Doppio, Espresso, Frappucino,
Freddo]

The var Keyword


The var type identifier can be used to declare a local variable. The compiler decide what is
the real type of the variable.
Example,
String message = "Hello world!";
Path path = Path.of("debug.log");
InputStream stream = Files.newInputStream(path);

can be simplified to,

var message = "Hello world!";


var path = Path.of("debug.log");
var stream = Files.newInputStream(path);

Restrictions on var ,

1. Only to be used in local variables declared in methods, constructors and initialiser


blocks.
2. var cannot be used for fields, nor for method or constructor parameters.
3. The compiler must be able to choose a type when the variable is declared. Since null
has no type, the variable must have an initialiser.

Operators

Operators Precedence
postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative * / %

additive + -

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR \|

logical AND &&

logical OR \|

ternary ? :

assignment = += -= *= /= %= &= ^= \|= <<= >>= >>>=

Unary operators demo,


class UnaryDemo {

public static void main(String[] args) {

int result = +1;


// result is now 1
System.out.println(result);

result--;
// result is now 0
System.out.println(result);

result++;
// result is now 1
System.out.println(result);

result = -result;
// result is now -1
System.out.println(result);

boolean success = false;


// false
System.out.println(success);
// true
System.out.println(!success);
}
}

Prefix/Postfix Demo,

class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
Type Comparison,
The instanceof operator compares an object to a specified type. One can use it to test if
an object is an instance of a class, an instance of a subclass, or an instance of a class that
implements a particular interface.
Example,
The following program, InstanceofDemo , defines a parent class (named Parent ), a simple
interface (named MyInterface ), and a child class (named Child ) that inherits from the
parent and implements the interface.

class InstanceofDemo {
public static void main(String[] args) {

Parent obj1 = new Parent();


Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: "


+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

with output,

obj1 instanceof Parent: true


obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

Expressions, Statements and Blocks


An expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language, that evaluates to a
single value.
Statements are roughly equivalent to sentences in natural languages. A statement forms
a complete unit of execution. Expressions can be made into a statement by terminating
the expression with a semicolon ( ; ).
A block is a group of zero or more statements between balanced braces and can be
used anywhere a single statement is allowed.

Control Flow
Same as C/C++, with the addition of, yield statement.

The yield statement exits from the current switch expression it is in. A yield statement
is always followed by an expression that must produce a value. This expression must not be
void . The value of this expression is the value produced by the enclosing switch
expression.

Example,

class Test {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public int calculate(Day d) {


return switch (d) {
case SATURDAY, SUNDAY -> 0;
default -> {
int remainingWorkDays = 5 - d.ordinal();
yield remainingWorkDays;
}
};
}
}

Switch Statements
A switch statement takes a selector variable as an argument and uses the value of this
variable to choose the path that will be executed.
The following primitive types cannot be used for the type of the selector variable:
boolean , long , float , and double .

Example,
int quarter = ...; // any value

String quarterLabel = null;


switch (quarter) {
case 0: quarterLabel = "Q1 - Winter";
break;
case 1: quarterLabel = "Q2 - Spring";
break;
case 2: quarterLabel = "Q3 - Summer";
break;
case 3: quarterLabel = "Q3 - Summer";
break;
default: quarterLabel = "Unknown quarter";
};

All statements after the matching case label are executed in sequence, regardless of
the expression of subsequent case labels, until a break statement is encountered.
The default section handles all values that are not explicitly handled by one of the
case sections.
In Java SE 7 and later, one can use a String object in the switch statement's
expression.
The selector variable of a switch statement can be an object, and this object can be
null.

switch Expressions
Several things have motivated this new syntax.

1. The default control flow behaviour between switch labels is to fall through. This syntax is
error-prone and leads to bugs in applications.
2. The switch block is treated as one block. This may be an impediment in the case
where one need to define a variable only in one particular case .
3. The switch statement is a statement. In the examples of the previous sections, a
variable is given a value in each case . Making it an expression could lead to better and
more readable code.
Example, from,

Day day = ...; // any day


int len = 0;
switch (day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
len = 6;
break;
case TUESDAY:
len = 7;
break;
case THURSDAY:
case SATURDAY:
len = 8;
break;
case WEDNESDAY:
len = 9;
break;
}
System.out.println("len = " + len);

to,

Day day = ...; // any day


int len =
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
System.out.println("len = " + len);

The syntax of switch label is now case L -> . Only the code to the right of the label is
executed if the label is matched. This code may be a single expression, a block, or a throw
statement. Because this code is one block, we can define variables in it that are local to this
particular block.
When using block, return does not work,

// Be careful, this code does NOT compile!


public String convertToLabel(int quarter) {
String quarterLabel =
switch (quarter) {
case 0 -> {
System.out.println("Q1 - Winter");
return "Q1 - Winter";
}
default -> "Unknown quarter";
};
return quarterLabel;
}

Traditionally, the return keyword is used to denote the value produced by a block of
code. Unfortunately this syntax leads to ambiguity in the case of the switch statement.
The block of code executed in the case where quarter is equal to 0 needs to return a
value. It uses the return keyword to denote this value. If one take a close look at this
code, one see that there are two return statements: one in the case block, and
another one in the method block. This is where the ambiguity lies: one may be wondering
what is the semantics of the first return . Does it mean that the program exits the
method with this value? Or does it leave the switch statement? Such ambiguities lead
to poor readability and error-prone code.
A new syntax has been created to solve this ambiguity: the yield statement.

public String convertToLabel(int quarter) {


String quarterLabel =
switch (quarter) {
case 0 -> {
System.out.println("Q1 - Winter");
yield "Q1 - Winter";
}
default -> "Unknown quarter";
};
}
return quarterLabel;
}

So far, switch statements do not accept null selector values. If one try to switch on
a null value one will get a NullPointerException .

Input/Output
Basic Output and Formatted Output
The most basic output function is System.out.print(x) , where x can be a value or
expression of any type. If the parameter, x , is not already a string, it is converted to a
value of type String , and the string is then output to the destination called standard
output.
System.out.println(x) outputs the same text as System.out.print , but it follows
that text by a line feed ( \n ), which means that any subsequent output will be on the
next line.
The function System.out.printf can be used to produce formatted output (like
C/C++).
System.out.printf takes one or more parameters.
The first parameter is a String that specifies the format of the output.
This parameter is called the format string . The remaining parameters specify
the values that are to be output.
System.out.printf("%1.2f", amount);
// Eg output, 5.28

Every format specifier begins with a percent sign (%) and ends with a letter,
possibly with some extra formatting information in between. The letter specifies the
type of output that is to be produced. For example, in %d and %12d , the “d”
specifies that an integer is to be written.
A format specifier such as %15.8e specifies an output in exponential form, with the
“8” telling how many digits to use after the decimal point. If one use “g” instead of
“e”, the output will be in exponential form for very small values and very large
values and in floating-point form for other values. In %1.8g , the 8 gives the total
number of digits in the answer, including both the digits before the decimal point
and the digits after the decimal point.
The “s” stands for “string,” and it can be used for values of type String. It can also
be used for values of other types; in that case the value is converted into a String
value in the usual way
To include an actual percent sign in the output, use the format specifier %% in the
format string.
Use %n to output a line feed.
Can also use a backslash, \ , as usual in strings to output special characters such
as tabs and double quote characters.
For numeric output, the format specifier can include a comma (“,”), which will cause
the digits of the number to be separated into groups, to make it easier to read big
numbers.

System.out.printf("%,d",x);
// 1,000,000,000 (in the United States)

You might also like