0% found this document useful (0 votes)
2 views35 pages

Java Lecture 2 - Merged

The document provides an introduction to Java programming, covering variables, data types, constants, conditional statements, loops, and patterns. It explains primitive and non-primitive data types, along with practical examples and homework problems for practice. The content is structured across multiple lectures, each focusing on different programming concepts and includes sample code snippets for clarity.

Uploaded by

Hr Vidya
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)
2 views35 pages

Java Lecture 2 - Merged

The document provides an introduction to Java programming, covering variables, data types, constants, conditional statements, loops, and patterns. It explains primitive and non-primitive data types, along with practical examples and homework problems for practice. The content is structured across multiple lectures, each focusing on different programming concepts and includes sample code snippets for clarity.

Uploaded by

Hr Vidya
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/ 35

Java - Introduction to Programming

Lecture 2

Variables & Data Types

1.​ Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).

package [Link];

public class Main {

public static void main(String[] args) {


// Variables
String name = "Aman";
int age = 30;

String neighbour = "Akku";


String friend = neighbour;
}
}

2.​ Data Types


Data types are declarations for variables. This determines the type and size of
data associated with variables which is essential to know since different data
types occupy different sizes of memory.

There are 2 types of Data Types :


-​ Primitive Data types : to store simple values
-​ Non-Primitive Data types : to store complex values

​ Primitive Data Types


​ These are the data types of fixed size.

Apna College
Data Type Meaning Size Range
(in Bytes)

byte 2’s complement integer 1 -128 to 127

short 2’s complement integer 2 -32K to 32K

int Integer numbers 4 -2B to 2B

long 2’s complement integer 8 -9,223,372,036,85


4,775,808
(larger values) to
9,223,372,036,85
4,775,807

float Floating-point 4 Upto 7 decimal


digits

double Double Floating-point 8 Upto 16


decimal digits

char Character 2 a, b, c ..​


A, B, C ..
@, #, $ ..

bool Boolean 1 True, false

Non-Primitive Data Types


​ These are of variable size & are usually declared with a ‘new’ keyword.

​ Eg : String, Arrays

​ String name = new String("Aman");


int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;

3.​ Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned
a different value once assigned.

Apna College
package [Link];

public class Main {

public static void main(String[] args) {


// Constants
final float PI = 3.14F;
}
}

Homework Problems
1.​ Try to declare meaningful variables of each type. Eg - a variable
named age should be a numeric type (int or float) not byte.

2.​ Make a program that takes the radius of a circle as input,


calculates its radius and area and prints it as output to the user.

3.​ Make a program that prints the table of a number that is input by
the user.

(HINT - You will have to write 10 lines for this but as we proceed in
the course you will be studying about ‘LOOPS’ that will simplify
your work A LOT!)

KEEP LEARNING & KEEP PRACTICING :)

Apna College
Java - Introduction to Programming
Lecture 3

1.​ Conditional Statements ‘if-else’


The if block is used to specify the code to be executed if the condition specified
in if is true, the else block is executed otherwise.

int age = 30;


if(age > 18) {
[Link]("This is an adult");
} else {
[Link]("This is not an adult");
}

2.​ Conditional Statements ‘switch’


Switch case statements are a substitute for long if statements that compare a
variable to multiple values. After a match is found, it executes the
corresponding code of that value case.

The following example is to print days of the week:

int n = 1;
switch(n) {
case 1 :
[Link]("Monday");
break;
case 2 :
[Link]("Tuesday");
break;
case 3 :
[Link]("Wednesday");
break;
case 4 :
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6 :
[Link]("Saturday");
break;
default :
[Link]("Sunday");
}

Apna College
Homework Problems
1.​ Make a Calculator. Take 2 numbers (a & b) from the user and an
operation as follows :

​ 1 : + (Addition) a + b

●​ 2 : - (Subtraction) a - b
●​ 3 : * (Multiplication) a * b
●​ 4 : / (Division) a / b
●​ 5 : % (Modulo or remainder) a % b

Calculate the result according to the operation given and


display it to the user.

2.​ Ask the user to enter the number of the month & print the name
of the month. For eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ &
so on.

KEEP LEARNING & KEEP PRACTICING :)

Apna College
Java - Introduction to Programming
Lecture 4

Loops
A loop is used for executing a block of statements repeatedly until a particular
condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.

For Loop
The syntax of the for loop is :

for (initialization; condition; update) {


// body of-loop
}

for (int i=1; i<=20; i++) {


[Link](i);
}

While Loop
The syntax for while loop is :
while(condition) {
// body of the loop
}

int i = 0;
while(i<=20) {
[Link](i);
i++;
}

