Examples for training for the exam Java SE 17 Developer: 1Z0-829. Part 1.
Task 1.1. Basics. Part 1. REPL component.
1. How to see version of Java on your PC?
2. What is java component known as REPL? Decipher abbreviation. How to run help
for it?
3. How to see built-in code, libraries of code that component from point 2
includes.
4. How to write multiple lines of code in component from point 2?
5. How to exit from this component?
6. Explain Java statement. What is a line terminator in Java?
7. Using this component from point 2 display "Hello World".
8. Remake point 7 and demonstrate errors: unclosed string literal, unclosed
character literal.
9. How to cancel you writing in this component and go to the next row?
Solution:
//1
//in CMD windows write
java -version
//2
//JShell is known as a Read-Eval-Print-Loop interactive program (accessible from
//terminal or on the Windows CMD). It allows you to execute Java code. Run in CMD
jshell
//after login to Jshell write:
/help
//3
/list -all
//4
//write { and push the ENTER. You may push ENTER for every new row. To exit push
//CTRL+C or write } and push ENTER
//5
/exit
//6
It is a command (or line of code) to be execute ended by semicolon ";". Semicolon
is a line terminator.
//7
System.out.print("Hello World");
//8
System.out.print("Hello World);
System.out.print('Hello World');
//9
//push CTRL+C
Task 1.2. Basics. Part 2. Variables.
1. What is a keyword? What is about case-sensitive in Java?
2. Demonstrate integer variable with assigned value 1 using Jshell.
3. Where is the variable stored?
4. What is an expression?
5. Assign new value (expression as sum) to variable from point 2 and display this
value to the console without moving to a new line after printing. What is an
error will be if write wrong name of variable?
6. What is a difference in variable declaration in Jshell and normal Java code?
7. Declare variables v1, v2 and v3. v3 must be as sum of v1 and v2. How to
display variables that you created in Jshell?
Solution:
//1
Keyword is a reserved word, that have predefined meaning in Java. All coding is
case-sensitive in Java (keywords required lowercase). For example "int" is a
keyword, "Int" - not.
//2
int myVar = 1;
//3
In random access memory (RAM)
//4
Expression - is a construct, made up of variables, operators, and method
invocations that evaluates to a single value.
//5
//System.out.print(myVarError); //will be error: cannot find symbol
{myVar = 2 + 3;
System.out.print(myVar);}
//6
In Jshell we can redeclare variable with same name. In Java code - not.
//7
int v1 = 10;
int v2 = 20;
int v3 = v1 + v2;
/var
Task 1.3. Basics. Part 3. Types.
1. List eight primitive data types in Java and explain what each data type
stores.
2. Create variables for each type from point 1, assign minimum and maximum
values if it is allowed. Explain wrapper class. Write result.
3. Print any number variable from point 2 concatenated with phrase "Value=" to
console: as single line and as multiple lines. What is the data type of the
message?
Solution:
//1
Whole number: byte, short, int, long.
Real number (floating point or decimal): float, double.
Single character: char.
Boolean value: boolean.
//2
//Wrapper class provides simple operations and some info about primitive data.
//For primitive types wrapper class named as type name with first letter in
//UPPERCASE, for example for "byte" is "Byte" (except "int" is "Integer").
byte varByte = Byte.MIN_VALUE; //-128
byte varByte = Byte.MAX_VALUE; //127
short varShort = Short.MIN_VALUE; //-32768
short varShort = Short.MAX_VALUE; //32767
int varInteger = Integer.MIN_VALUE; //-2147483648
int varInteger = Integer.MAX_VALUE; //2147483647
long varLong = Long.MIN_VALUE; //-9223372036854775808
long varLong = Long.MAX_VALUE; //9223372036854775807
float varFloat = Float.MIN_VALUE; //1.4E-45
float varFloat = Float.MAX_VALUE; //3.4028235E38
double varDouble = Double.MIN_VALUE; //4.9E-324
double varDouble = Double.MAX_VALUE; //1.7976931348623157E308
//= Char.MIN_VALUE; Char.MAX_VALUE; produce Error: cannot find symbol
char varChar = 'a'; //stores only one character
//= Boolean.MIN_VALUE; Boolean.MAX_VALUE produce Error: cannot find symbol
boolean varBoolean; //stores: true or false
//3
System.out.print("Value=" + varByte); //result will be as string
System.out.print(
"Value"
+
varByte
);
Task 1.4. Basics. Part 4. Types.
1. Explain 'overflow' and 'underflow' situations.
2. What is a symbol you cannot put in a numeric literal? How to improve
readability?
3. How many bits occupy types: byte, short, int, long?
4. What is default type for whole numbers in Java?
5. Demonstrate long variable with value 5;
Solution:
//1
//Called "integer wraparound" - when use expression that are not a simple literal
//value. Error not be because Java compiler doesn't attempt evaluate expression
//value. It is valid for byte, short, integer.
int varInt = Integer.MAX_VALUE + 1; //Overflow. Result -2147483648. Error not be.
int varInt = Integer.MIN_VALUE - 1; //Underflow. Result 2147483647. Error not be.
//but error "integer number too large" will be if assign value greater than type
//size. It is not wraparound situation.
int varInt = 2147483648;
//2
//comma not allowed. For readability use underscore. Undescore not allowed at the
//start, end and around ".", for example:
//System.out.println("value=" + _1.2_); System.out.println("value=" + 1_._2);
int varInt = 2_147_483_647;
//3
Byte.SIZE; //byte - 8 bits, short - 16 bits, int - 32 bits, long - 64 bits.
//4
int
//5
long varLong = 5L; //always write L if numeric literal value > Integer.MAX_VALUE
varLong = 2_147_483_647_999_999L;
Task 1.5. Basics. Part 5. Types.
1. In Jshell declare byte variable 'v1' and 'v2' at the same code line. Explain
rules of declaring multiple variables in one statement.
2. Using variables from point 2 demonstrate 'error: incompatible types: possible
lossy conversion from int to byte'. And demonstrate correct declaration.
3. Use variables from point 1 and declare long variable that have value =
10000000000000 multiply on (v1 + v2).
4. What is a default and non-default type for any decimal or real number? Write
their sizes in bits. Which is faster: float or double?
5. Declare integer variable v1 = 7 and v2 = 3. Then divide v1 by v2 and v2 by v1.
When will the error be?
Solution:
//1
//Rules: declare variables with same data type in a single statement; specify
//data type only once (or will be error <identifier> expected).
byte v1 = 1, v2 = 2;
//2
//for calculation with variable Java cannot evaluate value and by default Java
//uses int for result
byte v1 = (v2 * 10); //error
//Correct declaration: use casting (byte) or use literals instead of variables
byte v1 = (byte) (v2 * 10);
byte v1 = (2 * 10);
//3
long l1 = 10000000000000L * (v1 + v2);
//4
double - default, 64-bit. float - non-default, 32-bit. //double is faster
//5
int v1 = 7;
int v2 = 3;
System.out.print(v1 / v2); //error will not be, result = 2
System.out.print(v2 / v1); //result = 0
Task 1.6. Basics. Part 6. Types.
1. Define double variables with values: 5, 1222333444.1. Use different
approaches. Write result.
2. Recreate point 1 using float.
Create two float variables and assign to them variable values from point 1.
3. Demonstrate error: "incompatible types: possible lossy conversion from double
to float". And how do you fix it?
4. Write differences between char and string.
5. Demonstrate error: 1) incompatible types: java.lang.String cannot be converted
to char; 2) unclosed character literal.
6. How much memory does a char occupy?
7. Demonstrate char variable Unicode value for letter 'Q'. And how to use code
from HTML code.
Solution:
//1
double VD = 5; double vD = 5D; double vd = 5d; //result 5.0
//result 1.2223334441E9
double VD = 1222333444.1;
double VDconvert = (double) 1222333444.1;
double vD = 1222333444.1D;
double vd = 1222333444.1d;
//2
float VF = 5; float vF = 5F; float vf = 5f; //result 5.0
//result 1.2223334441E9
float VFconvert = (float) 1222333444.1;
float vF = 1222333444.1F;
float vf = 1222333444.1f;
//3
float f1 = 1.0 / 2f; //error
float f1 = 1 / 2f; float f1 = 1.0f / 2f; float f1 = (float) (1.0 / 2f); //fix
//4
char - holds only one character and literal enclosed in single quotes.
string - may hold multiple characters and literal enclosed in double quotes.
//5
char varChar = "abc"; //error
char varChar = 'aaa'; //error
//6
2 byte
//7
char vQ = '\u0051';
char vHTMLcode = 81; //from website "symbl.cc" use number from HTML code = Q
Task 1.7. Basics. Part 7.
1. What is a string in Java? In one line, write:
- Declare a variable with the concatenated text "ab", "cd";
- Print the text "My value=" followed by the value from that variable and add
at the end dollar sign using unicode number U+0024.
Write the expected result.
2. Redo point 1, but write it in multiple lines. Write the expected result.
3. What will the result be if a string is concatenated with: integer, boolean?
4. What does 'immutable' mean for a string? List the benefits. What is the
mutable alternative?
Solution:
//1
//It is a class that represents a sequence of characters.
//The result will have two rows:
//vS ==> "abcd"
//My value=abcd$$
String vS = "ab" + "cd"; System.out.print("My value=" + vS + "\u0024" + '\u0024');
//2
//The result will have ONE row:
//My value=abcd$$
{
String vS = "ab" + "cd";
System.out.print("My value=" + vS + "\u0024" + '\u0024');
}
//3
String
//4
String variable cannot be changed after creation. If you change or concatenate
some text with this variable then new String will be created automatically. And
the old String will be removed from memory. StringBuilder class is mutable.
Benefits: enhance performance, security and thread safety.
Task 1.8. Basics. Part 8. Operators.
1. What is an operator? Write the operator precedence from highest (higher
precedence) to lowest.
2. What is an operand? Write an example of expression with 2 operands and 1
operator.
Solution:
//1
//Operators are special symbols that perform specific operations on one, two, or
//three operands, and then return a result.
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 = += -= *= /= %= &= ^= |= <<= >>= >>>=
//2
//Operand - object (value, variable) that is manipulated by an operator.
int my_int = 1 + 2; //1 and 2 are operands. + is the operator. Expression: 1 + 2.
Task 1.9. Basics. Part 9. Operators.
1. Declare two char variables with values 'a' and 'b', and print the result of
their concatenation.
2. Write the alternative names for the remainder operator and demonstrate example
(write result).
3. Declare an integer variable v1 with a value of 5. Then, demonstrate 3 ways of
incrementing and decrementing it by 1. Provide in comments an alternative names
of these operators.
4. Remake point 3 and demonstrate one operation that subtract 3.5 from variable.
Explain result.
5. Demonstrate the shorthand operators for multiplication and division.
Solution:
//1
char v1 = 'a'; char v2 = 'b';
//The result will be 195 because, for char variables, the numbers in memory are
//added, not the character values. It means for char: + is addition, - is
//subtraction, * is multiplication, / is division.
System.out.print(v1 + v2);
System.out.print("" + v1 + v2); //alternative result = ab
//2
//names: leftover, modulus, modulo, mod.
int v1 = 10%3; // 1
//3
//incrementing
int v1 = 5;
v1 = v1 + 1;
v1++; //post-fix increment operator
v1 += 1; //addition compound assignment
System.out.print(v1);
//decrementing
int v1 = 5;
v1 = v1 - 1;
v1--; //post-fix decrement operator
v1 -= 1; //subtraction compound assignment
System.out.print(v1);
//4
// 5 - 3.5 = 1.5, but Java cannot automatically convert fractional part of a
//double to an integer. Instead, Java truncates value: 1.5 to 1.
//Result will be 1.
int v1 = 5;
v1 -= 3.5; //or the same as: v1 = (int) (v1 - 3.5);
//5
int v1 = 10;
v1 *= 2;
v1 /= 2;
Task 1.10. Basics. Part 10. Short questions.
What will the result be in JShell after execution?
1. int myInt = "1";
2. String s1 = "ab"; int i1 = 1; s1 = s1 + i1;
3. How many operators are in this example: int my_int = 1 + 2; ?
4. int v1 = 10/3;
5. {
int v1 = 1;
}
6. {
int v1 = 5;
v1 -= 1;
System.out.print(v1);
System.out.print(v1);
}
7. int v1 = 5; v1 = v1 + 1; v1++;
8. int v1 = 5; v1 = v1 + 1; v1 -= 1;
Solution:
//1
Error: incompatible types: java.lang.String cannot be converted to int
//2
s1 ==> "ab1"
//3
2 operators: = and +
//4
3
//5
nothing
//6
44
//7
5
6
6
//8
5
6
5
Task 2.1. Working with Java in IDE. Part 1. First program.
1. What is used as an SDK in Java?
2. Create the public class MyClass with method (called "main") that prints
'Hello' at first line and 'User' at second line, but return nothing.
Execute and explain result. Explain: public; part of class; main method.
3. Write the shothand of the method from point 2.
Solution:
//1
JDK (Java Development Kit) is used as a Software Development Kit (SDK).
//2
//Clicking on 'src' folder creates a class file MyClass.java, paste code in here
//Result:
//Hello
//User
//Process finished with exit code 0
public class MyClass {
public static void main(String[] args) {
//method body (or also code inside {} called code block)
System.out.println("Hello");
System.out.print("User");
}
}
//'public' - access modifier, define who can access to this code. Public can be
//accessed from any other classes.
//Part of class is the class body (class code block) which is located inside {}.
//The main method is the entry point that Java looks for first to execute the
//program.
//3
psvm
Task 2.2. Working with Java in IDE. Part 2. If-then.
1. Write an example where you declare (by two ways) integer variables: v0 = 0,
v1 = 1, v2 = 2, v3 = 3, v4.
Then, using 'if-then' demonstrate:
- if v0 = v1 and v0 = 0, print 1;
- if v0 equal v2 or equal v3, print 23;
- if v0 not equal v4, print "not equal";
otherwise, print "nothing" on the first line and "found" on the second line.
Which condition will be executed?
2. How many conditions can be tested in an if-then statement, excluding the first
'if'?
Solution:
//1
public class MyClass {
public static void main(String[] args) {
int v0 = 0, v1 = 1, v2 = 2;
int v3 = 3;
int v4 = 4; //v4 must be initialized
if (v0 == v1 && v0 == 0)
System.out.println("1");
else if ((v0 == v2) || (v0 == v3))
System.out.println("23");
else if (v0 != v4)
//this condition will be executed
System.out.println("not equal");
else {
System.out.println("nothing");
System.out.println("found");
}
}
}
//2
unlimited
Task 2.3. Working with Java in IDE. Part 3. If-then and other conditional operators.
1. Write an example with a boolean variable called boo. Assign the value true to
boo and use an if-then statement to print 'TRUE' if boo is true (in two ways),
and print 'false' if boo is false (in 3 ways).
2. Declare integer variable v1 with value 10, and string varible vRes.
Demonstrate an example with an operator that has three operands. What other
built-in operators have three operands?
Solution:
//1
public class MyClass {
public static void main(String[] args) {
boolean boo;
if (boo = true){
System.out.println("TRUE1");
}
else if (boo){
System.out.println("TRUE2");
}
else if (boo == false){
System.out.println("false1");
}
else if (boo != true){
System.out.println(boo);
}
// exclamation mark (!) is the NOT operator (logical complement operator)
else if (!boo){
System.out.println("false2");
}
}
}
//2
//Ternary conditional operator. Only this built-in operator has three operands.
public class MyClass {
public static void main(String[] args) {
int v1 = 10;
String vRes;
vRes = v1 == 100 ? "is 100" : "not is 100";
System.out.println(vRes);
}
}
Task 2.4. Working with Java in IDE. Part 4. Methods.
1. What is a method in Java?
2. List and explain six method components.
3. What is a method signature?
4. How to declare a method within another method in Java?
Solution:
//1
A method is an executable block of code that performs a certain action and may
have parameters.
//2
"Modifier" - such as public, private, and others.
"The return type" - the data type of the value returned by the method, or void if
the method does not return a value.
"The method name" - method name according to Java rules.
"The parameter list in parenthesis" - a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses () (empty parenthesis if
have not parameters).
"An exception list" - list of exceptions that a method can throw.
"The method body, enclosed between braces" - the method's code, including the
declaration of local variables, goes here.
//3
Method signature - the method's name + combination of number of parameters, their
types and parameter order. Return type is not included in the signature.
//4
Can't declare a method inside another method.
Task 2.5. Working with Java in IDE. Part 5. Methods.
1. In the class "myClass" create two public methods that returns nothing called:
"myMethod" with an integer parameter and "main". "main" method must have
integer variable vInt with value 15 and if vInt > 10,
then call "myMethod" and in here multiply value from vInt on 2 and print result.
After that in "main" method print value of vInt. Explain result.
2. How many parameters are allowed in a method?
3. What is the difference between a method parameter and a method argument?
4. Explain positional notation and named notation in Java methods.
5. Explain how to use a default value for a method parameter.
Solution:
//1
//result: 30, 15
public class MyClass {
public static void main(String[] args) {
int vInt = 15;
if (vInt > 10) {
myMethod(vInt);
}
System.out.println(vInt);
}
public static void myMethod(int pInt) {
//A variable name cannot be the same as a parameter name
//int pInt;
System.out.println(pInt * 2);
return; //it means return nothing; you may not need to write it
}
}
//2
have no limit
//3
When you declare variables in method parameters, they are called parameters.
When you pass values to these parameters, those values are called arguments.
//4
Java uses positional notation. Named notation is not supported.
//5
default values not supported for parameters
Task 2.6. Working with Java in IDE. Part 6. Methods.
1. What can be a return type in a method?
2. In the class "myClass" create two public methods that return an integer:
"myMethod", which takes an integer parameter, and "myA". "myA" method must have
integer variable vInt with a value from argument (for example 15). If vInt > 10,
then call "myMethod" passing the vInt and in here multiply the passed value by 2
and return the result. After that, in the "myA" method, multiply the result
of "myMethod" by 5 and display the new result.
Solution:
//1
Return type can be: primitive data types, reference data types (objects), class
or interface, void (no return, i.e. do not write "return void" or write "return"
or write nothing).
//2
public class MyClass {
public static void main(String[] args) {
int res;
res = myA(15); //result=150
//myA(15);
}
public static int myA(int p1) {
int vInt = p1;
if (vInt > 10) {
vInt = myMethod(vInt);
}
vInt = vInt * 5;
System.out.println(vInt);
return vInt;
}
public static int myMethod(int p2) {
return p2 * 2;
}
}
Task 2.7. Working with Java in IDE. Part 7. Methods.
1. What is an overloading methods?
2. Demonstrate overloading methods that return a boolean. Create a method called
"result" that calls the overloaded methods and returns:
- TRUE if at least one method returns TRUE;
- FALSE if at least one method returns FALSE;
- TRUE if all methods return TRUE.
Also, demonstrate the simulation of a default value for a parameter.
Solution:
//1
Overloading methods - means that methods within a class can have the same name
if they have different number, order, or types of parameters.
//2
public class MyClass {
public static void main(String[] args) {
boolean boo = result();
System.out.print(boo);
}
public static boolean result() {
boolean res;
//FALSE if all methods or at least one method returns FALSE
//TRUE if all methods returns TRUE
res = myMethod(1) &&
myMethod(1, "one") &&
myMethod("one", 1) &&
myMethod("default");
//TRUE if at least one method returns TRUE
res = myMethod(1) ||
myMethod(1, "one") ||
myMethod("one", 1) ||
myMethod("default");
return res;
}
//different number of parameters
public static boolean myMethod(int p1) {
return true;
}
public static boolean myMethod(int p1, String p2) {
return true;
}
//different order of parameters
public static boolean myMethod(String p2, int p1) {
return true;
}
//different types of parameters
//if the method is called with only a String argument, simulate a call with
//0 as the second parameter
public static boolean myMethod(String p1) {
return myMethod(p1, 0);
}
}
Task 2.8. Working with Java in IDE. Part 8. Methods.
1. Declare two constants: cA with value 'AA' and cB with value 'BB'. Then display
the result of their concatenation as 'AABB'.
2. Explain enum type: what is it extend, usage, case, what is it can include.
Demonstrate enum type En with constructor and display values.
Solution:
//1
public class MyClass {
private static final String cA = "AA";
private static final String cB = "BB";
public static void main(String[] args) {
System.out.println(cA + cB);
}
}
//2
//The enum implicitly extend java.lang.Enum class. An enum type is a data type
//that enables for a variable to be a set of predefined uppercase constants in
//order as you write. Enum body can include methods and fields.
public class MyClass {
public enum En {
FIRST(1, "one"), SECOND(2, "two");
private final int num;
private final String text;
En(int num, String text) {
this.num = num;
this.text = text;
}
}
public static void main(String[] args) {
System.out.println(En.FIRST.num + En.FIRST.text
+ En.SECOND.num + En.SECOND.text);
}
}
Task 2.9. Working with Java in IDE. Part 9. Methods. Short questions.
What will the result be in the IDE after execution?
1. public class MyClass {
public static void main() {
System.out.print("Hello");
}
}
2. public class MyClass {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print("World");
}
}
3. public class MyClass {
public static void main(String[] args) {
boolean boo = false;
if (boo != true){
System.out.println(boo + 1);
}
}
}
4. double v1 = D20;
5. public class MyClass {
public static void main(String[] args) {
boolean boo = false;
if (boo != true){
boolean boo = true;
System.out.println(boo);
}
}
}
Solution:
//1
Error. Define the main method as: public static void main(String[] args)
//2
HelloWorld
//3
error: java: bad operand types for binary operator '+'
//4
error
//5
error. java: variable boo is already defined in method main
Task 2.10. Working with Java in IDE. Part 10. Methods. Short questions.
What will the result be in the IDE after execution?
1. public class MyClass {
public static void myMethod(int pInt) {
int pInt = 10;
System.out.println(pInt * 2);
}
}
2. public class MyClass {
System.out.println("1" + "2");
}
3. public class MyClass {
public static int main(int p1) {
int vInt = 15;
if (vInt > 10) {
vInt = myMethod(vInt);
}
System.out.println(vInt);
return 1;
}
public static int myMethod(int p2) {
return p2 * 2;
}
}
4. public class MyClass {
public static void main(String[] args) {
System.out.println("Hello");
return void;
}
}
5. public class MyClass {
public static void main(String[] args) {
int vInt = 15;
if (vInt > 10) {
myMethod(vInt);
}
System.out.println(vInt);
}
public static int myMethod(int pInt) {
System.out.println(pInt * 2);
return;
}
}
Solution:
//1
error. java: variable pInt is already defined in method myMethod(int)
//2
error. java: <identifier> expected
//3
error. please define the main method as: public static void main(String[] args)
//4
error. java: illegal start of expression
//5
error. java: incompatible types: missing return value
Task 2.11. Working with Java in IDE. Part 11. Methods. Short questions.
What will the result be in the IDE after execution?
1. public class MyClass {
public static void main(String[] args) {
displayHighScorePosition("Hello", 100);
}
public static void displayHighScorePosition(string p1, int p2) {
System.out.println(p2 + p1);
}
}
2. public class MyClass {
public static void main(String[] args) {
System.out.println(Test(120));
}
public static String Test(int quantity) {
if (quantity <= 0) {
System.out.println("quantity <= 0");
return;
}
}
}
3. public class MyClass{
public static void main(String[] args) {
private static final String cA = "AA";
private static final String cB = "BB";
System.out.println(cA + cB);
}
}
4. public class MyClass {
public static void myMethod(int a, int b, int c){
if (a < 0) {
System.out.println("TRUE");
}
else if ((a == b) == c) {
System.out.println("TRUE");
}
else if (c != a){
System.out.println("FALSE");
}
}
}
Solution:
//1
error. java: cannot find symbol
//2
error. java: incompatible types: missing return value
//3
error: java: illegal start of expression
//4
error: java: incomparable types: boolean and int
Task 2.12. Working with Java in IDE. Part 12. Methods. switch.
1. In class MyClass declare integer variable vInt with value 3 and demonstrate
not enhanced switch statement. In comments list supported types. Explain
fall-through.
2. Remake point 1 and demonstrate switch expression. Two ways.
Solution:
//1
//Support types: byte, short, char, int, enum, String, Character, Byte,
//Short, Integer.
public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String res = "";
switch (vInt) {
case 1: case 2:
res = res + "one or two";
break;
//case 3: //duplicate case label NOT ALLOWED
case 3:
System.out.println("some code");
res = res + "three";
break;
default:
res = res + "not_found";
break; //optional, but recommended
}
//Fall-through means that if not write break in case section and case is
//found, then all next case and default sections will be executed until
//find break or end of switch statement.
System.out.println(res);
}
}
//2
public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String example = "";
//1 way
String res = switch (vInt) {
case 1, 2 -> {
example = "two";
yield "one " + "or " + example;
}
case 3 -> "three";
default -> "not_found"; //default is MANDATORY IN SWITCH EXPRESSION
};
//2 way
res = switch (vInt) {
case 1:
case 2:
yield "one or two";
case 3:
System.out.println("some code");
yield "three";
default:
yield "not_found";
};
System.out.println(res);
}
}
Task 2.13. Working with Java in IDE. Part 13. Methods. Loops.
1. Define x = 0, then write a WHILE loop, where add 1 to x on each step of cycle,
then stop cycle when x = 3.
2. Usint int loop counter write a FOR loop from 1 to 5, write a FOR loop from 5
to 1.
3. Define y = 0, then write a DO WHILE loop, where add 1 to y on each step of
cycle. Stop loop when y >= 3. Explain difference with WHILE loop.
4. Write FOR loop from 1 to 4 with label 'loop1'. Then inside 'loop1' write
nested loop FOR from 1 to current step of 'loop1' with label 'loop2' where
must be condition: if 'loop1' equal 3 then stop 'loop1'.
5. Make FOR loop from 1 to 4 where display all steps, but simulate step = 0.5 and
if step = 1,5 then go to next step (also do not display step = 1,5). Explain it.
6. Demonstrate and explain situation when we use FOR loop with counter name equal
variable name default 5.
7. Demonstrate GOTO statement (include nested block), write restrictions.
Solution:
public class MyClass {
public static void main(String[] args) {
//1
int x = 0;
while (x < 3) {
x = x + 1;
System.out.println(x);
}
//2
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
//3
int y = 0;
do { //DO WHILE body runs at least once, even if the condition is false
System.out.println(y);
y = y + 1;
}
while (y < 3);
//4
loop1:
for (int i = 1; i <= 4; i++) {
loop2:
//loop2: //label duplicate not allowed
for (int j = 1; j <= i; j++) {
if (i == 3) {
break loop1;
}
System.out.println("i=" + i);
System.out.println(" j=" + j);
}
}
//5
for (double i = 1; i <= 4; i += 0.25) {
if (i == 1.5) { //In this loop all actions on the step =1.5
continue; //after continue will not be performed
}
System.out.println(i);
}
//6
int a = 5;
//for (int a = 1; a <= 5; a++) { //will be error
for (int b = 1; b <= a; b++) {
System.out.println(b);
}
//7
//Java does not support goto. It is just a reserved keyword.
}
}
Task 2.14. Working with Java in IDE. Part 14. Methods. Short questions.
What will the result be in the IDE after execution?
1. public class MyClass {
public enum En {
FIRST(1, "one"), SECOND(2, "two");
En(int num, String text) {
this.num = num;
this.text = text;
}
}
}
2. public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String res;
switch (vInt) {
case 1: case 2:
res = "one or two";
break;
case null:
res = "three";
break;
}
}
}
3. public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String res = "";
switch (vInt) {
case 1: case 2:
res = res + "one or two";
case 3:
res = res + "three";
default:
res = res + "not_found";
}
System.out.println(res);
}
}
4. public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String res = "";
switch (vInt) {
case 1: case 2:
res = res + "one or two";
case 3:
res = res + "three";
case 4:
res = res + "three";
break;
default:
res = res + "not_found";
}
System.out.println(res);
}
}
Solution:
//1
Error. java: cannot find symbol symbol: variable num
//2
java: incompatible types: <nulltype> cannot be converted to int
//3
threenot_found
//4
threethree
Task 2.15. Working with Java in IDE. Part 15. Methods. Short questions.
What will the result be in the IDE after execution?
1. public class MyClass {
public static void main(String[] args) {
int vInt = 3;
String res = switch (vInt) {
case 1, 2 -> "one or two";
case 3 -> "three";
default -> "not_found";
}
System.out.println(res);
}
}
2. public class MyClass {
public static void main(String[] args) {
int cnt = 3;
for (int cnt = 1; cnt <= 3; cnt++) {
System.out.println(cnt);
}
}
}
3. public class MyClass {
public static void main(String[] args) {
int a = 1;
for (int b = a; b <= 3; b++) {
System.out.println(a);
}
}
}
4. public class MyClass {
public static void main(String[] args) {
int cnt = 1;
for (int a = cnt; a <= 5; cnt++) {
System.out.println(cnt);
}
}
}
Solution:
//1
8:10 java: ';' expected
//2
Error. variable cnt is already defined in method main
//3
1 1 1
//4
infinite loop