Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

lec3-Java Tutorial

This document provides a comprehensive tutorial on Java programming, covering key concepts such as variables, data types, literals, user input, operators, and expressions. It explains the rules for declaring variables, the different data types available in Java, and how to use the Scanner class for user input. Additionally, it includes practical exercises and code examples to reinforce learning.

Uploaded by

kashish bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lec3-Java Tutorial

This document provides a comprehensive tutorial on Java programming, covering key concepts such as variables, data types, literals, user input, operators, and expressions. It explains the rules for declaring variables, the different data types available in Java, and how to use the Scanner class for user input. Additionally, it includes practical exercises and code examples to reinforce learning.

Uploaded by

kashish bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Java Tutorial: Variables and Data Types in

Java Programming- lec3


Just like we have some rules that we follow to speak English (the
grammar), we have some rules to follow while writing a Java
program. This set of these rules is called syntax. It’s like
Vocabulary and Grammar of Java.
Variables

 A variable is a container that stores a value.


 This value can be changed during the execution of the
program.
 Example: int number = 8; (Here, int is a data type, the
number is the variable name, and 8 is the value it
contains/stores).

Rules for declaring a variable name


We can choose a name while declaring a Java variable if the
following rules are followed:

 Must not begin with a digit. (E.g., 1arry is an invalid


variable)
 Name is case sensitive. (Harry and harry are different)
 Should not be a keyword (like Void).
 White space is not allowed. (int Code With Harry is
invalid)
 Can contain alphabets, $character, _character, and digits
if the other conditions are met.

Data Types
Data types in Java fall under the following categories

1. Primitive Data Types (Intrinsic)


2. Non-Primitive Data Types (Derived)

Primitive Data Types


Java is statically typed, i.e., variables must be declared before
use. Java supports 8 primitive data types:
Data Type Size Value Range
1. Byte 1 byte -128 to 127
2. short 1 byte -32,768 to 32,767
3. int 2 byte -2,147,483,648 to 2,147,483,647
4. float 4 byte 3.40282347 x 1038 to 1.40239846 x 1
-9,223,372,036,854,775,808 to
5. long 8 byte
9,223,372,036,854,775,807
1.7976931348623157 x 10308,
6. double 8 byte
4.9406564584124654 x 10-324
7. char 2 byte 0 to 65,535
8. boolean Depends on JVM True or False
Quick Quiz: Write a Java program to add three numbers,
How to choose data types for our variables
In order to choose the data type, we first need to find the type of
data we want to store. After that, we need to analyze the min &
max value we might use.
Java Tutorial: Literals in Java lec4
Literals
A constant value that can be assigned to the variable is called a literal.

 101 – Integer literal


 10.1f – float literal
 10.1 – double literal (default type for decimals)
 ‘A’ – character literal
 true – Boolean literal
 “Harry” – String literal

Keywords
Words that are reserved and used by the Java compiler. They cannot be
used as an Identifier.
{You can visit docs.oracle.com for a comprehensive list}
Code as Described in the Video
package com.company;

public class CWH_04_literals {


public static void main(String[] args) {
byte age = 34;
int age2 = 56;
short age3 = 87;
long ageDino = 5666666666666L;
char ch = 'A';
float f1 = 5.6f;
double d1 = 4.66;

boolean a = true;
System.out.print(age);
String str = "Harry";
System.out.println(str);

}
}
Java Tutorial: Getting User Input
in Java
Lec5
Reading data from the Keyboard :
Scanner class of java.util package is used to take input from the user's
keyboard.The Scanner class has many methods for taking input from the
user depending upon the type of input. To use any of the methods of the
Scanner class, first, we need to create an object of the Scanner class as
shown in the below example :

import java.util.Scanner; // Importing the Scanner class


Scanner sc = new Scanner(System.in); //Creating an object
named "sc" of the Scanner class.

Copy
Taking an integer input from the keyboard :
Scanner S = new Scanner(System.in); //(Read from the
keyboard)
int a = S.nextInt(); //(Method to read from the keyboard)

Copy
Code as Described in the Video
package com.company;
import java.util.Scanner;