Do-While Loop
The syntax for the do-while loop is :
do {
// body of loop;
}
while (condition);

int i = 0;
do {
[Link](i);

Apna College
i++;
} while(i<=20);

Homework Problems
1.​ Print all even numbers till n.
2.​ Run
for(; ;) {

[Link]("Apna College");

loop on your system and analyze what happens. Try to think of the reason for
the output produced.

3.​ Make a menu driven program. The user can enter 2 numbers, either 1 or 0.

If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

​ Because marks don’t matter but our effort does.

(Hint : use do-while loop but think & understand why)

BONUS

Qs. Print if a number is prime or not (Input n from the user).

[In this problem you will learn how to check if a number is prime or not]

Apna College
Homework Solution (Lecture 3)

import [Link].*;

public class Conditions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int operator = [Link]();

/**
* 1 -> +
* 2 -> -
* 3 -> *
* 4 -> /
* 5 -> %
*/

switch(operator) {
case 1 : [Link](a+b);
break;
case 2 : [Link](a-b);
break;
case 3 : [Link](a*b);
break;
case 4 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a/b);
}
​ break;
case 5 : if(b == 0) {
[Link]("Invalid Division");
} else {
[Link](a%b);
}
​ break;
default : [Link]("Invalid Operator");
}
}

Apna College
}

Apna College
Java - Introduction to Programming
Lecture 5

Patterns - Part 1

1.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int m = 4;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
2.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int m = 4;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(i == 0 || i == n-1 || j == 0 || j == m-1) {
[Link]("*");
} else {
[Link](" ");
}
}
[Link]();
}
}
}

Apna College
3.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
4.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=n; i>=1; i--) {


for(int j=1; j<=i; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
5.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 4;

for(int i=n; i>=1; i--) {


for(int j=1; j<i; j++) {
[Link](" ");
}

for(int j=0; j<=n-i; j++) {


[Link]("*");
}
[Link]();
}
}
}

Apna College
6.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
7.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=n; i>=1; i--) {


for(int j=1; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
8.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;
int number = 1;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
[Link](number+" ");
number++;
}
[Link]();
}
}
}

Apna College
9.​

import [Link].*;

public class Patterns {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


for(int j=1; j<=i; j++) {
if((i+j) % 2 == 0) {
[Link](1+" ");
} else {
[Link](0+" ");
}
}
[Link]();
}
}
}

Apna College
Homework Problems (Solutions in next Lecture’s Video)
1.​ Print a solid rhombus.

2.​ Print a number pyramid.

3.​ Print a palindromic number pyramid.

Apna College
Homework Solution (Lecture 4)

1.​ Print all even numbers till n.

1.​ public class Solutions {

2.​ public static void main(String args[]) {

3.​ int n = 25;

4.​

5.​ for(int i=1; i<=n; i++) {

6.​ if(i % 2 == 0) {

7.​ [Link](i);

8.​ }

9.​ }

10.​ }

11.​ }

12.​

3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.
If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).

If they enter 0 then stop.

If he/ she scores :

Marks >=90 -> print “This is Good”

89 >= Marks >= 60 -> print “This is also Good”

59 >= Marks >= 0 -> print “This is Good as well”

​ Because marks don’t matter but our effort does.

Apna College
(Hint : use do-while loop but think & understand why)

import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int input;

do {
int marks = [Link]();
if(marks >= 90 && marks <= 100) {
[Link]("This is Good");
} else if(marks >= 60 && marks <= 89) {
[Link]("This is also Good");
} else if(marks >= 0 && marks <= 59) {
[Link]("This is Good as well");
} else {
[Link]("Invalid");
}

[Link]("Want to continue ? (yes(1) or no(0))");


input = [Link]();

} while(input == 1);
}
}

Qs. Print if a number n is prime or not (Input n from the user).

[In this problem you will learn how to check if a number is prime or not]
import [Link].*;

public class Solutions {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

boolean isPrime = true;


for(int i=2; i<=n/2; i++) {

Apna College
if(n % i == 0) {
isPrime = false;
break;
}
}

if(isPrime) {
if(n == 1) {
[Link]("This is neither prime not composite");
} else {
[Link]("This is a prime number");
}
} else {
[Link]("This is not a prime number");
}
}
}

Apna College
Java - Introduction to Programming
Lecture 6

Patterns - Part 2

1.​

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 4;

//upper part
for(int i=1; i<=n; i++) {
for(int j=1; j<=i; j++) {
[Link]("*");
}

int spaces = 2 * (n-i);


for(int j=1; j<=spaces; j++) {
[Link](" ");
}

for(int j=1; j<=i; j++) {


[Link]("*");
}
[Link]();
}

