Introduction to programming concepts Assessment Zone
Assessment zone Qno . 1. Source code is programming statements that are created by a programmer and saved in a file. Machine code a set of various instructions that a machine can read and understand directly. Qno 2. Qno 3. A procedural programming language is one that uses sets of functions and commands to complete actions. Object-oriented programming is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields, and code in the form of procedures. Compiler Interpreter A compiler translates code from a high-level programming language into machine code before the program runs. An interpreter translates code written in a high-level programming language into machine code line-by-line as the code runs.
Assessment zone Qno . 4. Java is called Platform Independent because programs written in Java can be run on multiple platforms that has a Java Virtual Machine (JVM) installed. We need not re-write them individually for any particular platform .
Introduction to JAVA Keypoints
Features in Java The primary objective of Java programming language creation was to make it portable, simple and secure programming language . Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords. Simple Object-Oriented Portable Platform independent Secured Robust
Features in Java Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. Object-Oriented Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
Features in Java Platform independent Java is a write once, run anywhere language. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms Secured Java is best known for its security. With Java, we can develop virus-free systems.
Features in Java Robust Java is robust because: It uses strong memory management. Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Java Virtual Machine JVM is an engine, which works as a runtime environment for Java code. JVM converts the java code into machine language. When you run a compiled .class file, it goes to JVM, and then JVM returns the output. Basic tasks for a Java Virtual Machine consist of Loading the code, then verifying the code, and executing the code. Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code
Java Editors
Structure of Java Program
JAVA Fundamentals Keypoints
Java Character set Character set is a set of valid characters that a language can recognize. Java has the following character set: Letters: – A-Z, a-z Digits: – 0-9 Special symbols: – Special symbol available over keyboard. White spaces: – blank space, tab, carriage return, new line, form feed Other characters: - All ASCII & Unicode characters ASCII is a character encoding system that only includes up to 256 characters, primarily composed of English letters, numbers, and symbols. Unicode is a much larger encoding standard that includes over 149,000 characters.
Keywords Words that convey a special meaning to the language complier/interpreter.
Identifiers Names used to identify a variable, function, class, module, or other object. Variable is a name of memory location. Function is a reusable portion of a program, sometimes called a procedure or subroutine. A Class is a logical template to create objects that share common properties and methods. A Module is a group of closely related packages and resources along with a new module descriptor file. Rules An identifier can have letter [A-Z] or [a-z], numbers [0-9], and underscore (_) or a dollar sign ($). Cannot have a space in an identifier Cannot start with a number There is no limit in the length of an Identifier but it is a good practice to keep the length in between 4 to 15 letters only. We can't use the Java reserved keywords as an identifier Identifiers are case-sensitive
LITERALS Values to be stored in variables Types String Literal The text with alphanumeric characters enclosed in double quotes Example: “first”, “NPS”, “johny12##”, “ helloworld ”, “1234 Numeric Literal int – are positive or negative whole numbers with no decimal Example: 34, 267, -65, -30050593 float – float or double is a number, positive or negative, containing one or more decimals Example: 45.5, 678.7f, -234.56, -247.2334563f Character literal 2 bytes Any single letter enclosed within single quotes is a character literal Example: ‘a’, ‘G’, ‘8’, ‘#’. Boolean literal Used to represent one of the two Boolean values i.e., True or False
PUNCTUATORS Special characters used to implement the grammatical and structure of a Syntax.
OPERATORS operators are the special symbol that tells the compiler to perform a special operation.
Escape Sequence a character is preceded by a backslash (\) is known as Java escape sequence It may include letters, numerals, punctuations, escape characters must be enclosed in quotation marks ("").
Why Escape Sequence Lets see
Escape Sequence – sample program
Comments Remarks given in the program to explain some aspects of the code to someone reading the code. They are non-executable statements. There are two types of comments Single Line Comments - // Multi Line Comments - /* ….*/ Documentation Comments
Datatypes Type of data involved in the operation is known as Data type It specifies the different sizes and values that can be stored in the variable. Two types Primitive Data type Predefined data type Non -Primitive Data type User defined data type
DECLARATION OF THE VARIABLE Compiler allocates memory to the variables that are used in the program. int a =345; char ch =’p’; float pie=3.142f; String name= “James Gosling”; double rate= 2345.23586743; boolean attendance=true;
Programs Write a program to print “National Public School , Whitefield” , Your name & Your age Write a program to print “National Public School , Whitefield” , Your name & Your age in different lines Declare 6 different primitive variables , initialize a value and display the values in the variable. Declare three variables to store your name , class and section and print the same as a proper sentence . Write a program to store your name and age. Display the same and the age after 5 years in proper sentence . Write a program to store two numbers, display the sum, difference, product and quotient . Write a program to store a number, display the square of given number. Write a program to store three subject marks display the total & average.
1. Write a program to print “National Public School , Whitefield” in one line and Your name & Your age in next line public class prg1 { public static void main() { System.out.println ("National Public School Whitefield"); System.out.print ("Sreedevi R"); System.out.print ("12"); } }
2. Write a program to print “National Public School , Whitefield” , Your name & Your age in different lines public class prg2 { public static void main() { System.out.println ("National Public School Whitefield"); System.out.println ("Sreedevi R"); System.out.println ("12"); } }
3. Declare 6 different primitive variables , initialize a value and display the values in the variable. public class prg3 { public static void main() { byte a=121; short b=10000; int c=3000000; long d=1200882266; float pie=3.142f; double rate= 2345.23586743; char ch ='p'; boolean attendance=true; String name="James Gosling"; System.out.println ("Byte value"+a ); System.out.println ("Short value"+b ); System.out.println ("Integer value"+c ); System.out.println ("Long value"+d ); System.out.println ("Float value"+pie ); System.out.println ("Double value"+rate ); System.out.println ("Character value"+ ch ); System.out.println ("Boolean value"+attendance ); System.out.println ("String value"+name ); } }
4. Declare three variables to store your name , class and section and print the same as a proper sentence . public class prg4 { public static void main() { String name="James Gosling"; char c='8'; char s='B'; System.out.println ("My name is "+name+" I study in "+ c+s ); } }
5. Write a program to store your name and age. Display the same and the age after 5 years in proper sentence . public class prg5 { public static void main() { String name="James Gosling"; int age=12; int newage ; newage =age+5; System.out.println ("My name is "+name+" I am "+age+" years old"); System.out.println (" I will be "+ newage +"years old after 5 years"); } }
6. Write a program to store two numbers, display the sum, difference, product and quotient . public class prg6 { public static void main() { int num1=7; int num2=2; int sub; sub=num1-num2; System.out.println ("The two numbers are "+num1+" and "+num2); System.out.println (" The result of addition"+ num1+num2); System.out.println (" The result of subtraction"+ (num1-num2)); System.out.println (" The result of multiplication"+ num1*num2); System.out.println (" The result of division"+ num1/num2); } }
7. Write a program to store a number, display the square of given number. public class prg7 { public static void main() { int num1=7; int sqr ; sqr =num1*num1; System.out.println ("The square of the number "+num1+" is "+ sqr ); } }
7. Write a program to store a number, display the square of given number. public class prg7 { public static void main() { int num1=7; int sqr ; sqr =num1*num1; System.out.println ("The square of the number "+num1+" is "+ sqr ); } }
8. Write a program to store three subject marks display the total & average public class prg8 { public static void main() { int m1=72; int m2=89; int m3=92; int tot; int avg; tot=m1+m2+m3; avg=tot/3; System.out.println ("The marks in 3 subjects are "+m1+" , "+m2 +" , "+m3); System.out.println ("Total marks in 3 subjects is "+tot); System.out.println ("Average marks in 3 subjects is "+avg); } }
Programs Write a program to find the area and circumference of the circle. Write a program to find the area and perimeter of the square . Write a program to find the area and perimeter of the rectangle. Write a program to store the mass and acceleration of an object in two variables and display the force. (Hint: Force= mass*acceleration) Write a program to store the distance and time in two variables and display the speed. (Hint: speed= distance/time) Write a program to store the meters in a variable and convert it to kilometers. (Hint: 1 kilometer = 1000 Meters) Write a program to store the kilograms in a variable and convert it to grams. (Hint: 1 Kilogram = 1000 Grams) Write a program to store the temperature in a variable in Fahrenheit and convert it to Celsius. ( Hint: Celsius =(Fahrenheit – 32) x 5 ÷ 9 )
9. Write a program to find the area and circumference of the circle. public class prg9 { public static void main() { float radius=10; double area,perimeter ; area=(2*3.14*10*10); perimeter =2*3.14*10; System.out.println ("The radius of the circle is "+radius); System.out.println ("The area of the circle is "+area); System.out.println ("The perimeter of the circle is "+perimeter); } }
10. Write a program to find the area and perimeter of the square . public class prg10 { public static void main() { float s=18; double area,perimeter ; area=(s*s); perimeter =4*s; System.out.println ("The side of the square is "+s); System.out.println ("The area of the square is "+area); System.out.println ("The perimeter of the square is "+perimeter); } }
11. Write a program to find the area and perimeter of the rectangle . public class prg11 { public static void main() { float l=12,b=10; double area,perimeter ; area=(l*b); perimeter =2*( l+b ); System.out.println ("The length of the rectangle is "+l); System.out.println ("The breadth of the rectangle is "+b); System.out.println ("The area of the rectangle is "+area); System.out.println ("The perimeter of the rectangle is "+perimeter); } }
12 . Write a program to store the mass and acceleration of an object in two variables and display the force. (Hint: Force= mass*acceleration) public class prg12 { public static void main() { float mass=2,acc=5; double force; force=mass*acc; System.out.println ("The value of mass is "+mass+ " Kg"); System.out.println ("The value of Acceleration is "+acc+ " m/s"); System.out.println ("The force is "+force); } }
13. Write a program to store the distance and time in two variables and display the speed. (Hint: speed= distance/time) public class prg13 { public static void main() { float d=200,t=5; double speed; speed=d/t; System.out.println ("The value of distance is "+d+ " Km"); System.out.println ("The value of time is "+t+ " hr "); System.out.println ("The speed is "+ speed+"Km / hr "); } }
Homework Write a program to store the distance and time in two variables and display the speed. (Hint: speed= distance/time) Write a program to store the meters in a variable and convert it to kilometers. (Hint: 1 kilometer = 1000 Meters) Write a program to store the kilograms in a variable and convert it to grams. (Hint: 1 Kilogram = 1000 Grams)
13. Write a program to store the distance and time in two variables and display the speed. (Hint: speed= distance/time) public class prg13 { public static void main() { float d=200,t=5; double speed; speed=d/t; System.out.println ("The value of distance is "+d+ " Km"); System.out.println ("The value of time is "+t+ " hr "); System.out.println ("The speed is "+ speed+"Km / hr "); } }
14. Write a program to store the meters in a variable and convert it to kilometers. (Hint: 1 kilometer = 1000 Meters) public class prg14 { public static void main() { double m=2010.5; double km; km=m/1000; System.out.println ("The value in meters is "+m+ " m"); System.out.println ("The value in Kilometers is "+km+ " km"); } }
15. Write a program to store the kilograms in a variable and convert it to grams. (Hint: 1 Kilogram = 1000 Grams) public class prg15 { public static void main() { double kg=2.5; double g; g=kg*1000; System.out.println ("The value in Kilograms is "+kg+ " kg"); System.out.println ("The value in grams is "+g+ " g"); } }
16.Write a program to store the temperature in a variable in Fahrenheit and convert it to Celsius. ( Hint: Celsius =(Fahrenheit – 32) x 5 ÷ 9 ) public class prg16 { public static void main() { double f=102.5; double c; c=(f-32.5)*5/9; System.out.println ("The value in Fahrenheit is "+f+ " f"); System.out.println ("The value in Celsius is "+c+ "c"); } }
Java User Input Java Scanner class is part of the java. util package. The Scanner is mostly used to receive user input and parse them into primitive data types such as int, double or default String. create an object of the class and use any of the available methods found in the Scanner class documentation
Java User Input Scanner myObj = new Scanner(System.in); String name = myObj.nextLine (); int age = myObj.nextInt (); double salary = myObj.nextDouble ();
17. Write a program to store the distance and time in two variables and display the speed. (Hint: speed= distance/time) public class prg17 { public static void main() { Scanner myObj = new Scanner(System.in); Float distance = myObj.nextFloat (); Float time = myObj.nextFloat (); //float d=200,t=5; double speed; speed=d/t; System.out.println ("The value of distance is "+d+ " Km"); System.out.println ("The value of time is "+t+ " hr "); System.out.println ("The speed is "+ speed+"Km / hr "); } }
Type Conversion Conversion of one Primitive data type to another Primitive data type is known as type conversion. Two types: Implicit Type Conversion When the conversion automatically performs by the compiler without the programmer's interference, it is called implicit type casting E xplicit Type Conversion
Implicit Type Conversion (Widening) The conversion involves a smaller data type to the larger type size. Two conditions: 1. Both source and destination should be compatible. 2. The destination type should be larger than the source.
class itc { public static void main(String[] args ) { int i = 100; // Automatic type conversion // Integer to long type long l = i ; // Automatic type conversion // long to float type float f = l; // Print and display commands System.out.println ("Int value " + i ); System.out.println ("Long value " + l); System.out.println ("Float value " + f); } }
Explicit Type Conversion The conversion involves a smaller data type to the larger type size. Two conditions: 1. Both source and destination are in-compatible. 2. The Destination type is smaller than the source type..
class etc { public static void main(String args []) { byte b; int i = 257; double d = 323.142; System.out.println ("Conversion of int to byte."); b = (byte) i ; System.out.println (" i = " + i + " b = " + b); System.out.println ("\ nConversion of double to byte."); b = (byte)d; System.out.println ("d = " + d + " b= " + b); } }
Operators Chapter 8
Key terms OPERATORS - symbol that performs a specific kind of operation OPERANDS - A value involved in an operation EXPRESSION - any legal combination of symbols that represents a value, which is evaluated and produces the result. STATEMENT - programming instruction that does something
a=7 b=5 False True True True False False
int age; age=15; int a = 7; int b = 2; 2 Result - New value in a will be 9 3 14 5 1
Operator Precedence
; byte d;
// Implicitly it is not possible
Decision Making Statement
Decision Making Statement Flow of control of program Execute a block of statement depending upon a condition if statement if…else statement Nested if if…else…if statement Switch Case
if statement Syntax if(condition / test expression) { statement(s) will execute if the condition is true } Example a = 15; if( a < 20 ) System.out.println ("a is less than 20" ); System.out.println ("value of a is :", a );
Write a program to check the age of a person for casting vote import java.util .*; public class Prg18 { public static void main() { Scanner myObj = new Scanner(System.in); int age= myObj.nextInt (); if( age>= 18 ) System.out.println ("Congratulations !You can caste vote"); } }
if…else statement Syntax if(condition) { statement(s) will execute if the condition is true } else { statement(s) will execute if the condition is false } Example a = 100 if( a < 20 ) System.out.println ("a is less than 20" ) ; else System.out.println ("a is not less than 20" ) ;
Write a program to check the age of a person for casting vote (if…else) import java.util .*; public class Prg19 { public static void main() { Scanner myObj = new Scanner(System.in); int age= myObj.nextInt (); if( age>= 18 ) System.out.println ("Congratulations !You can caste vote"); else System.out.println (“Oops !You have to wait for some more time to vote"); } }
Write two programs to explain the prefix and postfix concept of Increment / Decrement Operator public class IncrementDecrement1 { public static void main(String[] args ) { int b = 5; ++b; System.out.println (b++); b++; System.out.println (b); } } public class IncrementDecrement2 { public static void main(String[] args ) { int a=11, b=22, c; c = a + b + a++ + b++ + ++a + ++b; System.out.println ("a="+a); System.out.println ("b="+b); System.out.println ("c="+c); } } Output 6 8 Output 13 24 103
Q uestions Write a program to check the age of a person for casting vote Write a program to check the age of a person for casting vote (if…else) Write a program to check whether a given number is even or odd Write a program to check whether a given number is positive or negative Write a program to check whether a number is divisible by 5 and 11 or not. A certain amount is invested at the rate 10% per annum for 3 years. On the maturity , if the total sum that can be withdrawn is more than Rs.5,000 the person will be charged Rs 150 and only the remaining amount will be released. Write a Java program to Accept the Principal amount and find the Simple Interest (SI) and based on the above condition find the total amount the person will be able to withdraw Hint: SI = (P * R * T) / 100. Write a program to find whether a given year is a leap year or not Write a java program to calculate the electricity bill based on the following criteria: However on the bill amount they have to pay a GST of 3 %. Write a program to find the eligibility of admission for a professional course based on the following criteria: Marks in Maths >=65 Marks in Phys >=55 Marks in Chem>=50 Units Price per unit 1 to 100 1.20 101 to 300 2 301 and more 3
Write a program to check whether a given number is even or odd. import java.util .*; public class prg21 { public static void main() { System.out.println (“Enter a whole number :"); Scanner myObj = new Scanner(System.in); int num= myObj.nextInt (); if( num%2==0) System.out.println ("The entered number is even"); else System.out.println ("The entered number is odd"); } }
Write a program to check whether a given number is positive or negative. import java.util .*; public class prg21 { public static void main() { System.out.println (“Enter a whole number :"); Scanner myObj = new Scanner(System.in); int num= myObj.nextInt (); if( num>=0) System.out.println ("The entered number is positive number"); else System.out.println ("The entered number is negative number"); } }
22.Write a program to check whether a number is divisible by 5 and 11 or not. import java.util .*; public class prg22 { public static void main() { System.out.println (“Enter a whole number :"); Scanner myObj = new Scanner(System.in); int num= myObj.nextInt (); if (num%5==0) &&(num%11==0) System.out.println ("The number is divisible by both 5 and 11"); else System.out.println (“the number is not divisible by both 5 and 11"); } }
23. A certain amount is invested at the rate 10% per annum for 3 years. On the maturity, if the interest amount is more than Rs.5,000 the person will be charged Rs 150 and only the remaining amount will be released . Write a Java program to Accept the Principal amount and find the Simple Interest (SI) and based on the above condition find the total amount the person will be able to withdraw Hint: SI = (P * R * T) / 100 . import java.util .*; public class SI_CI { public static void main(String args []) { Scanner in = new Scanner(System.in); System.out.print ("Enter Amount: "); double p = in.nextDouble (); double si = p * 10 * 3 / 100; double withdraw; if( si >=5000) { withdraw=p+si-150; System.out.println ("The amount you can withdraw is"+withdraw );} else { withdraw= p+si ; System.out.println ("The amount you can withdraw is "+withdraw); } } }
Q24. Write a program to find whether a given year is a leap year or not import java.util .*; public class prg26 { public static void main() { Scanner yr = new Scanner(System.in); System.out.println ("Enter the year:"); int year = yr.nextInt (); if((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0)) System.out.println ( year+"is a leap year."); else System.out.println ( year+"is not a leap year."); } } To determine whether a year is a leap year, follow these steps: If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5. The year is a leap year (it has 366 days). The year is not a leap year (it has 365 days).
if...else if...else statement Syntax if(condition 1) statement 1 else if( condition 2) statement 2 else if( condition 3) statement 3 else --- executes when the none of the above condition is true ---
if...else if...else statement Example a = 100 if( a == 10 ) then print("Value of a is 10" ) elseif( a == 20 ) then print("Value of a is 20" ) elseif( a == 30 ) then print("Value of a is 30" ) else print("None of the values is matching" ) end
Q uestions Write a program to check the age of a person for casting vote Write a program to check the age of a person for casting vote (if…else) Write a program to check whether a given number is even or odd Write a program to check whether a given number is positive or negative Write a program to check whether a number is divisible by 5 and 11 or not. A certain amount is invested at the rate 10% per annum for 3 years. On the maturity , if the total sum that can be withdrawn is more than Rs.5,000 the person will be charged Rs 150 and only the remaining amount will be released. Write a Java program to Accept the Principal amount and find the Simple Interest (SI) and based on the above condition find the total amount the person will be able to withdraw Hint: SI = (P * R * T) / 100. Write a program to find whether a given year is a leap year or not Write a java program to calculate the electricity bill based on the following criteria: However on the bill amount they have to pay a GST of 3 %. Write a program to find the eligibility of admission for a professional course based on the following criteria: Marks in Maths >=65 Marks in Phys >=55 Marks in Chem>=50 Units Price per unit 1 to 100 1.20 101 to 300 2 301 and more 3
Q25. Write a java program to calculate the electricity bill based on the following criteria: class ComputeElectricityBill { public static void main(String args []) { long units; Scanner sc =new Scanner(System.in); System.out.println ("enter number of units"); units= sc.nextLong (); double billpay =0; if(units<100) billpay =units*1.20; else if(units<300) billpay =100*1.20+(units-100)*2; else if(units>300) billpay =100*1.20+200 *2+(units-300)*3; System.out.println ("Bill to pay : " + billpay ); } } Units Price per unit 1 to 100 1.20 101 to 300 2 301 and more 3
Q26. Write a program to find the eligibility of admission for a professional course based on the following criteria: Marks in Maths >=65 Marks in Phy >=55 Marks in Chem>=50 import java.util .*; public class prg23 { public static void main() { Scanner mrk = new Scanner(System.in); System.out.println ("Enter your Maths marks:"); float maths = mrk.nextFloat (); System.out.println ("Enter your Physics marks:"); float phys = mrk.nextFloat (); System.out.println ("Enter your Chemistry marks:"); float chem= mrk.nextFloat (); if(( maths >=65)&&( phys >=55) &&(chem>=50)) System.out.println ("Congratulations!"); else System.out.println ("Better Luck Next Time!"); } }
Assessment Zone Write a program to check the age of a person to display the fare amount as per the following condition . Age Fare amount >=60 4000 >=15 and <60 5000
Q. Write a program to check the age of a person to display the fare amount as per the following condition age= io.read ("*n") if(age >=60) then print(“You will have to pay ₹. 4000”) elseif (age>=15 and age<60) then print("The amount you have to pay ₹. 5000”) else print(“No fare”) end
Q. Write a program to take the bill amount from the user and then display the resultant amount to be paid by the customer ba = io.read ("*n") if( ba >=5000 and ba <10000) then print("The amount you have to pay after the discount of ₹500 is",ba-500) elseif ( ba >=10000 and ba <15000) then print("The amount you have to pay after the discount of ₹750 is",ba-750) elseif( ba >=15000) then print("The amount you have to pay after the discount of ₹1000 is",ba-1000) else print("Please pay the Bill Amount", ba ) end
Q. Write a program to take number of hours from the user and then display the charges to be paid. hour= io.read ("*n") if(hour<10) then print("You will be charged ₹300") elseif (hour>=10 and hour<20) then print("You will be charged ₹400") else print("You will be charged ₹500") end
Q. Which class collected most . Cl_A_str =48 Cl_B_str =55 Cl_A_P =50 Cl_B_P =45 if( Cl_A_str * Cl_A_P > Cl_B_str * Cl_B_P ) then print(“Class A has collected more fund") elseif ( Cl_A_str * Cl_A_P > Cl_B_str * Cl_B_P ) then print (“Class A has collected more fund") end
Revision Write a Lua program to find the area of triangle (hint : area of triangle = ½ * base *height) 2. Write a Lua program to Swap Two Variables (use a dummy variable)