public class CWH_05_TakingInpu {


public static void main(String[] args) {
System.out.println("Taking Input From the User");
Scanner sc = new Scanner(System.in);
// System.out.println("Enter number 1");
// int a = sc.nextInt();
// float a = sc.nextFloat();
// System.out.println("Enter number 2");
// int b = sc.nextInt();
// float b = sc.nextFloat();

// int sum = a +b;


// float sum = a +b;
// System.out.println("The sum of these numbers is");
// System.out.println(sum);
// boolean b1 = sc.hasNextInt();
// System.out.println(b1);
// String str = sc.next();
String str = sc.nextLine();
System.out.println(str);

}
}

Java Programming Exercise 1:


CBSE Board Percentage
Calculator LEC6
Exercise 1.1
Write a program to calculate the percentage of a given student in the
CBSE board exam. His marks from 5 subjects must be taken as input from
the keyboard. (Marks are out of 100)

Java Tutorial: Chapter 1- Practice


Set | Java Practice Problems with
Solution -7
Chapter 1 – Practice Set

1. Write a program to sum three numbers in Java.


2. Write a program to calculate CGPA using marks of three subjects
(out of 100)
3. Write a Java program that asks the user to enter his/her name
and greets them with “Hello <name>, have a good day” text.
4. Write a Java program to convert Kilometers to miles.
5. Write a Java program to detect whether a number entered by the
user is an integer or not.

Code as Described in the Video


package com.company;

import java.util.Scanner;