Apna College
//lower part
for(int i=n; i>=1; i--) {
for(int j=1; j<=i; j++) {
[Link]("*");
}

int spaces = 2 * (n-i);


for(int j=1; j<=spaces; j++) {
[Link](" ");
}

for(int j=1; j<=i; j++) {


[Link]("*");
}
[Link]();
}
}
}

2.​

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

Apna College
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//stars
for(int j=1; j<=n; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
3.​

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

for(int i=1; i<=n; i++) {


//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//numbers
for(int j=1; j<=i; j++) {
[Link](i+" ");
}
[Link]();
}
}
}

Apna College
4.​

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}

//first part
for(int j=i; j>=1; j--) {
[Link](j);
}

//second part
for(int j=2; j<=i; j++) {
[Link](j);
}
[Link]();
}
}
}

Apna College
5.​

import [Link].*;

public class Solutions {


public static void main(String args[]) {
int n = 5;

//upper part
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}
for(int j=1; j<=2*i-1; j++) {
[Link]("*");
}
[Link]();
}

//lower part
for(int i=n; i>=1; i--) {
//spaces
for(int j=1; j<=n-i; j++) {
[Link](" ");
}
for(int j=1; j<=2*i-1; j++) {
[Link]("*");
}
[Link]();
}
}
}

Apna College
Homework Problems
1.​ Print a hollow Butterfly.

​ ​

2.​ Print a hollow Rhombus.

*****

* *

* *

* *

*****

3.​ Print Pascal’s Triangle.

11

121

1331

14641

4.​ Print half Pyramid.

Apna College
12

123

1234

12345

5.​ Print Inverted Half Pyramid.

11111

222

33

Apna College
Java - Introduction to Programming
Lecture 7

Methods/Functions
A function is a block of code that performs a specific task.
Why are functions used?
a.​ If some functionality is performed at multiple places in software, then
rather than writing the same code, again and again, we create a function
and call it everywhere. This helps reduce code redundancy.
b.​ Functions make maintenance of code easy as we have to change at one
place if we make future changes to the functionality.
c.​ Functions make the code more readable and easy to understand.

The syntax for function declaration is :


return-type function_name (parameter 1, parameter2, …… parameter n){
//function_body
}
return-type

The return type of a function is the data type of the variable that that function
returns.

For eg - If we write a function that adds 2 integers and returns their sum then
the return type of this function will be ‘int’ as we will return a sum that is an
integer value.
When a function does not return any value, in that case the return type of the
function is ‘void’.

function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used.

Parameters
A function can take some parameters as inputs. These parameters are specified
along with their data types.
For eg- if we are writing a function to add 2 integers, the parameters would be
passed like –
int add (int num1, int num2)
Apna College
main function
The main function is a special function as the computer starts running the code
from the beginning of the main function. Main function serves as the entry point
for the program.

Example :

package [Link];

public class Main {


//A METHOD to calculate sum of 2 numbers - a & b
public static void sum(int a, int b) {
int sum = a + b;
[Link](sum);
}

public static void main(String[] args) {


int a = 10;
int b = 20;
sum(a, b); // Function Call

}
}

Qs. Write a function to multiply 2 numbers.

import [Link].*;

public class Functions {

//Multiply 2 numbers

public static int multiply(int a, int b) {

return a*b;

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

Apna College
int a = [Link]();

int b = [Link]();

int result = multiply(a, b);

[Link](result);

Qs. Write a function to calculate the factorial of a number.

​import [Link].*;

public class Functions {


// public static int calculateSum(int a, int b) {
// int sum = a + b;
// return sum;
// }

// public static int calculateProduct(int a, int b) {


// return a * b;
// }

public static void printFactorial(int n) {


//loop
if(n < 0) {
[Link]("Invalid Number");
return;
}
int factorial = 1;

for(int i=n; i>=1; i--) {


factorial = factorial * i;
}

[Link](factorial);
return;
}

Apna College
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();

printFactorial(n);
}
}

Qs. Write a function to calculate the product of 2 numbers.


import [Link].*;

public class Functions {

// public static int calculateSum(int a, int b) {

// int sum = a + b;

// return sum;

// }

public static int calculateProduct(int a, int b) {

return a * b;

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int a = [Link]();

int b = [Link]();

[Link](calculateProduct(a, b));

Apna College
Homework Problems
1.​ Make a function to check if a number is prime or not.
2.​ Make a function to check if a given number n is even or not.
3.​ Make a function to print the table of a given number n.
4.​ Read about Recursion.

Apna College

You might also like