CSE 215lab - 1 (Ii)
CSE 215lab - 1 (Ii)
Objective:
• Printing Text
• Data Types / Variables,
• Type Casting
• Printing Data,
• User Input, Operators,
• Conditional Statements,
• Switch
Printing Text:
System.out.print("Hello World!");
• Primitive data types - byte, short, int, long, float, double, Boolean and char
• Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -
> char -> int -> long -> float -> double
int myInt = 9;
The same is true for most other types of variables (at least the primitive datatypes).
Program 1: Taking an integer as user input and printing the obtained value out to the console
The above program has a lot going on. Let’s break it down:
Line 1: We import the built-in Scanner class from java.util package. There are a lot
of modules built into Java, similar to header files in the C programming language. Think of this as
analogous to importing a header file in C programming language.
Line 5: This will become clearer when we cover Object Oriented Programming concepts.
However, the main thing to know here is that we are instantiating an object which is of type
Scanner. This will enable us to access the methods available to the Scanner class.
Line 7: We print out a prompt for the user so that s/he can type an input integer.
Line 8: We use one of the methods of the Scanner class, nextInt() , to obtain the next
To take various variables as input, you need to use the appropriate methods for it. Table 1
summarizes the appropriate methods.
Integer/int nextInt()
Double/double nextDouble()
Float/float nextFloat()
Boolean/boolean nextBoolean()
Table 1: Data Types and their corresponding method in Scanner class for user input.
Boolean Expressions:
Boolean Expressions are formed using boolean operators and boolean values comparison operators.
== Equal to ! NOT
Standard conditional statement Useful if your code turns out to have multiple
“else if” clauses with equal to comparison
Task:
1. Write a program that takes an integer and determines if it’s odd or even. Use switch cases to produce
result.
2. Write a program that takes an integer and determines if it’s prime or not. A number is prime if it is
divisible by 1 and itself only, i.e. 2, 3, 11, 37 etc.
4. Take a year as user input. Then print it check if it’s a leap year or not.
Note: A leap year must satisfy any or both of the following conditions:
Divisible by 400
Divisible by 4 and not divisible by 100
Sample output:
2015: false