public class CWH_Ch1_PS {


public static void main(String[] args) {
// Question1
// int a = 4;
// int b = 17;
// int c =6;
// int sum = a + b+c;
// System.out.println(sum);

// Question2
// float subject1 = 45;
// float subject2 = 95;
// float subject3 = 48;
// float cgpa = (subject1 + subject2 +subject3)/30;
// System.out.println(cgpa);

// Question 3
// System.out.println("What is your name");
// Scanner sc = new Scanner(System.in);
// String name = sc.next();
// System.out.println("Hello " + name + " have a good
day!");

// Question 5
System.out.println("Enter your number");
Scanner sc = new Scanner(System.in);
System.out.println(sc.hasNextInt());
}

Java Tutorial: Operators, Types


of Operators & Expressions in
Java lec8
 An operator is a symbol that the compiler to perform a specific
operation on operands.
 Example : a + b = c
 In the above example, 'a' and 'b' are operands on which the '+'
operator is applied.

Types of operators :
1. Arithmetic Operators :
 Arithmetic operators are used to perform mathematical
operations such as addition, division, etc on expressions.
 Arithmetic operators cannot work with Booleans.
 % operator can work on floats and doubles.
 Let x=7 and y=2

Operator Description Example

+ (Addition) Used to add two numbers x+y=9

Used to subtract the right-hand side value from


- (Subtraction) x-y=5
the left-hand side value

*
Used to multiply two values. x * y = 14
(Multiplication)

Used to divide left-hand Value by right-hand


/ (Division) x/y=3
value.

Used to print the remainder after dividing the


% (Modulus) left-hand side value from x%y=1
the right-hand side value.

++ (Increment) Increases the value of operand by 1. x++ = 8

-- (Decrement) Decreases the value of operand by 1. y-- = 1

2. Comparison Operators :
 As the name suggests, these operators are used to compare
two operands.
 Let x=7 and y=2

Operator Description Example

Checks if two operands are equal.


== (Equal to) x == y --> False
Returns a Boolean value.

Checks if two operands are not equal.


!= (Not equal x != y --> True
Returns a Boolean value.

Checks if the left-hand side value is


> (Greater than) greater than the right-hand side value. x > y --> True
Returns a Boolean value.

Checks if the left-hand side value is


< (Less than) smaller than the right-hand side value. x < y --> False
Returns a Boolean value.

Checks if the left-hand side value is


>=(Greater than or equal to) greater than or equal to the right-hand x >= y --> True
side value. Returns a Boolean value.

Checks if the left-hand side value is less


<= (Less than or equal to) than or equal to the right-hand side x <= y -->False
value. Returns a Boolean value.

3. Logical Operators:
 These operators determine the logic in an expression
containing two or more values or variables.
 Let x = 8 and y =2

&& (logical Returns true if both operands are true. x<y && x!=y -->
and) True

|| (logical or) Returns true if any of the operand is true. x<y && x==y --> True

Returns true if the result of the expression is false and !(x<y && x==y)
! (logical not)
vice-versa --> False

4. Bitwise Operators :
 These operators perform the operations on every bit of a
number.
 Let x =2 and y=3. So 2 in binary is 100, and 3 is 011.

Operator Description Example

& (bitwise and) 1&1 =1, 0&1=0,1&0=0,1&1=1, 0&0 =0 (A & B) = (100 & 011) = 000

| (bitwise or) 1&0 =1, 0&1=1,1&1=1, 0&0=0 (A | B) = (100 | 011 ) = 111

^ (bitwise XOR) 1&0 =1, 0&1=1,1&1=0, 0&0=0 (A ^ B) = (100 ^ 011 ) = 111

This operator moves the value left by


<< (left shift) 13<<2 = 52(decimal)
the number of bits specified.

This operator moves the value left by


>> (right shift) 13>>2 = 3(decimal)
the number of bits specified.

Precedence of operators
The operators are applied and evaluated based on precedence. For
example, (+, -) has less precedence compared to (*, /). Hence * and / are
evaluated first.
In case we like to change this order, we use parenthesis ().
Code as Described in the Video
package com.company;

public class CWH_Ch2_Operators {


public static void main(String[] args) {
// 1. Arithmetic Operators
int a = 4;
// int b = 6 % a; // Modulo Operator
// 4.8%1.1 --> Returns Decimal Remainder

// 2. Assignment Operators
int b = 9;
b *= 3;
System.out.println(b);

// 3. Comparison Operators
// System.out.println(64<6);
// 4. Logical Operators
// System.out.println(64>5 && 64>98);
System.out.println(64>5 || 64>98);

// 5. Bitwise Operators
System.out.println(2&3);
// 10
// 11
// ----
// 10
}
}

Java Tutorial: Associativity of


Operators in Java-lec9
Associativity
Associativity tells the direction of the execution of operators. It can either
be left to right or vice versa.
/ * -> L to R
+ - -> L to R
++, = -> R to L
Here is the precedence and associativity table which makes it easy for
you to understand these topics better:
Quick Quiz: How will you write the following expression in Java?

Code as Described in the Video

package com.company;
public class cwh_09_ch2_op_pre {
public static void main(String[] args) {
// Precedence & Associativity

//int a = 6*5-34/2;
/*
Highest precedence goes to * and /. They are then
evaluated on the basis
of left to right associativity
=30-34/2
=30-17
=13
*/
//int b = 60/5-34*2;
/*
= 12-34*2
=12-68
=-56
*/

//System.out.println(a);
//System.out.println(b);

// Quick Quiz
int x =6;
int y = 1;
// int k = x * y/2;

int b = 0;
int c = 0;
int a = 10;
int k = b*b - (4*a*c)/(2*a);
System.out.println(k);

}
}

Java Tutorial: Data Type of


Expressions &
Increment/Decrement Operators
lec10
Resulting data type after arithmetic operation

 Result = byte + short -> integer


 Result = short + integer -> integer
 Result = long + float -> float
 Result = integer + float -> float
 Result = character + integer -> integer
 Result = character + short -> integer
 Result = long + double -> double
 Result = float + double -> double

Increment and Decrement operators

 a++, ++a (Increment Operators)


 a--, --a (Decrement Operators)

These will operate on all data types except Booleans.


Quick Quiz: Try increment and decrement operators on a Java variable

 a++ -> first use the value and then increment


 ++a -> first increment the value then use it

Quick Quiz: What will be the value of the following expression(x).

1. int y=7;
2. int x = ++y*8;
3. value of x?
4. char a = ‘B’;
5. a++; (a is not ‘C’)

Code as Described in the Video


package com.company;

public class cwh_10_resulting_data_type {


public static void main(String[] args) {
/* byte x = 5;
int y = 6;
short z = 8;
int a = y + z;
float b = 6.54f + x;
System.out.println(b); */

// Increment and Decrement Operators


int i = 56;
// int b = i++; // first b is assigned i (56) then i
is incremented
int j = 67;
int c = ++j; // first j is incremented then c is
assigned j (68)
System.out.println(i++);
System.out.println(i);
System.out.println(++i);
System.out.println(i);
int y = 7;
System.out.println( ++y *8);
char ch = 'a';
System.out.println(++ch);
}
}

You might also like