Java Comments and Variables PDF

Document Details

AmpleBambooFlute

Uploaded by AmpleBambooFlute

Kirti M. Doongursee College

Tags

java programming java notes comments programming

Summary

These notes provide an introduction to Java programming, covering topics such as comments, variables (including final variables), data types (float and double), printing variables, and basic input from the user. There are multiple example programs, including one calculating a student's information.

Full Transcript

Java Comments Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Single-line Comments Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Jav...

Java Comments Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Single-line Comments Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed). This example uses a single-line comment before a line of code: // This is a comment System.out.println("Hello World"); System.out.println("Hello World"); // This is a comment Java Multi-line Comments Multi-line comments start with. Any text between will be ignored by Java. This example uses a multi-line comment (a comment block) to explain the code: System.out.println("Hello World"); Final Variables If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only): Example: final int myNum = 15; myNum = 20; // will generate an error: cannot assign a value to a final variable Float datatype : A float only holds approximately 6-7 significant digits. If you need more precision, consider using double (64-bit floating point). You must append f to floating point literals (e.g., 5.0f). Without it, Java will treat it as a double by default. float decimalValue = 3.14f; Eg: System.out.println("The float decimal value is: " + decimalValue); Double datatype : The double data type is used for double-precision 64-bit floating point numbers and is the default type for decimal values in Java. You don't need a suffix for double values (although you can still use d or D for clarity, it's optional). Example: double anotherDecimal = 2.71828d; double decimalValue = 3.14159; Key Differences: float: Uses 32 bits for storage, which offers less precision (about 6-7 decimal places). You must append f or F when declaring a float. double: Uses 64 bits for storage and provides more precision (about 15 decimal places). double is generally preferred for most floating-point calculations because of its higher precision, especially for scientific computations. Java Print Variables The println() method is often used to display variables. To combine both text and a variable, use the + character: Example: String name = "John"; System.out.println("Hello " + name); You can also use the + character to add a variable to another variable: String firstName = "John "; String lastName = "Doe"; String fullName = firstName + lastName; System.out.println(fullName); One Value to Multiple Variables : You can also assign the same value to multiple variables in one line: int x, y, z; x = y = z = 50; System.out.println(x + y + z); Program: created a program that stores different data about a college student & print it: // Student data String studentName = "John Doe"; int studentID = 15; int studentAge = 23; float studentFee = 75.25f; char studentGrade = 'B'; // Print variables System.out.println("Student name: " + studentName); System.out.println("Student id: " + studentID); System.out.println("Student age: " + studentAge); System.out.println("Student fee: " + studentFee); System.out.println("Student grade: " + studentGrade); Write java code to Calculate area of rectangle : area = length * width; Print: width, length and area. Java Type Casting Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte Widening Casting Widening casting is done automatically when passing a smaller size type to a larger size type: public class Main { public static void main(String[] args) { int myInt = 9; double myDouble = myInt; // Automatic casting: int to double System.out.println(myInt); // Outputs 9 System.out.println(myDouble); // Outputs 9.0 } } Narrowing Casting Narrowing casting must be done manually by placing the type in parentheses () in front of the value: public class Main { public static void main(String[] args) { double myDouble = 9.78d; int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // Outputs 9.78 System.out.println(myInt); // Outputs 9 } } Take inputs from user In Java, you can take user inputs in several ways, both for strings and numbers. The most commonly used approaches are through the Scanner class, BufferedReader, and Console class. Let’s go over these methods and their use cases, pros, and cons. 1. Using Scanner class The Scanner class is one of the most widely used classes for taking input from the user. It can read different types of data (strings, integers, doubles, etc.) and is very flexible and easy to use. Example for String and Number Inputs: import java.util.Scanner; public class InputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Reading a String System.out.print("Enter a string: "); String str = scanner.nextLine(); System.out.println("You entered: " + str); // Reading an integer System.out.print("Enter an integer: "); int num = scanner.nextInt(); System.out.println("You entered: " + num); // Reading a double System.out.print("Enter a double: "); double d = scanner.nextDouble(); System.out.println("You entered: " + d); scanner.close(); }} Pros: Ease of use: Scanner provides simple methods like nextInt(), nextDouble(), nextLine() for reading different types of inputs. Flexible: It can handle both strings and numbers. Customizable: You can set input delimiters, read entire lines, etc. Cons: Error Handling: It requires manual handling of exceptions when the user enters invalid data types (e.g., entering a string when an integer is expected). Resource Management: Scanner is not always the most efficient, especially when reading large amounts of data. 2. Using BufferedReader class The BufferedReader class is another common method, typically used with InputStreamReader for reading from the console. It reads input as strings, and you need to convert the input to the desired data type manually. Example for String and Number Inputs: import java.io.*; public class InputExample { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Reading a String System.out.print("Enter a string: "); String str = reader.readLine(); System.out.println("You entered: " + str); // Reading an integer System.out.print("Enter an integer: "); int num = Integer.parseInt(reader.readLine()); System.out.println("You entered: " + num); // Reading a double System.out.print("Enter a double: "); double d = Double.parseDouble(reader.readLine()); System.out.println("You entered: " + d); } } Pros: Efficient: BufferedReader is faster than Scanner when handling large amounts of input because it buffers the input, reducing the number of read operations. Can handle large inputs: Well-suited for reading large amounts of data, such as files. Cons: More verbose: Since everything is returned as a String, you need to manually parse it into other types (e.g., Integer.parseInt(), Double.parseDouble()). Less user-friendly: You must handle input parsing manually, which can lead to errors. 3. Using Console class The Console class can also be used to read user input, but it works only when the program is run from the command line or terminal. It is typically used for secure input, like passwords, as it does not display the characters as the user types. Example for String and Number Inputs: public class InputExample { public static void main(String[] args) { // Get the console object Console console = System.console(); if (console == null) { System.out.println("No console available"); return; } // Reading a string String str = console.readLine("Enter a string: "); System.out.println("You entered: " + str); // Reading a number int num = Integer.parseInt(console.readLine("Enter an integer: ")); System.out.println("You entered: " + num); }} Pros: Secure input: Ideal for password inputs since the characters are not echoed back to the console. Simple interface: Similar to Scanner, but does not display the input. Cons: Availability: Console is not available in all environments (e.g., IDEs like Eclipse). It works only in a real terminal/console environment. Limited: It does not support reading large blocks of data like Scanner or BufferedReader. Best Method and Why Best for general use: Scanner is generally the best option for taking user input in most applications because it is simple to use, supports various data types (strings, numbers, etc.), and handles common scenarios well. Best for performance (large input): BufferedReader is faster than Scanner and is ideal for reading large amounts of data. However, it is less convenient as it requires manual conversion of input. Best for secure input (passwords): Console is the go-to choice for secure user input where you need to hide the input, like passwords. But it’s only useful when running the program in a terminal, not in IDEs. Java Conditions and If Statements Java has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed The if Statement Use the if statement to specify a block of Java code to be executed if a condition is true. if (condition) { // block of code to be executed if the condition is true } Example: int x = 20; int y = 18; if (x > y) { System.out.println("x is greater than y"); } The else Statement Use the else statement to specify a block of code to be executed if the condition is false. int time = 20; if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." The else if Statement Use the else if statement to specify a new condition if the first condition is false. if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." Java Short Hand If...Else (Ternary Operator) Syntax variable = (condition) ? expressionTrue : expressionFalse; int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result); Write a program to check if person is old enough to vote, logic voting age >=18. Switch Statements Instead of writing many if..else statements, you can use the switch statement. The switch statement selects one of many code blocks to be executed: Syntax : switch(expression) { case x: // code block break; case y: // code block break; default: // code block } This is how it works: The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. The break and default keywords are optional The break Keyword When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing. Example : uses the weekday number to calculate the weekday name: int day = 4; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; } // Outputs "Thursday" (day 4) The default Keyword The default keyword specifies some code to run if there is no case match: int day = 4; switch (day) { case 6: System.out.println("Today is Saturday"); break; case 7: System.out.println("Today is Sunday"); break; default: System.out.println("Looking forward to the Weekend"); } // Outputs "Looking forward to the Weekend" Java Break You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop. This example stops the loop when i is equal to 4: for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); } Java Continue The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 4: for (int i = 0; i < 10; i++) { if (i == 4) { continue; } System.out.println(i); } Loops Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable. Java While Loop The while loop loops through a block of code as long as a specified condition is true: while (condition) { // code block to be executed } In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5: int i = 0; while (i < 5) { System.out.println(i); i++; } Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end! The Do/While Loop The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. do { // code block to be executed } while (condition); The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: int i = 0; do { System.out.println(i); i++; } while (i < 5); Java For Loop When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop: for (statement 1; statement 2; statement 3) { // code block to be executed } for (int i = 0; i < 5; i++) { System.out.println(i); } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. The example below will print the numbers 0 to 4: for (int i = 0; i < 5; i++) { System.out.println(i); } Java Nested Loops It is also possible to place a loop inside another loop. This is called a nested loop. The "inner loop" will be executed one time for each iteration of the "outer loop": // Outer loop for (int i = 1; i

Use Quizgecko on...
Browser
Browser